DEV Community

Cover image for Make peace with github using powershell
Abhik Ghosh
Abhik Ghosh

Posted on

Make peace with github using powershell

I am sure, you could relate to this pain of doing a repetitive set of tasks when you start a new project on your machine. Following are the typical tasks a developer do, no matter which language, framework or IDE they are using.

Step 1: Create a project directory or make use of a CLI generator to create the project structure
Step 2: On browser, open github.com and create repository using UI
Step 3: Create local repository if CLI hasn't already been created
Step 4: Add the remote(Github) repository, do an initial commit and push

Well, I wish step 2 is allowed to be done using the git cli someday. But as of today, there is no way one can create a repository without going to the browser and manually creating the same using UI. So, here is my solution which works great and saves me from repeating myself again and again. I use a Windows Computer and love powershell for this sort of automation scripts. I created a powershell function, when invoked, it uses Github Rest API to create a new repository and also does the initial commit for my empty project README.MD file. I have documented the steps below just in case you are looking for a reference. You can use the script as is and you are free to modify this to fit your need.

Here is the powershell solution:

Start here: create your github access token - https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
Place the access token in a file called config with a prefix as below:
Add Access Token

Preferably at the same path where the config file is saved, create powershell script New-Repo.ps1. This name can be anything else as you wish it to be. The following is the basic structure of the script with three parameters: RepoName, UserName and ConfigFile.

function New-Repo {

     [CmdletBinding()]
     Param(
         [Parameter(Mandatory = $true)]
         $RepoName,
         [Parameter(Mandatory = $true)]
         $UserName,
         $ConfigFile = "C:\Users\abhik\Documents\dev-env\powershell\GitAutomation\config" ## Default config file location
    )
 }
Enter fullscreen mode Exit fullscreen mode

Add the following code to retrieve the access token from the config file


##### Read Github Access Token #####
 $fileContent = Get-Content -Path $ConfigFile

 $accessToken = ''
 foreach ($line in $fileContent) {
     if ($line.Contains('PERSONAL_ACCESS_TOKEN')) {
        $accessToken = $line -replace ".*="
     }
 }

Enter fullscreen mode Exit fullscreen mode

Make a POST call to github repo rest endpoint https://api.github.com/user/repos:

##### Prepare Github API Post call #####
 $user = $UserName
 $pass = $accessToken
 $pair = "$($user):$($pass)"

 $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
 $basicAuthValue = "Basic $encodedCreds"
 $Headers = @{
    Authorization = $basicAuthValue
 }
 $body = @{
     name    = $RepoName
     accept  = 'application/vnd.github.v3+json'
     private = $false
 }

 $bodyJson = ConvertTo-Json $body
 Write-Output "Posting Data: "$bodyJson
 $response = Invoke-WebRequest -Method 'POST' -Uri 'https://api.github.com/user/repos' -Headers $Headers -Body $bodyJson

 $responseJson = $response | ConvertFrom-Json
 Write-Output "Repo : $($responseJson.html_url) Created!"
Enter fullscreen mode Exit fullscreen mode

Last and final step is to initialize a local git repo and do the initial commit.

##### Create local repo and sync remote #####
 Write-Output "Creating local repo..."
 git init
 New-Item -Path .\README.MD 
 git add README.MD
 git commit -m 'initial commit -setup with powershell script'

 Write-Output "Syncing remote..."
 git remote add origin "$($responseJson.html_url).git"
 git push --set-upstream origin master
Enter fullscreen mode Exit fullscreen mode

Now, to be able to access this function on a powershell shell, I added the function in the powershell profile. Here is how to add the function to your profile.

Open the profile using notepad.exe $PROFILE. This will prompt you to create the profile file(accept it) if you are using the profile for the first time. Once the profile is created, add the following line . C:\dev-env\powershell\GitAutomation\New-Repo.ps1. Please note, the dot(.) at the beginning of the line is important. It instructs powershell to keep the function in memory.

And that should do. Restart the powershell terminal and you should be able to call New-Repo function within your project root folder. Pass on the repo name along with the github username. Then, powershell will do its thing and you'll save yourself few seconds of manual work. As a developer, I think we should save time even if it is a few second 🙂 because we are lazy.

Output

Conclusion

The above code blocks outlines the powershell way of doing this automation. But the idea can easily be extended for a shell script. I use this script on a regular basis. More than time, it saved me from context switch we programmers do not like that much.

Full Code is available here: https://github.com/abhgho/git-powershell-automation/blob/main/New-Repo.ps1


Photo by Roman Synkevych on Unsplash

Discussion (0)