Class: Asciidoctor::Cli::Options

Inherits:
Hash
  • Object
show all
Defined in:
lib/asciidoctor/cli/options.rb

Overview

List of options that can be specified on the command line

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Options

Returns a new instance of Options.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/asciidoctor/cli/options.rb', line 10

def initialize(options = {})
  self[:attributes] = options[:attributes] || {}
  self[:input_files] = options[:input_files]
  self[:output_file] = options[:output_file]
  self[:safe] = options[:safe] || SafeMode::UNSAFE
  self[:standalone] = options.fetch :standalone, true
  self[:template_dirs] = options[:template_dirs]
  self[:template_engine] = options[:template_engine]
  self[:attributes]['doctype'] = options[:doctype] if options[:doctype]
  self[:attributes]['backend'] = options[:backend] if options[:backend]
  self[:eruby] = options[:eruby]
  self[:verbose] = options.fetch :verbose, 1
  self[:warnings] = options.fetch :warnings, false
  self[:load_paths] = options[:load_paths]
  self[:requires] = options[:requires]
  self[:base_dir] = options[:base_dir]
  self[:source_dir] = options[:source_dir]
  self[:destination_dir] = options[:destination_dir]
  self[:failure_level] = ::Logger::Severity::FATAL
  self[:trace] = false
  self[:timings] = false
end

Class Method Details

.parse!(args) ⇒ Object



33
34
35
# File 'lib/asciidoctor/cli/options.rb', line 33

def self.parse!(args)
  Options.new.parse! args
end

Instance Method Details

#parse!(args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
# File 'lib/asciidoctor/cli/options.rb', line 37

