#!/usr/bin/env ruby # -*- ruby -*- require 'net/https' require 'json' require 'uri' require 'cgi' require 'optparse' require 'scrapbox' require 're_expand' class GitHelp def datafile File.expand_path("~/.githelp") end def initialize @pagedata = {} @project = Scrapbox::Project.new("GitHelp") end def getdata # # ページデータ取得 # puts "-----------------ページデータを取得" @project.pages.each { |title,page| puts "...#{title}" @pagedata[title] = page.text.split(/\n/) } dumpdata = {} dumpdata['codes'] = [] dumpdata['defs'] = [] # # 関数/定数を評価" # puts "-----------------関数/定数を取得" @pagedata.each { |title,pagedata| puts "...#{title}" pagedata. each { |line| if line =~ /code:(.*\.rb)$/ then src = $1 puts "=========== #{src}" page = Scrapbox::Page.new(@project,title) dumpdata['codes'] << page.code(src) end } } puts "-----------------GitHelpデータを検出" @pagedata.each { |title,pagedata| puts "...#{title}" processing_defs = false codeindent = nil pagedata.each { |line| if !codeindent if line =~ /^(\s*)code:/ codeindent = $1.length next end else line =~ /^(\s*)/ if line.length < codeindent codeindent = nil else next end end if line =~ /^\s*[\$\%]/ puts line if line =~ /^\%/ && !processing_defs puts "'$'で始まる用例定義なしでコマンドを定義しようとしています" exit end dumpdata['defs'] << line processing_defs = true else processing_defs = false end } } File.open(datafile,"w"){ |f| f.puts dumpdata.to_json } end def githelp(pager) data = JSON.parse(File.read(datafile)) # # 関数定義などをeval # data['codes'].each { |code| eval code } g = ExpandRuby::Generator.new # re_expandのジェネレータ # # GitHelpエントリ # lines = [] data['defs'].each { |line| if line =~ /^\s*\$\s*(.*)$/ # $.... lines << $1 elsif line =~ /^\s*\%\s*(.*)$/ # %.... cmd = $1 lines.each { |l| desc = eval('"' + l + '"') g.add desc.force_encoding('utf-8'), cmd.force_encoding('utf-8') } lines = [] end } # puts "GENERATE #{params.split('|').join(' ')} " res = g.generate " #{ARGV.join(' ').sub(/\[/,'').sub(/\]/,'')} " listed = {} list = res[0].find_all { |a| # 0 ambig if listed[a[1]] false else listed[a[1]] = true end } if pager == 'peco' then res = IO.popen(pager, "r+") {|io| list.each_with_index { |entry,ind| io.puts "#[#{ind}] #{entry[0]}" io.puts " #{entry[1]}" } io.close_write io.gets } if res if res =~ /^\#\[(\d+)\]/ cmd = list[$1.to_i][1] else cmd = res.sub(/^\s*/,'') end puts cmd system cmd end else res = IO.popen(pager, "w") {|io| list.each_with_index { |entry,ind| io.puts "#[#{ind}] #{entry[0]}" io.puts " #{entry[1]}" } } end end end is_repository = system 'git rev-parse --git-dir > /dev/null >& /dev/null' unless is_repository STDERR.puts "Gitレポジトリで実行して下さい" exit end options = ARGV.getopts('ut') githelp = GitHelp.new if !File.exist?(githelp.datafile) && !options['u'] puts "#{githelp.datafile}を作成します..." githelp.getdata end if options['u'] then githelp.getdata else pager = 'peco' peco_installed = system "command -v peco > /dev/null" if options['t'] || !peco_installed pager = 'more' end githelp.githelp pager end