programing

브라우저를 열지 않고 CLI에서 GitHub에 대한 원격 응답을 만들 수 있습니까?

showcode 2023. 6. 4. 10:47
반응형

브라우저를 열지 않고 CLI에서 GitHub에 대한 원격 응답을 만들 수 있습니까?

새 로컬 Git 저장소를 만들었습니다.

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

원격 레포를 만들고 여기서 GitHub에 대한 내 커밋을 푸시하는 git 명령이 있습니까?브라우저를 실행하고 새 리포지토리 만들기로 넘어가는 것이 큰 문제가 아니라는 것을 알고 있습니다. 하지만 CLI에서 이를 달성할 수 있는 방법이 있다면 매우 기쁠 것입니다.

방대한 양의 기사를 읽었지만 git 명령을 사용하여 CLI에서 원격 레포를 만드는 방법에 대해 언급한 기사는 없습니다.팀 루카스의 멋진 기사원격 저장소 설정이 제가 찾은 것 중 가장 가깝지만 깃허브는 셸 액세스를 제공하지 않습니다.

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

GitHub API를 사용하여 명령줄을 통해 GitHub repo를 생성할 수 있습니다.리포지토리 API를 확인하십시오.약 3분의 1 정도 아래로 스크롤하면 API를 통해 레포를 만드는 방법을 설명하는 "만들기" 섹션이 나타납니다(바로 위에는 API로 레포를 포크하는 방법도 설명하는 섹션이 있습니다).분명히 당신은 사용할 수 없습니다.git이 작업을 수행하려면 다음과 같은 도구를 사용하여 명령줄을 통해 수행할 수 있습니다.curl.

API 외부에서는 명령줄을 통해 GitHub에 대한 평판을 생성할 수 없습니다.GitHub은 당신이 언급한 것처럼 셸 액세스 등을 허용하지 않으므로 GitHub API 외에 repo를 생성할 수 있는 유일한 방법은 GitHub의 웹 인터페이스를 통해서입니다.

이 작업은 다음 세 가지 명령을 사용하여 수행할 수 있습니다.

curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
git remote add origin git@github.com:nyeates/projectname.git
git push origin master

(v3 Github API용으로 업데이트됨)


이 명령에 대한 설명...

github repo 작성

    curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
  • curl은 URL을 검색하고 상호 작용하는 Unix 명령(Mac에서도 작동함)입니다.일반적으로 이미 설치되어 있습니다.
  • 는 서버 입니다."-u"는 서버 인증에 사용할 사용자 이름과 비밀번호를 지정합니다.
    • 위의 예와 같이 사용자 이름만 지정하면 curl이 암호를 묻는 메시지를 표시합니다.
    • 암호를 입력하지 않으려면 인증의 githubs api 설명서를 참조하십시오.
  • "-d"는 요청과 함께 POST 데이터를 보낼 수 있는 컬 매개 변수입니다.
    • githubs 정의 API 형식으로 POST 데이터를 보내고 있습니다.
  • 필요한 POST 데이터는 "name"뿐입니다. "description"도 포함하고 싶습니다.
  • 저는 모든 POST 데이터를 인용할 때 ' '라는 단일 따옴표를 사용하는 것이 좋다는 것을 알게 되었습니다.

푸시할 위치 정의

git remote add origin git@github.com:nyeates/projectname.git
  • 연결된(원격) 복제 허브의 위치 및 존재에 대한 정의 추가
  • "filename"은 소스가 어디에서 왔는지에 대해 git에서 사용하는 기본 이름입니다.
    • 엄밀히 말하면 깃허브에서 나온 것은 아니지만, 이제 깃허브 레포는 기록의 원천이 될 것입니다.
  • "git@github.com :nyeats"는 github과 신뢰할 수 있는 ssh 키 쌍을 이미 설정했다고 가정하는 ssh 연결입니다.

로컬 보고서를 github에 푸시

git push origin master
  • 마스터 로컬 분기에서 오리진 원격(github)으로 푸시

만약 당신이 디펑크의 훌륭한 허브 도구를 설치한다면, 이것은 다음과 같이 쉬워집니다.

hub create

저자의 말에 따르면, "허브는 깃허브를 잘하게 해주는 깃을 위한 명령줄 래퍼입니다."