def parse!(args)
  opts_parser = ::OptionParser.new do |opts|
    # NOTE don't use squiggly heredoc to maintain compatibility with Ruby < 2.3
    opts.banner = "    Usage: asciidoctor [OPTION]... FILE...\n    Convert the AsciiDoc input FILE(s) to the backend output format (e.g., HTML 5, DocBook 5, etc.)\n    Unless specified otherwise, the output is written to a file whose name is derived from the input file.\n    Application log messages are printed to STDERR.\n    Example: asciidoctor input.adoc\n\n    EOS\n\n    opts.on('-b', '--backend BACKEND', 'set backend output format: [html5, xhtml5, docbook5, manpage] (default: html5)',\n        'additional backends are supported via extended converters (e.g., pdf, epub3)') do |backend|\n      self[:attributes]['backend'] = backend\n    end\n    opts.on('-d', '--doctype DOCTYPE', ['article', 'book', 'manpage', 'inline'],\n        'document type to use when converting document: [article, book, manpage, inline] (default: article)') do |doctype|\n      self[:attributes]['doctype'] = doctype\n    end\n    opts.on('-e', '--embedded', 'suppress enclosing document structure and output an embedded document (default: false)') do\n      self[:standalone] = false\n    end\n    opts.on('-o', '--out-file FILE', 'output file (default: based on path of input file); use - to output to STDOUT') do |output_file|\n      self[:output_file] = output_file\n    end\n    opts.on('--safe',\n        'set safe mode level to safe (default: unsafe)',\n        'enables include directives, but prevents access to ancestor paths of source file',\n        'provided for compatibility with the asciidoc command') do\n      self[:safe] = SafeMode::SAFE\n    end\n    opts.on('-S', '--safe-mode SAFE_MODE', (safe_mode_names = SafeMode.names),\n        %(set safe mode level explicitly: [\#{safe_mode_names.join ', '}] (default: unsafe)),\n        'disables potentially dangerous macros in source files, such as include::[]') do |name|\n      self[:safe] = SafeMode.value_for_name name\n    end\n    opts.on('-s', '--no-header-footer', 'suppress enclosing document structure and output an embedded document (default: false)') do\n      self[:standalone] = false\n    end\n    opts.on('-n', '--section-numbers', 'auto-number section titles in the HTML backend; disabled by default') do\n      self[:attributes]['sectnums'] = ''\n    end\n    opts.on('--eruby ERUBY', ['erb', 'erubi', 'erubis'],\n        'specify eRuby implementation to use when rendering custom ERB templates: [erb, erubi, erubis] (default: erb)') do |eruby|\n      self[:eruby] = eruby\n    end\n    opts.on('-a', '--attribute name[=value]', 'a document attribute to set in the form of name, name!, or name=value pair',\n        'this attribute takes precedence over the same attribute defined in the source document',\n        'unless either the name or value ends in @ (i.e., name@=value or name=value@)') do |attr|\n      next if (attr = attr.rstrip).empty? || attr == '='\n      begin\n        attr = attr.encode UTF_8\n      rescue ::EncodingError\n        attr = attr.force_encoding UTF_8\n      end unless attr.encoding == UTF_8\n      name, _, val = attr.partition '='\n      self[:attributes][name] = val\n    end\n    opts.on('-T', '--template-dir DIR', 'a directory containing custom converter templates that override the built-in converter (requires tilt gem)',\n        'may be specified more than once') do |template_dir|\n      if self[:template_dirs].nil?\n        self[:template_dirs] = [template_dir]\n      elsif ::Array === self[:template_dirs]\n        self[:template_dirs] << template_dir\n      else\n        self[:template_dirs] = [self[:template_dirs], template_dir]\n      end\n    end\n    opts.on('-E', '--template-engine NAME', 'template engine to use for the custom converter templates (loads gem on demand)') do |template_engine|\n      self[:template_engine] = template_engine\n    end\n    opts.on('-B', '--base-dir DIR', 'base directory containing the document and resources (default: directory of source file)') do |base_dir|\n      self[:base_dir] = base_dir\n    end\n    opts.on('-R', '--source-dir DIR', 'source root directory (used for calculating path in destination directory)') do |src_dir|\n      self[:source_dir] = src_dir\n    end\n    opts.on('-D', '--destination-dir DIR', 'destination output directory (default: directory of source file)') do |dest_dir|\n      self[:destination_dir] = dest_dir\n    end\n    opts.on('-IDIRECTORY', '--load-path DIRECTORY', 'add a directory to the $LOAD_PATH',\n        'may be specified more than once') do |path|\n      (self[:load_paths] ||= []).concat(path.split ::File::PATH_SEPARATOR)\n    end\n    opts.on('-rLIBRARY', '--require LIBRARY', 'require the specified library before executing the processor (using require)',\n        'may be specified more than once') do |path|\n      (self[:requires] ||= []).concat(path.split ',')\n    end\n    opts.on('--failure-level LEVEL', %w(info INFO warning WARNING error ERROR fatal FATAL), 'set minimum log level that yields a non-zero exit code: [INFO, WARN, ERROR, FATAL] (default: FATAL)') do |level|\n      level = 'WARN' if (level = level.upcase) == 'WARNING'\n      self[:failure_level] = ::Logger::Severity.const_get level\n    end\n    opts.on('-q', '--quiet', 'silence application log messages and script warnings (default: false)') do\n      self[:verbose] = 0\n    end\n    opts.on('--trace', 'include backtrace information when reporting errors (default: false)') do\n      self[:trace] = true\n    end\n    opts.on('-v', '--verbose', 'directs application messages logged at DEBUG or INFO level to STDERR (default: false)') do\n      self[:verbose] = 2\n    end\n    opts.on('-w', '--warnings', 'turn on script warnings (default: false)') do\n      self[:warnings] = true\n    end\n    opts.on('-t', '--timings', 'print timings report (default: false)') do\n      self[:timings] = true\n    end\n    opts.on_tail('-h', '--help [TOPIC]', 'print a help message',\n        'show this usage if TOPIC is not specified or recognized',\n        'show an overview of the AsciiDoc syntax if TOPIC is syntax',\n        'dump the Asciidoctor man page (in troff/groff format) if TOPIC is manpage') do |topic|\n      case topic\n      # use `asciidoctor -h manpage | man -l -` to view with man pager\n      when 'manpage'\n        if (manpage_path = ::ENV['ASCIIDOCTOR_MANPAGE_PATH'])\n          if ::File.exist? manpage_path\n            if manpage_path.end_with? '.gz'\n              require 'zlib' unless defined? ::Zlib::GzipReader\n              $stdout.puts ::Zlib::GzipReader.open(manpage_path) {|gz| gz.read }\n            else\n              $stdout.puts ::File.read manpage_path\n            end\n          else\n            $stderr.puts %(asciidoctor: FAILED: manual page not found: \#{manpage_path})\n            return 1\n          end\n        # Ruby 2.3 requires the extra brackets around the ::File.join method call\n        elsif ::File.exist? (manpage_path = (::File.join ROOT_DIR, 'man', 'asciidoctor.1'))\n          $stdout.puts ::File.read manpage_path\n        else\n          manpage_path = %x(man -w asciidoctor).chop rescue ''\n          if manpage_path.empty?\n            $stderr.puts 'asciidoctor: FAILED: manual page not found; try `man asciidoctor`'\n            return 1\n          elsif manpage_path.end_with? '.gz'\n            require 'zlib' unless defined? ::Zlib::GzipReader\n            $stdout.puts ::Zlib::GzipReader.open(manpage_path) {|gz| gz.read }\n          else\n            $stdout.puts ::File.read manpage_path\n          end\n        end\n      when 'syntax'\n        # Ruby 2.3 requires the extra brackets around the ::File.join method call\n        if ::File.exist? (syntax_path = (::File.join ROOT_DIR, 'data', 'reference', 'syntax.adoc'))\n          $stdout.puts ::File.read syntax_path\n        else\n          $stderr.puts 'asciidoctor: FAILED: syntax page not found; visit https://asciidoctor.org/docs'\n          return 1\n        end\n      else\n        $stdout.puts opts\n      end\n      return 0\n    end\n    opts.on_tail('-V', '--version', 'display the version and runtime environment (or -v if no other flags or arguments)') do\n      return print_version $stdout\n    end\n  end\n\n  old_verbose, $VERBOSE = $VERBOSE, (args.include? '-w')\n  opts_parser.parse! args\n\n  if args.empty?\n    if self[:verbose] == 2 # -v flag was specified\n      return print_version $stdout\n    else\n      $stderr.puts opts_parser\n      return 1\n    end\n  end\n\n  infiles = []\n  # shave off the file to process so that options errors appear correctly\n  if args.size == 1 && args[0] == '-'\n    infiles << args.pop\n  else\n    args.each do |file|\n      if file.start_with? '-'\n        # warn, but don't panic; we may have enough to proceed, so we won't force a failure\n        $stderr.puts %(asciidoctor: WARNING: extra arguments detected (unparsed arguments: '\#{args.join \"', '\"}') or incorrect usage of stdin)\n      elsif ::File.file? file\n        infiles << file\n      # NOTE only attempt to glob if file is not found\n      else\n        # Tilt backslashes in Windows paths the Ruby-friendly way\n        if ::File::ALT_SEPARATOR == RS && (file.include? RS)\n          file = file.tr RS, FS\n        end\n        if (matches = ::Dir.glob file).empty?\n          # NOTE if no matches, assume it's just a missing file and proceed\n          infiles << file\n        else\n          infiles.concat matches\n        end\n      end\n    end\n  end\n\n  infiles.reject {|file| file == '-' }.each do |file|\n    begin\n      fstat = ::File.stat file\n      if fstat.file? || fstat.pipe?\n        unless fstat.readable?\n          $stderr.puts %(asciidoctor: FAILED: input file \#{file} is not readable)\n          return 1\n        end\n      else\n        $stderr.puts %(asciidoctor: FAILED: input path \#{file} is a \#{fstat.ftype}, not a file)\n        return 1\n      end\n    rescue ::Errno::ENOENT\n      $stderr.puts %(asciidoctor: FAILED: input file \#{file} is missing)\n      return 1\n    end\n  end\n\n  self[:input_files] = infiles\n\n  delete :attributes if self[:attributes].empty?\n\n  if self[:template_dirs]\n    begin\n      require 'tilt' unless defined? ::Tilt.new\n    rescue ::LoadError\n      raise $! if self[:trace]\n      $stderr.puts 'asciidoctor: FAILED: \\'tilt\\' could not be loaded'\n      $stderr.puts '  You must have the tilt gem installed (gem install tilt) to use custom backend templates'\n      $stderr.puts '  Use --trace to show backtrace'\n      return 1\n    rescue ::SystemExit\n      # not permitted here\n    end\n  end\n\n  if (load_paths = self[:load_paths])\n    load_paths.uniq!\n    load_paths.reverse_each {|path| $:.unshift ::File.expand_path path }\n  end\n\n  if (requires = self[:requires])\n    requires.uniq!\n    requires.each do |path|\n      begin\n        require path\n      rescue ::LoadError\n        raise $! if self[:trace]\n        $stderr.puts %(asciidoctor: FAILED: '\#{path}' could not be loaded)\n        $stderr.puts '  Use --trace to show backtrace'\n        return 1\n      rescue ::SystemExit\n        # not permitted here\n      end\n    end\n  end\n\n  self\nrescue ::OptionParser::MissingArgument\n  $stderr.puts %(asciidoctor: option \#{$!.message})\n  $stdout.puts opts_parser\n  1\nrescue ::OptionParser::InvalidOption, ::OptionParser::InvalidArgument\n  $stderr.puts %(asciidoctor: \#{$!.message})\n  $stdout.puts opts_parser\n  1\nensure\n  $VERBOSE = old_verbose\nend\n".gsub '          ', ''


306
307
308
309
310
311
312
313
# File 'lib/asciidoctor/cli/options.rb', line 306

def print_version os = $stdout
  os.puts %(Asciidoctor #{::Asciidoctor::VERSION} [https://asciidoctor.org])
  encoding_info = { 'lc' => 'locale', 'fs' => 'filesystem', 'in' => 'internal', 'ex' => 'external' }.map do |k, v|
    %(#{k}:#{v == 'internal' ? (::File.open(__FILE__) {|f| f.getc.encoding }) : (::Encoding.find v)})
  end
  os.puts %(Runtime Environment (#{::RUBY_DESCRIPTION}) (#{encoding_info.join ' '}))
  0
end