How to create Repository using Github Rest API, Configure Visibility and Assign a Team as Readonly

April 16, 2021

Introduction

I had to create many repositories in an Github organization. I created an organization, and I had around 40 projects which I need to migrate from perforce to git.

We can repository from Github portal(UI), and it requires at least 6 clicks:

  1. Click on ’+’ button on left top
  2. Click on repository
  3. On left side, click your organization (by default your username is selected)
  4. Type project name
  5. Change visibility (public/private or internal)
  6. Click on checkbox for README.md
  7. Click create
  8. After creating, assign team permissions (3 clicks)

So total of 7+3=10 clicks per project So, for 40 projects I had to perform 40*10 = 400 clicks, which was unmanageable.

Requirements

My requirements are:

  • Create Repositories (with above mentioned settings)
  • Commit and Push project files

Pre-requisite

I synced those 40 folders to my local directory. Lets call it mylibs_ And, I have a team in github which I will assign permission to these projects.

Fetch Team_id

curl  -u USERNAME:TOKEN https://github.com/api/v3/repos/USERNAME/PROJECT/teams

Shell Script

Assumming following folders:

  • Target folder: mylibs
  • Original Project folder: mylibs_
AUTH="USERNAME:TOKEN"
for d in *;
do
  echo "Working on ${d}"
  curl -s -o /dev/null -w "%{http_code}" \
    -u ${AUTH} \
    -X POST \
    -H "Accept: application/vnd.github.v3+json" \
    https://github.com/api/v3/orgs/mylibs/repos \
    -d '{"name": "'${d}'", "visibility": "private", "private": "true", "auto_init": "true", "team_id": "TEAM_ID"}'

  echo "";
  git clone [email protected]:mylibs/${d}.git ../mylibs/${d}

  cp -R ${d}/* ../mylibs/${d}/

  cd ../mylibs/${d}/
  
  git add .
  git commit -m "Migration from P4 to git"
  git push
  echo ""
  echo "Done with ${d}"
  cd -
done

Create Github Authentication Token

Visit github page for How to create oAuth token{:target=“_blank”}

Note

Please note that the repositories created will be with visibility=private. And the team assigned to each repository will be having readonly access.


Similar Posts

Latest Posts