Search code examples
c#gitpowershellazure-devopscommand

HOW TO - Connect to DevOps Uninitialized Git Repository (git remote add origin to uninitialized repo)


I am creating a Project with git on DevOps using API. By default DevOps creates a git repository with same same name as project. I already have a project on my local machine and want to connect to that git repo and push it there.

How can I do that? Please help.

P.S. : I have to do it programmatically with C# code.

Thanks in Advance.


Solution

  • Short answer

    You have to add the proper git remote, found on the initial project repo page.

    Longer answer

    After creating a new project, the repo page looks like this: new project in azdo

    The second block contains the code for getting adding existing repo from command line. Let's say I have this local folder at C:\work\githubtest and just follow the commands above. For the example I'm showing above the red rectangle:

    • what is in the folder; README-local.MD
    • what I committed; the file above

    add local repo

    The suggested commands from the rectangle and the screenshot are:

    git remote add origin https://yourorg@dev.azure.com/yourorg/GithubTest/_git/GithubTest
    git push -u origin --all
    

    The result

    the result in AzDo

    In C#

    So, your question is how to do this programmatically, in C#? Well the part of the git command is asked and answered here This could look in your example something like:

    string directory = ""; // directory of the git repository
    
    using (PowerShell powershell = PowerShell.Create()) {
        // this changes from the user folder that PowerShell starts up with to your git repository
        powershell.AddScript($"cd {directory}");
    
        powershell.AddScript(@"git remote add origin https://yourorg@dev.azure.com/yourorg/GithubTest/_git/GithubTest");
        powershell.AddScript(@"git push -u origin --all");
    
        Collection<PSObject> results = powershell.Invoke();
    }