Github의 공식적인 새로운 명령줄 인터페이스:

gh repo create

자세한 내용과 옵션설치 지침을 참조하십시오.


예를 들어 Git 워크플로우를 완료하려면 다음을 수행합니다.

mkdir project
cd project
git init
touch file
git add file
git commit -m 'Initial commit'
gh repo create
git push -u origin master

단계(간단사한단계(용)사▁((단())▁simpleusing계)git+hub=> GitHub):

  1. 허브(GitHub)를 설치합니다.

    • OS X:brew install hub
    • 바둑 두기:go get github.com/github/hub
    • 그렇지 않은 경우(Go도 있음):

      git clone https://github.com/github/hub.git && cd hub && ./script/build
      
  2. 하거나 빈.mkdir foo && cd foo && git init.

  3. 실행:hub create처음으로 GitHub 자격 증명에 대해 묻습니다.

    용도:hub create [-p] [-d DESCRIPTION] [-h HOMEPAGE] [NAME]

    예:hub create -d Description -h example.com org_name/foo_repo

    를 "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "OAuth토큰, 저니다됩에 됩니다.~/.config/hub.

    하려면 새리지토이명시전지달면정려하로으를 합니다.NAME으로 선적으로로ORGANIZATION/NAME사용자가 구성원인 조직 아래에 작성할 양식입니다.

    와 함께-p사용하여 합니다.-d그리고.-hURL각각 다음과 같다.

    메시지가 표시되지 않도록 하려면 다음을 사용합니다.GITHUB_USER그리고.GITHUB_PASSWORD환경 변수

  4. 그런 다음 평소처럼 커밋하고 푸시하거나 확인합니다.hub commit/hub push.

추가 도움말을 보려면 다음을 실행하십시오.hub help.

참고 항목:GitHub에서 명령줄을 사용하여 Git 저장소 가져오기

제 생각에, 이것을 하는 공식적인 github 보석이 있습니다.배우면서 더 많은 정보를 추가하려고 노력하겠지만, 저는 이 보석을 발견한 지 얼마 되지 않아서 아직 많은 것을 알지 못합니다.

설정한 후 를 통해 새로운 할 수 .create명령어인 명령나사수없습다니용을 할 수 없습니다.create-from-local명령. 현재 로컬 repo를 가져와서 github에서 해당 원격을 생성해야 합니다.

$ gh create-from-local
=> error creating repository

이에 대한 통찰력을 가진 사람이 있다면 제가 무엇을 잘못하고 있는지 알고 싶습니다.이미 제출된 문제가 있습니다.

업데이트: 결국 이 작업을 수행하게 되었습니다.문제를 어떻게 재현할지는 정확히 알 수 없지만 처음부터 시작했습니다(.git 폴더 삭제).

git init
git add .emacs
git commit -a -m "adding emacs"

이 줄은 원격 레포를 생성하고 푸시하기도 하지만 안타깝게도 제가 원하는 레포의 이름을 지정할 수 없을 것 같습니다.저는 그것을 github에서 "dot files"라고 부르고 싶었지만, ghost는 제가 홈 폴더에 있을 때부터 "jason"이었던 현재 폴더의 이름을 사용했습니다.(원하는 동작을 요청하는 티켓을 추가했습니다)

gh create-from-local

그러나 이 명령은 원격 repo의 이름을 지정하는 인수를 수락하지만 새 프로젝트를 처음부터 시작하기 위한 것입니다. 즉, 이 명령을 호출한 후 현재 위치와 관련하여 새로 생성된 하위 폴더에서 로컬 repo를 추적하는 새 원격 repo를 얻습니다.둘 다 인수로 지정된 이름을 사용합니다.

gh create dotfiles

Bash 셸을 사용하여 원격 저장소를 신속하게 생성하려면 다음과 같이 하십시오.

리포지토리를 만들 때마다 전체 코드를 입력하는 것이 번거롭습니다.

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

더 쉬운 방법은 다음과 같습니다.

  1. "/에 셸 githubscript.sh
  2. 하여 다음코여저장다니합으로 합니다.githubscript.sh 파일
#!bin/bash
curl -u 'YOUR_GITHUB_USER_NAME' https://api.github.com/user/repos -d "{\"name\":\"$1\"}";
git init;
git remote add origin git@github.com:YOUR_GITHUB_USER_NAME/$1.git;

