Class: SeeingIsBelieving::Binary::Config

Inherits:
HashStruct
  • Object
show all
Defined in:
lib/seeing_is_believing/binary/config.rb

Constant Summary collapse

DeprecatedArgMessage =
Binary::ErrorMessage.for :args do
  def to_s
    "Deprecated: `#{args.join ' '}` #{explanation}"
  end
end

Instance Method Summary collapse

Methods inherited from HashStruct

#==, #[], #[]=, #each, #fetch, #hash, #initialize, #inspect, inspect, #key?, #keys, #merge, #pretty_print, #to_hash, #values

Constructor Details

This class inherits a constructor from SeeingIsBelieving::HashStruct

Instance Method Details

#add_error(explanation) ⇒ Object



46
47
48
# File 'lib/seeing_is_believing/binary/config.rb', line 46

def add_error(explanation)
  errors << ErrorMessage.new(explanation: explanation)
end

#finalize(stdin, stdout, stderr, file_class) ⇒ Object



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
# File 'lib/seeing_is_believing/binary/config.rb', line 276

def finalize(stdin, stdout, stderr, file_class)
  if print_event_stream?
    require 'seeing_is_believing/event_stream/handlers/stream_json_events'
    lib_options.event_handler = EventStream::Handlers::StreamJsonEvents.new(stdout)
  end

  stdin.set_encoding 'utf-8'

  case debug
  when String
    debug_file    = File.open(debug, 'a').tap { |f| f.sync = true }
    self.debugger = Debugger.new stream: debug_file, colour: false
  when true
    self.debugger = Debugger.new stream: stderr, colour: stderr.tty?
  end
  self.lib_options.debugger = debugger

  if filename && body
    add_error("Cannot give a program body and a filename to get the program body from.")
  elsif filename && file_class.exist?(filename)
    self.lib_options.stdin = stdin
    # TODO: this doesn't seem like a safe assumption
    self.body = file_class.read filename, external_encoding: "utf-8"
  elsif filename
    add_error("#{filename} does not exist!")
  elsif body
    self.lib_options.stdin = stdin
  elsif print_version? || print_help? || errors.any?
    self.body = ""
  else
    self.body = stdin.read
  end

  self
end

#parse_args(args) ⇒ Object



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
# File 'lib/seeing_is_believing/binary/config.rb', line 50

