Module: Twig::Cli

Included in:
Twig
Defined in:
lib/twig/cli.rb,
lib/twig/cli/help.rb

Overview

Handles raw input from the command-line interface.

Defined Under Namespace

Modules: Help

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prompt_with_choices(prompt, choices) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/twig/cli.rb', line 8

def self.prompt_with_choices(prompt, choices)
  # Prints the given string `prompt` and the array `choices` numbered, and
  # prompts the user to enter a number. Returns the matching value, or nil
  # if the user input is invalid.

  raise ArgumentError, 'At least two choices required' if choices.size < 2

  puts prompt
  choices.each_with_index do |choice, index|
    puts "#{sprintf('%3s', index + 1)}. #{choice}"
  end
  print '> '

  input = $stdin.gets.to_i
  choices[input - 1]
end

Instance Method Details

#abort_for_option_exception(exception) ⇒ Object



341
342
343
344
# File 'lib/twig/cli.rb', line 341

def abort_for_option_exception(exception)
  puts exception.message + "\nFor a list of options, run `twig help`."
  exit 1
end

#get_branch_property_for_cli(branch_name, property_name) ⇒ Object



380
381
382
383
384
385
386
387
388
389
390
# File 'lib/twig/cli.rb', line 380

def get_branch_property_for_cli(branch_name, property_name)
  value = get_branch_property(branch_name, property_name)
  if value
    puts value
  else
    raise Twig::Branch::MissingPropertyError,
      %{The branch "#{branch_name}" does not have the property "#{property_name}".}
  end
rescue ArgumentError, Twig::Branch::MissingPropertyError => exception
  abort exception.message
end

#read_cli_args!(args) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/twig/cli.rb', line 346

def read_cli_args!(args)
  Twig::Subcommands.exec_subcommand_if_any(args) if args.any?

  args = read_cli_options!(args)
  branch_name = target_branch_name
  format = options.delete(:format)
  property_to_unset = options.delete(:unset_property)

  # Handle remaining arguments, if any
  if args.any?
    property_name, property_value = args[0], args[1]

    read_cli_options!(args)

    # Get/set branch property
    if property_value
      # `$ twig <key> <value>`
      set_branch_property_for_cli(branch_name, property_name, property_value)
    else
      # `$ twig <key>`
      get_branch_property_for_cli(branch_name, property_name)
    end
  elsif property_to_unset
    # `$ twig --unset <key>`
    unset_branch_property_for_cli(branch_name, property_to_unset)
  elsif format == :json
    # `$ twig --format json`
    puts branches_json
  else
    # `$ twig`
    puts list_branches
  end
end

#read_cli_options!(args) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/twig/cli.rb', line 55