N.B.변경을 호출할 전달되는 항목은 다음과 같습니다.YOUR_GITHUB_USER_NAME스크립트를 저장하기 전에.

  1. 을 에대필 권설정으로 합니다.script 파일 chmod 755 githubscript.sh

  2. 환경 구성 파일에 스크립트 디렉터리를 포함합니다. nano ~/.profile; export PATH="$PATH:$HOME/Desktop/my_scripts"

  3. 또한 githubscript를 실행할 별칭을 설정합니다.sh 파일. nano ~/.bashrc; alias githubrepo="bash githubscript.sh"

  4. 이제 다시 로드합니다..bashrc그리고..profile파일들이 터미널에 있습니다. source ~/.bashrc ~/.profile;

  5. 이제 새 리포지토리를 만듭니다. demo: githubrepo demo;

지금까지 받아들여진 답변과 가장 많이 투표한 답변 모두 구식입니다.비밀번호 인증은 더 이상 사용되지 않으며 2020년 11월 13일 16:00 UTC에 삭제될 예정입니다.

GitHub API를 사용하는 방법은 개인 액세스 토큰을 사용하는 것입니다.

다음 작업을 수행해야 합니다(모든 CAPS 키워드 대체).

  1. 사이트를 통해 개인 액세스 토큰을 만듭니다.예, 브라우저를 사용해야 하지만 이후 모든 액세스에 한 번만 사용할 수 있습니다.토큰을 안전하게 저장합니다.
  2. 레포비아 생성
curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos  -d '{"name":"REPO"}'

또는 처음부터 비공개로 설정하려면 다음을 수행합니다.

curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}'
  1. 새 오리진을 추가하고 푸시합니다.
git remote add origin git@github.com:USER/REPO.git
git push origin master

이는 토큰을 매번 입력해야 하는 단점이 있으며, bash 기록에 표시됩니다.

