日: 2018年10月17日

  • GitLabでCLI経由でmerge requestを送る

    GitLabでCLI経由でmerge requestを送る

    はじめに

    GitLabでコマンドベースでmerge requestを作成する。
    postでAPIを叩いていろいろ設定すればそれでも可能だけど、python-gitlabというpython製のツールがとても便利だったので紹介。

    使い方

    pipでpython-gitlabをインストール

    pip install --upgrade python-gitlab

    vi ~/.python-gitlab.cfg

    [global]
    default = somewhere
    ssl_verify = true
    timeout = 5
    
    [somewhere]
    url = https://gitlab.com
    private_token = xXxxxxxxxxxxxxxxxxx
    api_version = 4

    ここで必要になるprivate_tokenはGitLabのユーザ画面から作成することが可能

     

    mergeするスクリプトを作成

    import os
    import gitlab
    
    hostname = '%s' % os.uname()[1]
    
    # gitlabへのURLを入れる
    gl = gitlab.Gitlab('https://gitlab.com/', private_token='xxxxxxxxxxx')
    gl.auth()
    
    # プロジェクト番号をgitlabを調べる
    project = gl.projects.get(123, lazy=True)
    
    mr = project.mergerequests.create({'source_branch': (hostname),
                                       'target_branch': 'master',
                                       'title': (hostname) + ' user list'
                                       })
    
    mrs = project.mergerequests.list(state='opened', order_by='updated_at')[0]
    
    print(mrs.attributes['web_url'])

    実行

    $python merge.py 
    https://gitlab.com/infra/redash-user/merge_requests/30

    作られたmerge requestのページへのリンクが表示される。

    チャットやメールでこのリンクをreviewerに知らせれば、フローも簡略化できる。

    詳しい使い方はこちら

    https://python-gitlab.readthedocs.io/en/stable/index.html