Class: MmTool::MmToolCli

Inherits:
Object
  • Object
show all
Defined in:
lib/mm_tool/mm_tool_cli.rb

Overview

Implement the command line interface for MmTool::ApplicationMain

Instance Method Summary collapse

Constructor Details

#initialize(app_instance = MmTool::ApplicationMain.shared_application) ⇒ MmToolCli


Initialize




14
15
16
17
18
19
20
21
22
23
# File 'lib/mm_tool/mm_tool_cli.rb', line 14

def initialize(app_instance = MmTool::ApplicationMain.shared_application)
  self.validate_prerequisites

  decorated_list = MmTool.encoder_list.map{|s| C.bold(s)}.join(', ')
  USER_DEFAULTS[:encoder][:help_desc].gsub!('ENCODER_LIST', decorated_list)

  @application = app_instance
  @defaults = MmUserDefaults.shared_user_defaults
  @defaults.register_defaults(with_hash: USER_DEFAULTS)
end

Instance Method Details


Print Help


noinspection RubyResolve



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
54
55
56
57
58
59
# File 'lib/mm_tool/mm_tool_cli.rb', line 29

def print_help
  # Amount of hanging indent is dependent on the space arguments take up.
  hang = @defaults.example_args_by_length[-1].length + 4

  header = <<~HEREDOC
    #{C.bold('Usage:')} #{File.basename($0)} [options...] <directory|file> [options...] <directory|file> ...
    
    Performs media analysis and reports on files that don't meet quality requirements and/or files that
    have containers and/or streams of undesired types. Files with undesired containers and/or streams
    can optionally be transcoded into a new file.
    
    You must specify a file or a directory. Specifying a directory implies a recursive search for files
    matching the #{C.bold('--container-extension')} option.
  
    Options and files are processed as they occur, and remain in effect for subsequent input files until
    encountered again with a different value. Boolean flags shown below modify default behavior. They
    can be undone for subsequent input files with the capitalized version of the short flag, or by adding
    or deleting #{C.bold('no-')} for the verbose argument form.

    You can also set default options in #{PATH_USER_DEFAULTS}.
  HEREDOC

  puts OutputHelper.hanging_string(string: header, hang: 3, margin: OutputHelper.console_width)

  @defaults.arguments_help_by_group.each_pair do |group, arguments|
    puts group
    arguments.each do |argument|
      puts OutputHelper.hanging_string(string: argument, hang: hang, margin: OutputHelper.console_width) + "\n"
    end
  end
end

#run(args) ⇒ Object


Run the CLI.


noinspection RubyResolve



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
# File 'lib/mm_tool/mm_tool_cli.rb', line 99

def run(args)

  path = nil
  while args.count > 0 do

    # Convert single hyphen arguments to one or more multi-hyphen
    # arguments. Doing this as an extra step eliminates redundancy,
    # but also allows -abc in place of -a -b -c.
    if args[0] =~ /^-[A-Za-z]+$/

      args[0][1..-1].reverse.each_char do |char|

        case char

        when 'h'
          args.insert(1, '--help')
        when 'i'
          args.insert(1, '--no-info-header')
        when 'I'
          args.insert(1, '--info-header')
        when 's'
          args.insert(1, '--no-shell-commands')
        when 'S'
          args.insert(1, '--shell-commands')
        when 't'
          args.insert(1, '--transcode')
        when 'T'
          args.insert(1, '-no-transcode')
        when 'u'
          args.insert(1, '--no-fix-undefined-language')
        when 'U'
          args.insert(1, '--fix-undefined-language')
        when 'p'
          args.insert(1, '--dump')
        when 'P'
          args.insert(1, '--no-dump')
        else
          OutputHelper.print_error_and_exit("Error: option #{C.bold(args[0])} was specified, but I don't know what that means.")
        end

      end

      args.shift
      next
    end

    # The main loop processes options, commands, and files in first-in,
    # first out order, which is the normal Unix way compared to how
    # Ruby scripts try to handle things.
    case args[0]

      #-----------------------
      # Main Options
      #-----------------------

    when '--help'
      self.print_help
      exit 0

    when '--containers'
      @defaults[:container_files] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--scan'
      value = validate_arg_value(args[0], args[1]).downcase
      unless %w(normal all flagged quality force).include?(value)
        OutputHelper.print_error("Note: value #{C.bold(value)} doesn't make sense; assuming #{C.bold('normal')}.")
        value = 'normal'
      end
      @defaults[:scan_type] = value
      args.shift

    when '--ignore-titles'
      @defaults[:ignore_titles] = true

    when '--no-ignore-titles'
      @defaults[:ignore_titles] = false

    when '--no-info-header'
      @defaults[:info_header] = false

    when '--info-header'
      @defaults[:info_header] = true

    when '--no-shell-commands'
      @defaults[:shell_commands] = false

    when '--shell-commands'
      @defaults[:shell_commands] = true

    when '--version'
      puts "#{File.basename $0}, version #{MmTool::VERSION}"
      exit 0

    when '--'
      break

      #-----------------------
      # Command-like Options
      #-----------------------

    when '--transcode'
      @defaults[:ignore_files] = false
      @defaults[:unignore_files] = false
      @defaults[:transcode] = true

    when '--no-transcode'
      @defaults[:transcode] = false
      @application.tempfile = nil

    when '--ignore-files'
      @defaults[:ignore_files] = true

    when '--no-ignore-files'
      @defaults[:ignore_files] = false

    when '--unignore-files'
      @defaults[:unignore_files] = true

    when '--no-unignore-files'
      @defaults[:unignore_files] = false


      #-----------------------
      # Media
      #-----------------------

    when '--containers-preferred'
      @defaults[:containers_preferred] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--codecs-audio-preferred'
      @defaults[:codec_audio_preferred] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--codecs-video-preferred'
      @defaults[:codec_video_preferred] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--codecs-subs-preferred'
      @defaults[:codec_subs_preferred] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--keep-langs-audio'
      @defaults[:keep_langs_audio] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--keep_langs_video'
      @defaults[:keep_langs_video] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--keep-langs-subs'
      @defaults[:keep_langs_subs] = validate_arg_value(args[0], args[1]).split(',')
      args.shift

    when '--no-use-external-subs'
      @defaults[:use_external_subs] = false

    when '--use-external-subs'
      @defaults[:use_external_subs] = true

      #-----------------------
      # Transcoding
      #-----------------------

    when '--no-drop-subs'
      @defaults[:drop_subs] = false

    when '--suffix'
      @defaults[:suffix] = validate_arg_value(args[0], args[1])

    when '--undefined-language'
      @defaults[:suffix] = validate_arg_value(args[0], args[1])

    when '--no-fix-undefined-language'
      @defaults[:fix_undefined_language] = false

    when '--fix-undefined-language'
      @defaults[:fix_undefined_language] = true

    when '--encoder'
      @defaults[:encoder] = validate_encoder_value(args[0], args[1])

    when '--re-encode'
      @defaults[:reencode] = true

    when '--no-re-encode'
      @defaults[:reencode] = false

      #-----------------------
      # Quality
      #-----------------------

    when '--min-width'
      @defaults[:min_width] = validate_arg_value(args[0], args[1])

    when '--min-channels'
      @defaults[:min_channels] = validate_arg_value(args[0], args[1])

      #-----------------------
      # Other
      #-----------------------

    else

      # An unknown parameter was encountered, so let's stop everything.
      if args[0] =~ /^--.*$/
        OutputHelper.print_error_and_exit("Error: option #{C.bold(args[0])} was specified, but I don't know what that means.")
      end

      # Otherwise, check for existence of the path, and proceed or warn.
      path = File.expand_path(args[0])
      if File.exist?(path)
        @application.run(path)
      else
        OutputHelper.print_error("Note: skipping #{C.bold(path)}, which seems not to exist.")
      end

    end # case

    args.shift

  end # while

  # If path has never been set, then the user didn't specify anything to check,
  # which is likely to be a mistake.
  unless path
    OutputHelper.print_error_and_exit("You did not specify any input file(s) or directory(s). Use #{C.bold(File.basename($0))} for help.")
  end