def read_cli_options!(args)
  custom_properties = Twig::Branch.all_property_names

  option_parser = OptionParser.new do |opts|
    opts.banner         = Help.intro
    opts.summary_indent = ' ' * 2
    opts.summary_width  = 32

    ###

    Help.header(opts, 'Common options')

    desc = 'Use a specific branch.'
    opts.on(
      '-b BRANCH', '--branch BRANCH', *Help.description(desc)
    ) do |branch|
      set_option(:branch, branch)
    end

    desc = 'Unset a branch property.'
    opts.on('--unset PROPERTY', *Help.description(desc)) do |property_name|
      set_option(:unset_property, property_name)
    end

    desc = 'Show this help content.'
    opts.on('--help', *Help.description(desc)) do
      summary_lines = opts.to_s.split("\n")
      run_pager

      # Filter out custom property lines
      prev_line = nil
      summary_lines.each do |line|
        # Squash successive blank lines
        next if line == "\n" && prev_line == "\n"

        unless Help.line_for_custom_property?(line)
          puts line
          prev_line = line
        end
      end

      exit
    end

    desc = 'Show Twig version.'
    opts.on('--version', *Help.description(desc)) do
      puts Twig::VERSION
      exit
    end

    ###

    Help.header(opts, 'Filtering branches')

    desc = 'Only list branches below a given age.'
    opts.on(
      '--max-days-old AGE', *Help.description(desc, :add_blank_line => true)
    ) do |age|
      set_option(:max_days_old, age)
    end

    desc = 'Only list branches whose name matches a given pattern.'
    opts.on(
      '--only-branch PATTERN',
      *Help.description(desc, :add_blank_line => true)
    ) do |pattern|
      set_option(:property_only, :branch => pattern)
    end

    desc = 'Do not list branches whose name matches a given pattern.'
    opts.on('--except-branch PATTERN', *Help.description(desc)) do |pattern|
      set_option(:property_except, :branch => pattern)
    end

    custom_properties.each do |property_name|
      property_name_sym = property_name.to_sym

      opts.on("--only-#{property_name} PATTERN") do |pattern|
        set_option(:property_only, property_name_sym => pattern)
      end

      opts.on("--except-#{property_name} PATTERN") do |pattern|
        set_option(:property_except, property_name_sym => pattern)
      end
    end
    Help.description_for_custom_property(opts, [
      ['--only-PROPERTY PATTERN',   'Only list branches with a given property'],
      ['',                          'that matches a given pattern.']
    ], :trailing => '')
    Help.description_for_custom_property(opts, [
      ['--except-PROPERTY PATTERN', 'Do not list branches with a given property'],
      ['',                          'that matches a given pattern.']
    ])

    desc =
      'Print branch properties in a format that can be used by other ' \
      'tools. Currently, the only supported value is `json`.'
    opts.on(
      '--format FORMAT', *Help.description(desc, :add_blank_line => true)
    ) do |format|
      set_option(:format, format)
    end

    desc =
      'Lists all branches regardless of other filtering options. ' \
      'Useful for overriding options in ' +
      File.basename(Twig::Options::CONFIG_PATH) + '.'
    opts.on('--all', *Help.description(desc)) do |pattern|
      unset_option(:max_days_old)
      unset_option(:property_except)
      unset_option(:property_only)
    end

    ###

    Help.header(opts, 'Listing branches')

    desc = "      Set the width for the `branch` column.\n      (Default: \#{Twig::DEFAULT_BRANCH_COLUMN_WIDTH})\n    DESC\n    opts.on('--branch-width NUMBER', *Help.description(desc)) do |width|\n      set_option(:property_width, :branch => width)\n    end\n\n    custom_properties.each do |property_name|\n      opts.on(\"--\#{property_name}-width NUMBER\") do |width|\n        set_option(:property_width, property_name.to_sym => width)\n      end\n    end\n    Help.description_for_custom_property(opts, [\n      ['--PROPERTY-width NUMBER', \"Set the width for a given property's column.\"],\n      ['',                        \"(Default: \#{Twig::DEFAULT_PROPERTY_COLUMN_WIDTH})\"]\n    ])\n\n    desc = <<-DESC\n      Only include properties where the property name matches the given\n      regular expression.\n    DESC\n    opts.on(\n      '--only-property PATTERN',\n      *Help.description(desc, :add_blank_line => true)\n    ) do |pattern|\n      set_option(:property_only_name, pattern)\n    end\n\n    desc = <<-DESC\n      Exclude properties where the property name matches the given regular\n      expression.\n    DESC\n    opts.on(\n      '--except-property PATTERN',\n      *Help.description(desc, :add_blank_line => true)\n    ) do |pattern|\n      set_option(:property_except_name, pattern)\n    end\n\n    colors = Twig::Display::COLORS.keys.\n      map { |value| format_string(value, :color => value) }.\n      join(', ')\n    weights = Twig::Display::WEIGHTS.keys.\n      map { |value| format_string(value, :weight => value) }.\n      join(' and ')\n    default_header_style = format_string(\n      Twig::DEFAULT_HEADER_COLOR.to_s,\n      :color => Twig::DEFAULT_HEADER_COLOR\n    )\n    desc = <<-DESC\n      STYLE is a color, weight, or a space-separated pair of one of each.\n      Valid colors are \#{colors}. Valid weights are \#{weights}.\n      (Default: \"\#{default_header_style}\")\n    DESC\n    opts.on(\n      '--header-style \"STYLE\"',\n      *Help.description(desc, :add_blank_line => true)\n    ) do |style|\n      set_option(:header_style, style)\n    end\n\n    desc = 'Show oldest branches first. (Default: false)'\n    opts.on('--reverse', *Help.description(desc)) do\n      set_option(:reverse, true)\n    end\n\n    ###\n\n    Help.header(opts, 'GitHub integration')\n\n    desc = <<-DESC\n      Set a custom GitHub API URI prefix, e.g.,\n      https://github-enterprise.example.com/api/v3.\n      (Default: \"\#{Twig::DEFAULT_GITHUB_API_URI_PREFIX}\")\n    DESC\n    opts.on(\n      '--github-api-uri-prefix PREFIX',\n      *Help.description(desc, :add_blank_line => true)\n    ) do |prefix|\n      set_option(:github_api_uri_prefix, prefix)\n    end\n\n    desc = <<-DESC\n      Set a custom GitHub URI prefix, e.g.,\n      https://github-enterprise.example.com.\n      (Default: \"\#{Twig::DEFAULT_GITHUB_URI_PREFIX}\")\n    DESC\n    opts.on('--github-uri-prefix PREFIX', *Help.description(desc)) do |prefix|\n      set_option(:github_uri_prefix, prefix)\n    end\n\n    ###\n\n    Help.header(opts, 'Config files and tab completion', :trailing => '')\n\n    Help.print_paragraph(opts, %{\n      Twig can automatically set up a config file for you, where you can put\n      your most frequently used options for filtering and listing branches.\n      To get started, run `twig init` and follow the instructions. This does\n      two things:\n    })\n\n    Help.print_paragraph(opts, %{\n      * Creates \#{Twig::Options::CONFIG_PATH}, where you can put your\n        favorite options, e.g.:\n    })\n\n    Help.print_section(opts, [\n      '      except-branch: staging',\n      '      header-style:  green bold',\n      '      max-days-old:  30',\n      '      reverse:       true'\n    ].join(\"\\n\"))\n\n    Help.print_paragraph(opts, %{\n      * Enables tab completion for Twig subcommands and branch names, e.g.:\n    })\n\n    Help.print_section(opts, [\n      '      `twig cre<tab>` -> `twig create-branch`',\n      '      `twig status -b my-br<tab>` -> `twig status -b my-branch`'\n    ].join(\"\\n\"), :trailing => '')\n\n    ###\n\n    Help.header(opts, 'Subcommands', :trailing => '')\n\n    Help.print_paragraph(opts, \"Twig comes with these subcommands:\", :trailing => \"\\n\\n\")\n\n    Help.subcommand_descriptions.each do |desc|\n      Help.print_line(opts, desc)\n    end\n\n    Help.subheader(opts, 'Writing a subcommand', :trailing => '')\n\n    Help.print_paragraph(opts, %{\n      You can write any Twig subcommand that fits your own Git workflow. To\n      write a Twig subcommand:\n    })\n\n    Help.print_section(opts, [\n      '1.  Write a script; any language will do. (If you want to take',\n      '    advantage of Twig\\'s option parsing and branch processing, you\\'ll',\n      '    need Ruby. See `twig-checkout-parent` for an example.)'\n    ].join(\"\\n\"))\n\n    Help.print_section(opts, [\n      '2.  Save it with the `twig-` prefix in your `$PATH`,',\n      '    e.g., `~/bin/twig-my-subcommand`.'\n    ].join(\"\\n\"))\n\n    Help.print_section(opts, [\n      '3.  Make it executable: `chmod ugo+x ~/bin/twig-my-subcommand`'\n    ].join(\"\\n\"))\n\n    Help.print_section(opts, [\n      '4.  Run your subcommand: `twig my-subcommand` (with a *space* after',\n      '    `twig`'\n    ].join(\"\\n\"))\n  end\n\n  option_parser.parse!(args)\nrescue OptionParser::InvalidOption, OptionParser::MissingArgument => exception\n  abort_for_option_exception(exception)\nensure\n  args\nend\n"

