파이썬 스크립트에서 현재 자식 해시를 얻으십시오
파이썬 스크립트의 출력에 현재 git hash를 포함시키고 싶습니다 ( 해당 출력을 생성 한 코드 의 버전 번호 ).
파이썬 스크립트에서 현재 git hash에 어떻게 액세스 할 수 있습니까?
이 git describe
명령은 사람이 표현할 수있는 코드의 "버전 번호"를 작성하는 좋은 방법입니다. 설명서의 예제에서 :
git.git 현재 트리와 같은 것으로 다음을 얻습니다.
[torvalds@g5 git]$ git describe parent v1.0.4-14-g2414721
즉, "부모"브랜치의 현재 헤드는 v1.0.4를 기반으로하지만 그 위에 몇 개의 커밋이 있기 때문에, 추가 커밋 수 ( "14")와 커밋에 대한 약식 객체 이름을 추가했습니다. 끝에 자체 ( "2414721")가 있습니다.
Python 내에서 다음과 같은 작업을 수행 할 수 있습니다.
import subprocess
label = subprocess.check_output(["git", "describe"]).strip()
git
명령 에서 데이터를 가져 오는 것을 해킹 할 필요가 없습니다 . GitPython 은이 작업과 다른 많은 작업을 수행하는 매우 좋은 방법 git
입니다. Windows에 대한 "최선의 노력"을 지원합니다.
pip install gitpython
당신이 할 수있는 후
import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
이 게시물 에는 명령 이 포함되어 있으며 Greg의 답변 에는 하위 프로세스 명령이 포함되어 있습니다.
import subprocess
def get_git_revision_hash():
return subprocess.check_output(['git', 'rev-parse', 'HEAD'])
def get_git_revision_short_hash():
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])
numpy
멋진 멀티 플랫폼 루틴 이 있습니다 setup.py
.
import os
import subprocess
# Return the git revision as a string
def git_version():
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
return out
try:
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
GIT_REVISION = out.strip().decode('ascii')
except OSError:
GIT_REVISION = "Unknown"
return GIT_REVISION
하위 프로세스가 이식 가능하지 않고 간단한 작업을 수행하기 위해 패키지를 설치하지 않으려는 경우에도 수행 할 수 있습니다.
import pathlib
def get_git_revision(base_path):
git_dir = pathlib.Path(base_path) / '.git'
with (git_dir / 'HEAD').open('r') as head:
ref = head.readline().split(' ')[-1].strip()
with (git_dir / ref).open('r') as git_hash:
return git_hash.readline().strip()
나는 이것을 repos에서만 테스트했지만 꽤 일관되게 작동하는 것 같습니다.
다음은 Greg의 답변에 대한 완전한 버전입니다 .
import subprocess
print(subprocess.check_output(["git", "describe", "--always"]).strip().decode())
또는 리포지토리 외부에서 스크립트를 호출하는 경우 :
import subprocess, os
os.chdir(os.path.dirname(__file__))
print(subprocess.check_output(["git", "describe", "--always"]).strip().decode())
참고URL : https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script
'programing tip' 카테고리의 다른 글
C # 빈 문자열 배열 선언 (0) | 2020.06.27 |
---|---|
프로그래밍 방식으로 테이블 뷰 행 선택 (0) | 2020.06.27 |
CSS를 사용하여 배경 이미지 중심 맞추기 (0) | 2020.06.27 |
XOR이 해시를 결합하는 기본 방법 인 이유는 무엇입니까? (0) | 2020.06.27 |
ASP.NET 웹 API에서 다운로드 파일 이름을 설정하는 방법 (0) | 2020.06.27 |