LoginSignup
1
0

More than 5 years have passed since last update.

Vimで編集中のファイルのGitホスティングサービス上のURLを取得する

Posted at

障害発生時や実装時など、手元のエディタで開いているファイルのGitホスティングサービス上のURLを、Slackで共有したい時があるかもしれません。

私の場合、Vimを使っていてBitbucketのURLを共有したいというケースがありました。
それに対し、Vim scriptで GitUrl というコマンドを追加し、 .git/config の設定を元にURLを出力するようにしました。

以下にそのscriptと、補足を記載します。

追加したVim script

  function! GitUrl()
    let l:TEMPLATE = 'https://example.com/projects/__PROJECT__/repos/__REPOSITORY__/browse/__PATH__'

    let l:project    = system('git remote get-url origin | sed "s/\// /g" | awk ''{print $(NF-1)}'' | tr -d "\n"')
    let l:repository = system('git remote get-url origin | sed "s/\// /g" | awk ''{print $(NF)}'' | sed "s/.git$//" | tr -d "\n"')
    let l:path       = system('git rev-parse --show-prefix | tr -d "\n"') . expand('%')
    let l:remote_url = substitute(substitute(substitute(l:TEMPLATE, '__PROJECT__', l:project, ''), '__REPOSITORY__', l:repository, ''), '__PATH__', l:path, '')

    echo l:remote_url
  endfunction
  command! GitUrl call GitUrl()

例えば railstutorial プロジェクトの hello_app リポジトリの app/controllers/application_controller.rb を開いている場合、 :GitUrl を実行すると、以下のURLを出力します。

https://example.com/projects/railstutorial/repos/hello_app/browse/app/controllers/application_controller.rb

scriptの補足

  • Bitbucketはプロジェクトの下にリポジトリが所属する構成を期待しています。
  • git remote get-url origin で取得するURLは、SSH URLを期待しています。URLからプロジェクト名とリポジトリ名を取得します。
    • 上記例では ssh://git@example.com/railstutorial/hello_app.git
  • git rev-parse --show-prefix でルートディレクトリからの相対パスを取得し、 expand('%') で編集中のファイルの名前を追加し、パスを作成します。

GitHub以外のGitホスティングサービスを利用する場合、エディタ上でURLを取得するプラグインやエクステンションが探しづらいかもしれません。そういう場合に10行程度のVim scriptでしのげるのがよいと思いました。

1
0
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
0