1
1

More than 3 years have passed since last update.

gitのbranch名,tag名をpythonで取得する

Last updated at Posted at 2020-01-07

はじめに

機械学習系でmodelと中間生成ファイル,精度などの結果を同時に管理したいとき,Githubでbranchを切ってコードを管理するだけでなく,S3などのストレージを用いて管理したい欲が深いです。

既存のツール

既存のツールで同様の課題を解決したかったら,mlflowを使うのが良さそうです.

ただ,mlflowでversion管理するにせよ,flaskなどで自作管理アプリを開発するにせよ,gitのbranch名とS3のobject名は統一した方がいいという気持ちがありました.

また,過去に切ったreleaseタグにcheckoutして当時の推定値を再現したい欲もあります.

ということで現在のbranchと,remoteのreleaseタグを全取得するPythonコードを書きました.

import subprocess
import pandas as pd


def get_current_branch(repository_dir='./') -> str:
    '''現在のbranch名を取得
    Args:
        repository_dir(str): リポジトリのあるディレクトリ
    Return:
        str
    '''
    cmd = "cd %s && git rev-parse --abbrev-ref HEAD" % repository_dir
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait()
    stdout_data = proc.stdout.read()
    # stderr_data = proc.stderr.read()
    current_branch = stdout_data.decode('utf-8').replace('\n','')
    return current_branch


def get_remote_tags(repository='./') -> pd.core.frame.DataFrame:
    '''リモートのタグを取得する
    Args:
        repository(str): リポジトリのあるディレクトリ or リポジトリのURL(例: https://github.com/mlflow/mlflow )
    Returns:
        pd.core.frame.DataFrame
    Note:
        タグではなくbranchを取得したい場合は, cmdの'--tags'を'-h'に変更すれば良いです.
    '''
    if repository.startswith('https://github.com/'):
        cmd = "git ls-remote --tags %s" % repository
    else:
        cmd = "cd %s && git ls-remote --tags" % repository
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait()
    stdout_data = proc.stdout.read()
    # stderr_data = proc.stderr.read()
    if stdout_data:
        tag_df = pd.DataFrame([r.split('\t') for r in stdout_data.decode('utf-8').split('\n')], columns=['hash', 'tag_name'])
        return tag_df.dropna(how='any')
    else:
        print('cannot find tags.')
        return pd.DataFrame(columns=['hash', 'tag_name'])
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1