LoginSignup
5
5

More than 5 years have passed since last update.

使用頻度の低い Git のエイリアスを見つける

Posted at

いろいろなところで便利な Git のエイリアスを見つけて ~/.gitconfig に追加する生活を送っていると、あまり使わない死んだエイリアスが積もっていくことになります。

不要な設定を取り除くことができれば設定をコンパクトかつ本当に使われている設定のみが残り、自分の設定の価値が向上します。

そこであまり使わない git のエイリアスを可視化してみます。

history_shell.rb

history_shell.rb
module History
  module Shell
    def zsh_history_file
      @zsh_history_file ||= File.expand_path('~/.zsh_history')
    end

    def zsh_history
      @zsh_history ||= File.read(zsh_history_file)
    end

    def encoded_zsh_history
      @encoded_zsh_history ||= zsh_history.encode('UTF-8', 'ASCII-8BIT', undef: :replace, invalid: :replace, replace: '')
    end

    def history
      @history ||= encoded_zsh_history.split(/\n/).map(&:strip)
    end

    def command_lines
      @command_lines ||= history.map {|line| line.split(';').last.strip }
    end

    def command_history(pattern = nil)
      (pattern ? command_lines.grep(pattern) : command_lines).map {|command_line| command_line.split(/\s+/) }
    end
  end

  module Statistics
    def stats(population, keys)
      Hash[keys.map {|key| [key, population.count(key)] }]
    end
  end

  module Git
    include Shell
    include Statistics

    extend self

    def git_command_history
      @git_command_history ||= command_history(/^git\s/)
    end

    def git_subcommands
      @git_subcommands ||= git_command_history.map {|command| command.find {|element| element != 'git' && /^\w/ === element } }.compact
    end

    def git_subcommands_stats
      stats(git_subcommands, git_subcommands.uniq)
    end

    def git_aliases
      @git_aliases ||= `git config --global --list | grep '^alias[.]' | cut -d. -f2 | cut -d= -f1`.split(/\n/)
    end

    def git_aliases_stats
      stats(git_subcommands, git_aliases)
    end
  end
end
git_aliases_stats = History::Git.git_aliases_stats

average_count = git_aliases_stats.values.inject(:+) / git_aliases_stats.count
git_aliases_stats.select {|_, count| count <= average_count }

History::Git#.git_aliases_stats は Git のエイリアスとヒストリに現れた回数の Hash を返します。

上記のコードでは平均値以下のエイリアスを得ています。

git_aliases_stats = History::Git.git_aliases_stats

git_aliases_stats.count
git_aliases_stats.select {|_, count| count <= 0 }

次に上記のコードでは一度もヒストリに現れなかったエイリアスを列挙します。

どちらも不要そうなエイリアスを見つけるのに役立ち、非常に便利です。

どうぞご利用ください。

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