이를 방지하려면 다음과 같이 하십시오.

  1. 합니다( 헤더파저예장다니합일에를예(▁it:다▁store니▁(합저▁in).HEADER_FILE)
Authorization: token MY_ACCESS_TOKEN
  1. 파일에서 컬을 읽습니다.
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo
  1. 보안을 강화하기 위해 액세스 권한을 400으로 설정하고 사용자를 루트로 설정할 수 있습니다.
chmod 400 HEADER_FILE
sudo chown root:root HEADER_FILE
  1. 이제 헤더 파일에 액세스하려면 sudo가 필요합니다.
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo

@Mechanical Snail의 다른 답변에 따르면, 제가 엄청나게 과잉 살상을 하는 것으로 판명된 파이썬을 사용하지 않은 것을 제외하고는.을 당신의 니추합다에 추가하세요.~/.gitconfig:

[github]
    user = "your-name-here"
[alias]
    hub-new-repo = "!REPO=$(basename $PWD) GHUSER=$(git config --get github.user); curl -u $GHUSER https://api.github.com/user/repos -d {\\\"name\\\":\\\"$REPO\\\"} --fail; git remote add origin git@github.com:$GHUSER/$REPO.git; git push origin master"

아니요, 브라우저를 적어도 한 번은 열어야 합니다.usernameGitHub에서 생성되면 GitHub API를 활용하여 다음 명령을 사용하여 명령줄에서 리포지토리를 만들 수 있습니다.

curl -u 'github-username' https://api.github.com/user/repos -d '{"name":"repo-name"}'

예:

curl -u 'arpitaggarwal' https://api.github.com/user/repos -d '{"name":"command-line-repo"}'

20200714 업데이트

Github에는 새로운 공식 CLI가 있습니다.

...gh는 공식 GitHub CLI 툴이 근본적으로 다른 디자인으로 어떻게 보일 수 있는지 살펴볼 수 있도록 지원하는 새로운 프로젝트입니다.두 도구 모두 GitHub를 터미널로 가져오는 반면 허브는 Git에 대한 프록시 역할을 하며 gh는 독립 실행형 도구입니다.

허브와의 핵심적인 차이점은 이것이 기존 git 명령을 덮어쓰지 않는다는 것입니다.따라서 허브를 사용할 때처럼 별칭을 지정할 수 없습니다.

GitHub CLI를 GitWrapper가 아닌 자체 명령어로 설계하기로 했기 때문에 Hub에 추가하지 않았습니다.Git에 대한 프록시인 실행 파일을 유지하는 것은 어려운 일이며 Git 호환성을 항상 유지해야 함으로써 제한을 받고 싶지 않았습니다.우리는 처음부터 취약한 패러다임을 기반으로 GitHub CLI를 구축하고 싶지 않았습니다.

mislav (허브 유지관리자)

원답

허브가 필요합니다.허브는 git에 대한 명령줄 래퍼입니다.별칭을 사용하여 네이티브 깃과 통합되도록 만들어졌습니다.새 리포지토리 만들기를 포함하여 github 작업을 git에 제공하려고 합니다.

→  create a repo for a new project
$ git init
$ git add . && git commit -m "It begins."
$ git create -d "My new thing"
→  (creates a new project on GitHub with the name of current directory)
$ git push origin master

마지막으로 GitHub이 모든 핵심 기능에 대한 새로운 CLI를 공식적으로 발표했습니다.

여기서 확인하세요: https://cli.github.com/

HomeBrew를 통해 설치하기brew install gh기타 방법: https://github.com/cli/cli#installation

그리고나서

gh repo create

기타 사용 가능한 기능.

$ gh --help

Work seamlessly with GitHub from the command line.

USAGE
  gh <command> <subcommand> [flags]

CORE COMMANDS
  gist:       Create gists
  issue:      Manage issues
  pr:         Manage pull requests
  release:    Manage GitHub releases
  repo:       Create, clone, fork, and view repositories

ADDITIONAL COMMANDS
  alias:      Create command shortcuts
  api:        Make an authenticated GitHub API request
  auth:       Login, logout, and refresh your authentication
  completion: Generate shell completion scripts
  config:     Manage configuration for gh
  help:       Help about any command

FLAGS
  --help      Show help for command
  --version   Show gh version

EXAMPLES
  $ gh issue create
  $ gh repo clone cli/cli
  $ gh pr checkout 321

ENVIRONMENT VARIABLES
  See 'gh help environment' for the list of supported environment variables.

LEARN MORE
  Use 'gh <command> <subcommand> --help' for more information about a command.
  Read the manual at https://cli.github.com/manual

FEEDBACK
  Open an issue using 'gh issue create -R cli/cli'

이제 터미널에서 레포를 만들 수 있습니다.

2단계 인증을 사용하는 사용자의 경우 bennedich의 솔루션을 사용할 수 있지만 첫 번째 명령에 X-Github-OTP 헤더를 추가하기만 하면 됩니다.CODE를 2단계 인증 공급자로부터 받은 코드로 대체합니다.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

GitHub 및 BitBucket용 REST API를 사용하여 Gitter라는 이름의 멋진 스크립트를 작성했습니다.

https://github.com/dderiso/gitter

비트 버킷:

gitter -c -r b -l javascript -n node_app

GitHub:

gitter -c -r g -l javascript -n node_app
  • -c
  • -r 공급자b = repo 파일(g = GitHub, b = 비트버킷)
  • -n
  • -l합니다.

루비스트의 경우:

gem install githubrepo
githubrepo create *reponame*

사용자 이름을 입력하고 pw 메시지가 표시됩니다.

git remote add origin *ctrl v*
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오브젝트 문서가 여기 있습니다.

토큰을 만드는 방법은 여기로 이동합니다. 이 명령을 입력합니다(이 응답 날짜 기준).(모든 CAPS 키워드 대체):

curl -u 'YOUR_USERNAME' -d '{"scopes":["repo"],"note":"YOUR_NOTE"}' https://api.github.com/authorizations

암호를 입력하면 토큰이 포함된 다음 항목이 표시됩니다.

{
  "app": {
    "name": "YOUR_NOTE (API)",
    "url": "http://developer.github.com/v3/oauth/#oauth-authorizations-api"
  },
  "note_url": null,
  "note": "YOUR_NOTE",
  "scopes": [
    "repo"
  ],
  "created_at": "2012-10-04T14:17:20Z",
  "token": "xxxxx",
  "updated_at": "2012-10-04T14:17:20Z",
  "id": xxxxx,
  "url": "https://api.github.com/authorizations/697577"
}

여기로 이동하여 언제든지 토큰을 해지할 수 있습니다.

베네딕의 답변을 토대로 이 일을 하기 위해 깃의 별칭을 만들었습니다.다음을 추가합니다.~/.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 암호를 입력합니다.

마음에 드는 이 솔루션을 찾았습니다. https://medium.com/ @haviorhasler/명령줄에서 원격 Git-repo를 만드는 방법-2d6857f49564

먼저 Github 개인 액세스 토큰을 만들어야 합니다.

즐겨찾는 텍스트 편집기에서 ~/.bash_profile 또는 ~/.bashrc를 엽니다.파일의 맨 위에 다음 줄을 추가합니다. 여기서 내보낸 변수의 나머지는 다음과 같습니다.

export GITHUB_API_TOKEN=<your-token-here>

아래의 다른 bash 함수를 사용하여 다음과 유사한 것을 붙여넣을 수 있습니다.

function new-git() {
    curl -X POST https://api.github.com/user/repos -u <your-username>:$GITHUB_API_TOKEN -d '{"name":"'$1'"}'
}

만 명 실 수 있 다 니 할 습 행 을 령 다 때 들 트 를 니 ▁command 다 있 습 ▁now ▁the 수 , ▁run 실 ▁you ▁a ▁can 할 이$ new-git awesome-repoGithub 사용자 계정에 새 공용 원격 리포지토리를 만듭니다.

디스카밀러:저는 오픈 소스 프로젝트의 저자입니다.

이 기능은 https://github.com/chrissound/Human-Friendly-Commands 에서 지원됩니다. 기본적으로 다음 스크립트입니다.

#!/usr/bin/env bash

# Create a repo named by the current directory
# Accepts 1 STRING parameter for the repo description
# Depends on bin: jq
# Depends on env: GITHUB_USER, GITHUB_API_TOKEN
github_createRepo() {
  projName="$(basename "$PWD")"
  json=$(jq -n \
    --arg name "$projName" \
    --arg description "$1" \
    '{"name":$name, "description":$description}')

  curl -u "$GITHUB_USER":"$GITHUB_API_TOKEN" https://api.github.com/user/repos -d "$json"
  git init
  git remote add origin git@github.com:"$GITHUB_USER"/"$projName".git
  git push origin master
};

다른 이유로 설명으로 추가할 수 없지만(베네딕의 답변과 함께 사용하는 것이 더 좋습니다) Windows 명령줄의 경우 올바른 구문은 다음과 같습니다.

curl -u YOUR_USERNAME https://api.github.com/user/repos -d "{\"name\":\"당신의_REPO_NAME\"}"

기본 형식은 같지만 싱글 대신 큰따옴표(")를 사용해야 하며, POST 매개변수(-d 플래그 뒤)에 전송된 큰따옴표는 백슬래시로 이스케이프해야 합니다.제 사용자 이름 주위의 작은 따옴표도 제거했지만, 사용자 이름에 공백이 있다면 가능합니까?아마도 큰따옴표가 필요할 것입니다.

여기에 내 초기 git 명령이 있습니다(따라서, 이 동작은 다음에서 발생합니다).C:/Documents and Settings/your_username/):

mkdir ~/Hello-World
# Creates a directory for your project called "Hello-World" in your user directory
cd ~/Hello-World
# Changes the current working directory to your newly created directory
touch blabla.html
# create a file, named blabla.html
git init
# Sets up the necessary Git files
git add blabla.html
# Stages your blabla.html file, adding it to the list of files to be committed
git commit -m 'first committttt'
# Commits your files, adding the message 
git remote add origin https://github.com/username/Hello-World.git
# Creates a remote named "origin" pointing at your GitHub repository
git push -u origin master
# Sends your commits in the "master" branch to GitHub

명령줄에 새 리포지토리 생성

echo "# <RepositoryName>" >> README.md

git init

git add README.md

git commit -m "first commit"

git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git

git push -u origin master

명령줄에서 기존 리포지토리 푸시

git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git

git push -u origin master

언급URL : https://stackoverflow.com/questions/2423777/is-it-possible-to-create-a-remote-repo-on-github-from-the-cli-without-opening-br

반응형