Class: Confgit::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/confgit/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_options(command, *banner, &block) ⇒ Object

オプション解析を定義する



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/confgit/cli.rb', line 78

def self.define_options(command, *banner, &block)
	define_method "options_#{command}" do |argv|
		options = {}

		OptionParser.new { |opts|
			begin
				opts.banner = banner(opts, command, *banner)
				instance_exec(opts, argv, options, &block)
			rescue => e
				abort e.to_s
			end
		}

		options
	end
end

.run(argv = ARGV, options = {}) ⇒ Object



12
13
14
# File 'lib/confgit/cli.rb', line 12

def self.run(argv = ARGV, options = {})
	CLI.new.run(argv, options)
end

Instance Method Details

#action(command, argv, options = {}) ⇒ Object

アクションの実行



60
61
62
63
64
65
66
67
68
69
# File 'lib/confgit/cli.rb', line 60

def action(command, argv, options = {})
	command = command.gsub(/-/, '_')

	# オプション解析
	options_method = "options_#{command}"
	options.merge!(send(options_method, argv)) if respond_to?(options_method)

	confgit = Repo.new
	confgit.send("confgit_#{command}", options, *argv)
end

サブコマンド・オプションのバナー作成



72
73
74
75
# File 'lib/confgit/cli.rb', line 72

def banner(opts, method, *args)
	subcmd = method.to_s.gsub(/^.+_/, '')
	["Usage: #{opts.program_name} #{subcmd}", *args].join(' ')
end

#i18n_initObject

I18n を初期化する



45
46
47
48
49
50
51
# File 'lib/confgit/cli.rb', line 45

def i18n_init
	I18n.load_path = Dir[File.expand_path('../locales/*.yml', __FILE__)]
	I18n.backend.load_translations

	locale = ENV['LANG'][0, 2].to_sym if ENV['LANG']
	I18n.locale = locale if I18n.available_locales.include?(locale)
end

#run(argv = ARGV, options = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/confgit/cli.rb', line 16

def run(argv = ARGV, options = {})
	i18n_init

	trap ('SIGINT') { abort '' }

	# コマンド引数の解析
	command = nil

	OptionParser.new { |opts|
		begin
			opts.version = LONG_VERSION || VERSION
			opts.banner = "Usage: #{opts.program_name} <command> [<args>]"

			opts.on('-h', '--help', t(:help))	{ abort opts.help }
			opts.separator ''
			opts.separator t(:commands)

			opts.order!(argv)
			command = argv.shift
			abort opts.help unless command
		rescue => e
			abort e.to_s
		end
	}

	action(command, argv, options)
end

#t(code, options = {}) ⇒ Object

I18n で翻訳する



54
55
56
57
# File 'lib/confgit/cli.rb', line 54

def t(code, options = {})
	options[:scope] ||= [:usage]
	I18n.t(code, options)
end