Search code examples
gitazurebitbucketlibgit2sharp

C# Push Files to Bitbucket repository from an Azure App Service?


I want to push files from a folder on Azure App Service to a Git repository.

I have copied the local git repo up to the server and I'm using LibGit2Sharp to commit and push these files:

using (var repo = new Repository(@"D:\home\site\wwwroot\repo"))
{
    // Stage the file
    Commands.Stage(repo, "*");

    // Create the committer's signature and commit
    Signature author = new Signature("translator", "example.com", DateTime.Now);
    Signature committer = author;

    // Commit to the repository
    Commit commit = repo.Commit($"Files updated {DateTime.Now}", author, committer);

    Remote remote = repo.Network.Remotes["origin"];
    var options = new PushOptions
    {
        CredentialsProvider = (_url, _user, _cred) =>
            new UsernamePasswordCredentials
            {
                Username = _settings.UserName,
                Password = _settings.Password
            }
    };
    repo.Network.Push(remote, @"+refs/heads/master", options);
}

It works, but seems to take a while and and this seems a bit clunky. Is there a more efficient way to achieve this via code, or perhaps directly via Azure (config or Azure Functions)?


Solution

  • In case of Azure Apps you can still bundle embedded exes, There a portable Git available on below link

    https://github.com/sheabunge/GitPortable

    You should bundle that with your app and create a batch file as well. And then you should launch it using C# code

    static void ExecuteCommand(string command)
    {
        var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
        processInfo.CreateNoWindow = true;
        processInfo.UseShellExecute = false;
        processInfo.RedirectStandardError = true;
        processInfo.RedirectStandardOutput = true;
    
        var process = Process.Start(processInfo);
    
        process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
            Console.WriteLine("output>>" + e.Data);
        process.BeginOutputReadLine();
    
        process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
            Console.WriteLine("error>>" + e.Data);
        process.BeginErrorReadLine();
    
        process.WaitForExit();
    
        Console.WriteLine("ExitCode: {0}", process.ExitCode);
        process.Close();
    }
    

    PS: Credits Executing Batch File in C#

    Another SO thread that talk about something similar

    Azure App Service, run a native EXE to convert a file

    How to run a .EXE in an Azure App Service

    Run .exe executable file in Azure Function