end

#validate_arg_value(arg, value) ⇒ Object


Perform a really simple validation of the given value for the given argument, returning the value if successful.


noinspection RubyResolve



336
337
338
339
340
341
342
343
# File 'lib/mm_tool/mm_tool_cli.rb', line 336

def validate_arg_value(arg, value)
  if !value
    OutputHelper.print_error_and_exit("Error: option #{C.bold(arg)} was specified, but no value was given.")
  elsif value =~ /^-.*$/
    OutputHelper.print_error_and_exit("Error: option #{C.bold(arg)} was specified, but the value #{C.bold(value)} looks like another option argument.")
  end
  value
end

#validate_encoder_value(arg, value) ⇒ Object


Perform a really simple validation of the given value for the given argument, returning the value if successful.


noinspection RubyResolve



350
351
352
353
354
355
356
357
358
359
360
# File 'lib/mm_tool/mm_tool_cli.rb', line 350

def validate_encoder_value(arg, value)
  if !value
    OutputHelper.print_error_and_exit("Error: option #{C.bold(arg)} was specified, but no value was given.")
  elsif value =~ /^-.*$/
    OutputHelper.print_error_and_exit("Error: option #{C.bold(arg)} was specified, but the value #{C.bold(value)} looks like another option argument.")
  end
  unless MmTool.encoder_list.include?(value)
    OutputHelper.print_error_and_exit("Error: Unknown encoder #{C.bold(value)} specified for option #{C.bold(arg)}. Use #{C.bold(File.basename($0) << '--help')} for supported encoders.")
  end
  value
end

#validate_prerequisitesObject


Validate pre-requisites.


noinspection RubyResolve



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
# File 'lib/mm_tool/mm_tool_cli.rb', line 65

def validate_prerequisites
  commands        = %w(ffmpeg ffprobe)
  codecs_required = %w(libx264 libx265 libfdk_aac)
  task            = TTY::Command.new(printer: :null)
  success         = true

  # We'll check everything in items before failing, so that we can provide
  # a comprehensive list to the user. No one wants to see what's missing
  # on-by-one.
  commands.each do |command|
    unless TTY::Which.exist?(command)
      OutputHelper.print_error("Error: #{C.bold(command)} is not installed (or not in your #{C.bold('$PATH')}).")
      success = false
    end
  end
  exit 1 unless success

  # Now we'll make sure that all of the required codecs are installed as part of ffmpeg.
  # This is necessary because not every binary distribution supports non-free.

  # Again, we'll check them all before failing in order to list everything.
  codecs_required.each do |codec|
    result = task.run!("ffprobe -v quiet -codecs | grep #{codec}")
    OutputHelper.print_error("Error: ffmpeg was built without support for the #{C.bold(codec)} codec, which is required.") if result.failure?
    success = success && result.success?
  end
  exit 1 unless success

end