def parse_args(args)
  args          = args.dup
  as            = nil
  filenames     = []
  unknown_flags = []

  extract_positive_int_for = lambda do |flagname, &on_success|
    string = args.shift
    int    = string.to_i
    if int.to_s == string && 0 < int
      on_success.call int
    else
      add_error "#{flagname} expects a positive integer argument"
    end
    string
  end

  extract_non_negative_float_for = lambda do |flagname, &on_success|
    begin
      string = args.shift
      float  = Float string
      raise if float < 0
      on_success.call float
      string
    rescue
      add_error "#{flagname} expects a positive float or integer argument"
    end
  end

  saw_deprecated = lambda do |explanation, *args|
    self.deprecations << DeprecatedArgMessage.new(explanation: explanation, args: args)
  end

  encodings_are_deprecated = lambda do |*args|
    saw_deprecated.call "The ability to set encodings is deprecated. If you need this, details are at https://github.com/JoshCheek/seeing_is_believing/wiki/Encodings",
                        *args
  end

  next_arg = lambda do |flagname, argtype, &on_success|
    arg = args.shift
    arg ? on_success.call(arg) :
          add_error("#{flagname} needs an argument (#{argtype})")
    arg
  end

  until args.empty?
    case (arg = args.shift)
    when '-c', '--clean'
      self.print_cleaned = true

    when '-v', '--version'
      self.print_version = true

    when '--ignore-unknown-flags'
      self.ignore_unknown_flags = true

    when '-x', '--xmpfilter-style'
      self.annotator                 = AnnotateMarkedLines
      self.lib_options.rewrite_code  = AnnotateMarkedLines.code_rewriter(markers)
      self.remove_value_prefixes     = false
      self.lib_options.require_files << 'pp'
      self.lib_options.require_files << 'seeing_is_believing/customize_pp'

    when '--toggle-mark'
      extract_positive_int_for.call arg do |n|
        self.toggle_mark = n
      end

    when '-i', '--inherit-exitstatus', '--inherit-exit-status'
      self.inherit_exitstatus = true
      arg.include?("exit-status") &&
        saw_deprecated.call("Dash has been removed for consistency, use --inherit-exitstatus", arg)

    when '-j', '--json'
      self.result_as_json = true

    when '--stream'
      self.print_event_stream = true

    when '-h', '--help'
      self.print_help = true
      self.help_screen = Binary.help_screen(markers)

    when '-h+', '--help+'
      self.print_help  = true
      self.help_screen = Binary.help_screen_extended(markers)

    when '-g', '--debug'
      self.debug = true

    when '--debug-to'
      next_arg.call arg, "a filename" do |filename|
        self.debug = filename
      end

    when '-d', '--line-length'
      extract_positive_int_for.call arg do |n|
        self.annotator_options.max_line_length = n
      end

    when '-D', '--result-length'
      extract_positive_int_for.call arg do |n|
        self.annotator_options.max_result_length = n
      end

    when '-n', '--max-line-captures', '--number-of-captures'
      extracted = extract_positive_int_for.call arg do |n|
        self.lib_options.max_line_captures = n
      end
      seen = [arg]
      seen << extracted if extracted
      '--number-of-captures' == arg && saw_deprecated.call("use --max-line-captures instead", *seen)

    when '-t', '--timeout-seconds', '--timeout'
      extracted = extract_non_negative_float_for.call arg do |n|
        self.timeout_seconds             = n
        self.lib_options.timeout_seconds = n
      end
      '--timeout' == arg  && saw_deprecated.call("use --timeout-seconds instead", arg, extracted)

    when '-r', '--require'
      next_arg.call arg, "a filename" do |filename|
        self.lib_options.require_files << filename
      end

    when '-I', '--load-path'
      next_arg.call arg, "a directory" do |dir|
        self.lib_options.load_path_dirs << dir
      end

    when '-e', '--program'
      next_arg.call arg, "the program body" do |program|
        self.body = program
      end

    when '-a', '--as'
      next_arg.call arg, "a filename"  do |filename|
        as = filename
      end

    when '--local-cwd'
      self.lib_options.local_cwd = true

    when '-s', '--alignment-strategy'
      strategies     = {'file' => AlignFile, 'chunk' => AlignChunk, 'line' => AlignLine}
      strategy_names = strategies.keys.inspect
      next_arg.call arg, "one of these alignment strategies: #{strategy_names}" do |name|
        if strategies[name]
          self.annotator_options.alignment_strategy = strategies[name]
        else
          add_error("#{arg} got the alignment strategy #{name.inspect}, expected one of: #{strategy_names}")
        end
      end

    when '--interline-align'
      self.annotator_options.interline_align = true

    when '--no-interline-align'
      self.annotator_options.interline_align = false

    when '--shebang'
      executable = args.shift
      if executable
        saw_deprecated.call "SiB now uses the Ruby it was invoked with", arg, executable
      else
        add_error("#{arg} expected an arg: path to a ruby executable")
        saw_deprecated.call "SiB now uses the Ruby it was invoked with", arg
      end

    when /\A-K(.+)/
      self.lib_options.encoding = $1
      encodings_are_deprecated.call arg

    when '-K', '--encoding'
      next_arg.call arg, "an encoding" do |encoding|
        self.lib_options.encoding = encoding
        encodings_are_deprecated.call arg, encoding
      end

    when /^(-.|--.*)$/
      unknown_flags << arg

    when /^-[^-]/
      needs_arg = 'adDeIKnrst'
      arg.scan(/[#{needs_arg}].*|h\+|[^-]\+?/).reverse.each do |flag|
        if flag =~ /([#{needs_arg}])(.+)/
          args.unshift "-#{$1}", $2
        else
          args.unshift "-#{flag}"
        end
      end

    else
      filenames << arg
    end
  end

  unknown_flags.each do |flag|
    break if ignore_unknown_flags?
    add_error "#{flag} is not a flag, see the help screen (-h) for a list of options"
  end

  filenames.size > 1 &&
    add_error("can only have one filename but found #{filenames.map(&:inspect).join ', '}")

  result_as_json? && annotator == AnnotateMarkedLines &&
    add_error("SiB does not currently support output with both json and xmpfilter... maybe v4 :)")

  print_event_stream? && (result_as_json? || annotator == AnnotateMarkedLines) &&
    add_error("can only have one output format, --stream is not compatible with --json, -x, and --xmpfilter-style")

  toggle_mark? && print_event_stream? &&
    add_error("--toggle-mark and --stream are mutually exclusive")

  toggle_mark? && result_as_json? &&
    add_error("--toggle-mark and --json are mutually exclusive")


  self.filename                  = filenames.first
  self.lib_options.filename      = as || filename
  self.lib_options.debugger      = debugger
  self.annotator_options.markers = markers

  self
end