命令行批量建立 github 库

一个需求:如何批量建立 Github 帐号下的库。

Github 库通常的建立方式是通过网页,其次是通过 Github 客户端 Publish。

但这两种方式都无法批量建立库,每新建一个库都需要用户重复操作一遍。

查了一下,还真有这样的办法。Github 提供了 Restful API 来帮助企业管理代码库。不光是批量建立,还包括添加删除用户组等等,非常完善。就建库这一需求,Github 提供了这样的一个 API:

https://developer.github.com/v3/repos/

第5节就讲的是如何 Create 一个库,提供了非常详尽的设置参数:

Name Type Description
name string Required. The name of the repository
description string A short description of the repository
homepage string A URL with more information about the repository
private boolean Either true to create a private repository, or false to create a public one. Creating private repositories requires a paid GitHub account. Default: false
has_issues boolean Either true to enable issues for this repository, false to disable them. Default: true
has_wiki boolean Either true to enable the wiki for this repository, false to disable it. Default: true
has_downloads boolean Either true to enable downloads for this repository, falseto disable them. Default: true
team_id integer The id of the team that will be granted access to this repository. This is only valid when creating a repository in an organization.
auto_init boolean Pass true to create an initial commit with empty README. Default: false
gitignore_template string Desired language or platform .gitignore template to apply. Use the name of the template without the extension. For example, “Haskell”.
license_template string Desired LICENSE template to apply. Use the name of the template without the extension. For example, “mit” or “mozilla”.

当然其中大部分参数可以忽略,理论上只有库名是必须的。

所以使用以下命令就可以在不登录网站或者客户端的前提下建立一个库,通过 Sublime Text 等多行文本编辑软件(甚至通过 Excel)编辑一个多行批处理文件,然后运行即可:

1
2
3
4
5
curl -u "Github用户名:Github密码" https://api.github.com/user/repos -d '{"name":"库一名字"}'
curl -u "Github用户名:Github密码" https://api.github.com/user/repos -d '{"name":"库二名字"}'
curl -u "Github用户名:Github密码" https://api.github.com/user/repos -d '{"name":"库三名字"}'
curl -u "Github用户名:Github密码" https://api.github.com/user/repos -d '{"name":"库四名字"}'
curl -u "Github用户名:Github密码" https://api.github.com/user/repos -d '{"name":"库五名字"}'

库名重复时,Github 会自动报错,并不影响批处理继续执行。