我创建了一个新的本地Git存储库:

~$ mkdir projectname
~$ cd projectname
~$ git init
~$ touch file1
~$ git add file1
~$ git commit -m 'first commit'

有没有任何git命令来创建一个新的远程回购,并从这里将我的提交推到GitHub ?我知道打开浏览器去创建一个新的存储库并不是什么大问题,但是如果有一种方法可以从CLI实现这一点,我会很高兴。

我读了大量的文章,但没有一篇提到如何使用git命令从CLI创建远程回购。Tim Lucas的一篇不错的文章“设置一个新的远程git存储库”是我找到的最接近的文章,但是GitHub不提供shell访问。


当前回答

如果您安装了defunkt的优秀Hub工具,那么这将变得非常简单

中心创建

用作者的话来说,“hub是git的命令行包装器,可以让你更好地使用GitHub。”

其他回答

你可以使用GitHub API通过命令行创建一个GitHub repo。检查存储库API。如果你向下滚动大约三分之一的方式,你会看到一个名为“创建”的部分,解释如何通过API创建一个回购(正上方是一个部分,解释如何用API派生一个回购)。显然你不能使用git来做这件事,但是你可以使用curl这样的工具通过命令行来做这件事。

在API之外,没有办法通过命令行在GitHub上创建一个repo。正如你所注意到的,GitHub不允许shell访问等,所以除了GitHub API,创建回购的唯一方法是通过GitHub的web界面。

github API v3的CLI命令(替换所有CAPS关键字):

curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
# Remember replace USER with your username and REPO with your repository/application name!
git remote add origin git@github.com:USER/REPO.git
git push origin master

基于Bennedich的回答,我创建了一个Git别名。在~/.gitconfig中添加以下命令:

[github]
    user = "your_github_username"
[alias]
    ; Creates a new Github repo under the account specified by github.user.
    ; The remote repo name is taken from the local repo's directory name.
    ; Note: Referring to the current directory works because Git executes "!" shell commands in the repo root directory.
    hub-new-repo = "!python3 -c 'from subprocess import *; import os; from os.path import *; user = check_output([\"git\", \"config\", \"--get\", \"github.user\"]).decode(\"utf8\").strip(); repo = splitext(basename(os.getcwd()))[0]; check_call([\"curl\", \"-u\", user, \"https://api.github.com/user/repos\", \"-d\", \"{{\\\"name\\\": \\\"{0}\\\"}}\".format(repo), \"--fail\"]); check_call([\"git\", \"remote\", \"add\", \"origin\", \"git@github.com:{0}/{1}.git\".format(user, repo)]); check_call([\"git\", \"push\", \"origin\", \"master\"])'"

要使用它,运行

$ git hub-new-repo

从本地存储库中的任何地方,并在提示时输入您的Github密码。

对于使用双因素身份验证的用户,您可以使用bennedich的解决方案,但您只需要为第一个命令添加X-Github-OTP报头。将CODE替换为从双因素身份验证提供程序获得的代码。将USER和REPO替换为存储库的用户名和名称,就像在他的解决方案中那样。

curl -u 'USER' -H "X-GitHub-OTP: CODE" -d '{"name":"REPO"}' https://api.github.com/user/repos
git remote add origin git@github.com:USER/REPO.git
git push origin master

对于所有的Python 2.7。*用户。目前版本3的Github API有一个名为GitPython的Python包装器。只需使用easy_install PyGithub或pip install PyGithub安装即可。

from github import Github
g = Github(your-email-addr, your-passwd)
repo = g.get_user().user.create_repo("your-new-repos-name")

# Make use of Repository object (repo)

Repository对象文档在这里。