#run_pagerObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/twig/cli.rb', line 25

def run_pager
  # Starts a pager so that all following STDOUT output is paginated.
  # Based on: http://nex-3.com/posts/73-git-style-automatic-paging-in-ruby

  return if Twig::System.windows? || !$stdout.tty? || !Kernel.respond_to?(:fork)

  read_io, write_io = IO.pipe

  # Create child process
  unless Kernel.fork
    # The following runs only in the child process:
    $stdout.reopen(write_io)
    $stderr.reopen(write_io) if $stderr.tty?
    read_io.close
    write_io.close
    return
  end

  $stdin.reopen(read_io)
  read_io.close
  write_io.close

  ENV['LESS'] = 'FSRX'      # Don't page if the input fits on screen
  Kernel.select([$stdin])   # Wait for input before starting pager

  # Turn parent process into pager
  pager = ENV['PAGER'] || 'less'
  exec pager rescue exec '/bin/sh', '-c', pager
end

#set_branch_property_for_cli(branch_name, property_name, property_value) ⇒ Object



392
393
394
395
396
# File 'lib/twig/cli.rb', line 392

def set_branch_property_for_cli(branch_name, property_name, property_value)
  puts set_branch_property(branch_name, property_name, property_value)
rescue ArgumentError, RuntimeError => exception
  abort exception.message
end

#unset_branch_property_for_cli(branch_name, property_name) ⇒ Object



398
399
400
401
402
# File 'lib/twig/cli.rb', line 398

def unset_branch_property_for_cli(branch_name, property_name)
  puts unset_branch_property(branch_name, property_name)
rescue ArgumentError, Twig::Branch::MissingPropertyError => exception
  abort exception.message
end