Make peace with github using powershell
Tags: powershell, github, automation, productivity
Published: 2021-11-07 08:33:41

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjvws4ys80lb2df3ldeu.png)

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. 
```powershell
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
 	)
 }
```

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

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

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

Make a POST call to github repo rest endpoint `https://api.github.com/user/repos`:
```powershell
##### 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!"
```

Last and final step is to initialize a local git repo and do the initial commit. 
```powershell
##### 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
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e747k9hpylvl0o8m0ncu.png)

#### 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 <a href="https://unsplash.com/@synkevych?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Roman Synkevych</a> on <a href="https://unsplash.com/s/photos/github?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>