LoginSignup
0
0

More than 5 years have passed since last update.

Rubyで作るGithubのadd~push効率化コマンド.

Last updated at Posted at 2019-03-25

前書き

Githubでは自分の活動状況を生い茂る草で表現しています.スクリーンショット 2019-03-25 10.10.06.png

実際にディレクトリに変更を加えて,pushするまでには以下の3つのコマンドを使用しています.

// Githubに連携しているディレクトリ内
// originに自作のリポジトリが登録されています.
$ git add -A
$ git commit -m "add icons"
$ git push origin master

この一連の流れ,生い茂る草で自分のモチベーションを維持できるのではないかと考える僕は,工程が多いよ!!とツッコミを入れたくなります.こまめにプッシュした方が良いと思うので,工程を減らしたいと考えました.

実装

機能としては,

// Githubに連携しているディレクトリ内
// originに自作のリポジトリが登録されています.
$ push_seq -A add icon

上記のコマンドで先ほどの3つのコマンドを自動で行ってくれます.
-Agit addのオプション指定です.
add_icongit commit -mのコメント文です.

実装したのは以下の様なコマンドです.

~bin/push_seq
#!/usr/bin/env ruby
require 'open3'
require 'shellwords'

add_opt = ARGV[0]
com_phrase = ARGV[1..-1].shelljoin                                                                              
add_opt = '-A' if add_opt.nil?
com_phrase = 'no_comment' if com_phrase.nil?

out, err, status = Open3.capture3("git remote -v")
out.split("\n").each do |line|
  if m = line.match(/^origin\s+git@(.+) \(push\)$/)
    puts m[1]
    system("git add #{add_opt}")
    system("git commit -m #{Shellwords.escape(com_phrase)}")
    system("git push origin master")
  else
    puts "Don't find origin branch."
  end
end 

簡単に説明をします.
add_optcom_phraseはそれぞれadd時のオプションとcommit時のコメントに相当しております.それぞれの引数に指定がない場合は,-Ano_commentが代入されます.
Open3にてgit remote -vを実行し,Githubに登録されているブランチ?を取得します.その後,そのブランチ内にoriginに対応するものがあるか確かめた後,3つのコマンドを実行します.

  • 注意点が2つあります
    1. commit時のコメント用に使用する第2引数には空白が入れることができない.(@sakuro様からのご指摘により解決いたしました.)
    2. branchに対応したpushができない.
  • 解決策
    1. 第2引数には_(アンダーバー)等を空白の代わりに使用する.
    2. 第3引数などをコード内に用意してpush時に使用すればよい.

(おまけ)僕の環境での自作コマンドの動かし方

Mac使ってます.
自作コマンドは~/binに入れています.
terminalのシェルはfishです.
自作コマンドはfishの設定ファイル~/.config/fish/config.fishにailiasとしてPathを記載.

~/.config/fish/config.fish
set PATH /usr/local/bin $PATH
alias push_seq '~/bin/push_seq'

これで使えるよ!

終わりに

毎度のことながら,何か思うところがあればご指摘お願いします.
ご指摘をいただけることで,僕も勉強になりますので助かっております.:boy_tone1:

0
0
4

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