Module: Smorg::RB

Defined in:
lib/smorg/rb.rb,
lib/smorg/rb/version.rb,
sig/smorg/rb.rbs

Overview

rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Modules: Version

Constant Summary collapse

EXIT_SUCCESS =
0
EXIT_UNRESOLVED_CONFLICT =
1
EXIT_USER_ERROR =
2
EXIT_INTERNAL_ERROR =
3
REVIEW_DIFF_CONTEXT_LINES =
3
MERGE_PROVIDER_OPTIONS =
{
  'bash' => {
    provider_id: 'ruby.bash', family: 'bash', dialect: 'bash', backend: 'kreuzberg-language-pack'
  },
  'go' => {
    provider_id: 'ruby.go', family: 'go', dialect: 'go', backend: 'kreuzberg-language-pack'
  },
  'html' => {
    provider_id: 'ruby.html', family: 'html', dialect: 'html', backend: 'kreuzberg-language-pack'
  },
  'dotenv' => { family: 'dotenv', dialect: 'dotenv', backend: 'dotenv-line' },
  'json' => { family: 'json', dialect: 'json' },
  'jsonc' => { family: 'json', dialect: 'jsonc' },
  'json5' => { family: 'json', dialect: 'json5' },
  'markdown' => {
    provider_id: 'ruby.markdown', family: 'markdown', dialect: 'markdown', backend: 'kreuzberg-language-pack'
  },
  'ruby' => { family: 'ruby', dialect: 'ruby', backend: 'prism' },
  'rbs' => { provider_id: 'ruby.rbs', family: 'rbs', dialect: 'rbs', backend: 'rbs' },
  'rust' => {
    provider_id: 'ruby.rust', family: 'rust', dialect: 'rust', backend: 'kreuzberg-language-pack'
  },
  'toml' => {
    provider_id: 'ruby.toml', family: 'toml', dialect: 'toml', backend: 'kreuzberg-language-pack'
  },
  'typescript' => {
    provider_id: 'ruby.typescript', family: 'typescript', dialect: 'typescript',
    backend: 'kreuzberg-language-pack'
  },
  'tsx' => {
    provider_id: 'ruby.typescript', family: 'typescript', dialect: 'tsx', backend: 'kreuzberg-language-pack'
  },
  'yaml' => { provider_id: 'ruby.yaml.psych', family: 'yaml', dialect: 'yaml', backend: 'psych' },
  'text' => { family: 'text', dialect: 'text', profile_id: 'coarse_document' }
}.freeze
LANGUAGE_BY_EXTENSION =
{
  '.bash' => 'bash', '.sh' => 'bash', '.go' => 'go', '.htm' => 'html', '.html' => 'html',
  '.rs' => 'rust', '.ts' => 'typescript', '.tsx' => 'tsx'
}.freeze
LANGUAGE_ALIASES =
{
  'bash' => 'bash', 'sh' => 'bash', 'application/x-sh' => 'bash', 'text/x-shellscript' => 'bash',
  'go' => 'go', 'golang' => 'go', 'html' => 'html', 'htm' => 'html', 'text/html' => 'html', 'html5' => 'html',
  'dotenv' => 'dotenv', 'env' => 'dotenv', 'config-env' => 'dotenv', 'json' => 'json', 'jsonc' => 'jsonc',
  'json with comments' => 'jsonc', 'json5' => 'json5', 'markdown' => 'markdown', 'md' => 'markdown',
  'gfm' => 'markdown', 'text/markdown' => 'markdown', 'ruby' => 'ruby', 'rb' => 'ruby',
  'application/x-ruby' => 'ruby', 'rbs' => 'rbs', 'rust' => 'rust', 'rs' => 'rust',
  'application/rust' => 'rust', 'text/rust' => 'rust', 'toml' => 'toml', 'application/toml' => 'toml',
  'typescript' => 'typescript', 'ts' => 'typescript', 'application/typescript' => 'typescript',
  'text/typescript' => 'typescript', 'tsx' => 'tsx', 'typescriptreact' => 'tsx', 'yaml' => 'yaml',
  'yml' => 'yaml', 'application/yaml' => 'yaml', 'text/yaml' => 'yaml', 'plain' => 'text', 'text' => 'text',
  'plaintext' => 'text', 'text/plain' => 'text'
}.freeze
ATTRIBUTE_KEYS =
{
  'smorg.language' => :language,
  'linguist-language' => :language,
  'smorg.profile' => :profile_id,
  'smorg.requireProfileStatus' => :require_profile_status
}.freeze
VERSION =

Current gem version exposed at the traditional constant location.

Returns:

  • (String)
Version::VERSION

Class Method Summary collapse

Class Method Details

.apply_attribute_field(settings, field) ⇒ Object



881
882
883
884
885
886
887
888
# File 'lib/smorg/rb.rb', line 881

def apply_attribute_field(settings, field)
  key, value = field.split('=', 2)
  return unless value
  return settings[ATTRIBUTE_KEYS[key]] = value if ATTRIBUTE_KEYS.key?(key)

  marker_size = value.to_i
  settings[:conflict_marker_size] = marker_size if key == 'conflict-marker-size' && marker_size.positive?
end

.apply_attributes(settings, path_name, source) ⇒ Object



858
859
860
861
862
# File 'lib/smorg/rb.rb', line 858

def apply_attributes(settings, path_name, source)
  source.each_line do |raw_line|
    attribute_fields(raw_line, path_name).each { |field| apply_attribute_field(settings, field) }
  end
end

.apply_merge_fallbacks(result, requested_mode, marker_size, ancestor_source, current_source, other_source) ⇒ Object



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
# File 'lib/smorg/rb.rb', line 233

def apply_merge_fallbacks(result, requested_mode, marker_size, ancestor_source, current_source, other_source)
  fallback_reason_value = fallback_reason(result.fetch(:diagnostics, []))
  git_result = merge_git_file_fallback(marker_size, ancestor_source, current_source, other_source)
  if git_result[:output]
    return [
      merge_fallback_result(result, git_result),
      [
        {
          mode: 'git_merge_file',
          requested_mode: requested_mode,
          reason: fallback_reason_value,
          applied: true
        }
      ]
    ]
  end

  plain_result = merge_plain_fallback(other_source, current_source)
  if plain_result[:ok] && plain_result[:output]
    return [
      merge_fallback_result(result, plain_result),
      [
        {
          mode: 'git_merge_file',
          requested_mode: requested_mode,
          reason: fallback_reason_value,
          applied: false
        },
        {
          mode: 'plain_text',
          requested_mode: requested_mode,
          reason: fallback_reason(git_result.fetch(:diagnostics, [])),
          applied: true
        }
      ]
    ]
  end

  [result, []]
end

.attribute_directory_paths(dir) ⇒ Object



851
852
853
854
855
856
# File 'lib/smorg/rb.rb', line 851

def attribute_directory_paths(dir)
  parts = dir.split(File::SEPARATOR).reject(&:empty?)
  parts.each_index.map do |index|
    File.join(*parts[0..index], '.gitattributes')
  end
end

.attribute_fields(raw_line, path_name) ⇒ Object



864
865
866
867
868
869
870
871
872
# File 'lib/smorg/rb.rb', line 864

def attribute_fields(raw_line, path_name)
  line = raw_line.strip
  return [] if line.empty? || line.start_with?('#')

  pattern, *fields = line.split(/\s+/)
  return [] if fields.empty? || !attribute_pattern_matches?(pattern, path_name)

  fields
end

.attribute_files_for_path(path_name) ⇒ Object



832
833
834
835
836
837
# File 'lib/smorg/rb.rb', line 832

def attribute_files_for_path(path_name)
  clean_path = normalized_attribute_path(path_name)
  return ['.gitattributes'] if root_attribute_path?(clean_path)

  ['.gitattributes', *attribute_directory_paths(File.dirname(clean_path))]
end

.attribute_pattern_matches?(pattern, path_name) ⇒ Boolean

Returns:

  • (Boolean)


890
891
892
893
894
895
896
897
898
# File 'lib/smorg/rb.rb', line 890

def attribute_pattern_matches?(pattern, path_name)
  return true if pattern == path_name

  if !pattern.include?('/')
    File.fnmatch?(pattern, File.basename(path_name))
  else
    File.fnmatch?(pattern, path_name)
  end
end

.conflict_marker_prefixes(marker_size) ⇒ Object



911
912
913
914
# File 'lib/smorg/rb.rb', line 911

def conflict_marker_prefixes(marker_size)
  size = [marker_size.to_i, 1].max
  { start: '<' * size, separator: '=' * size, end: '>' * size }
end

.conflict_region_state(current, line, line_number, prefixes) ⇒ Object



916
917
918
919
920
921
922
923
924
925
926
# File 'lib/smorg/rb.rb', line 916

def conflict_region_state(current, line, line_number, prefixes)
  if line.start_with?(prefixes[:start])
    [{ start_line: line_number, separator_line: 0 }, nil]
  elsif current && current[:separator_line].zero? && line.start_with?(prefixes[:separator])
    [current.merge(separator_line: line_number), nil]
  elsif current && line.start_with?(prefixes[:end])
    [nil, current.merge(end_line: line_number)]
  else
    [current, nil]
  end
end

.diff_source_lines(source) ⇒ Object



578
579
580
# File 'lib/smorg/rb.rb', line 578

def diff_source_lines(source)
  source.to_s.lines.to_a
end

.fallback_reason(diagnostics) ⇒ Object



470
471
472
473
474
475
# File 'lib/smorg/rb.rb', line 470

def fallback_reason(diagnostics)
  first = diagnostics.first
  return 'structured_merge_failed' unless first

  (first[:category] || first['category'] || 'structured_merge_failed').to_s
end

.find_conflict_regions(source, marker_size) ⇒ Object



900
901
902
903
904
905
906
907
908
909
# File 'lib/smorg/rb.rb', line 900

def find_conflict_regions(source, marker_size)
  prefixes = conflict_marker_prefixes(marker_size)
  regions = []
  current = nil
  source.split("\n").each_with_index do |line, index|
    current, completed = conflict_region_state(current, line, index + 1, prefixes)
    regions << completed if completed
  end
  regions
end

.full_file_conflict_output(marker_size, ancestor_source, current_source, other_source) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/smorg/rb.rb', line 355

def full_file_conflict_output(marker_size, ancestor_source, current_source, other_source)
  marker_size = marker_size.to_i
  marker_size = 7 unless marker_size.positive?
  [
    "#{'<' * marker_size} ours",
    current_source,
    "#{'|' * marker_size} base",
    ancestor_source,
    '=' * marker_size,
    other_source,
    "#{'>' * marker_size} theirs",
    ''
  ].join("\n")
end

.git_install_run_options(options) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/smorg/rb.rb', line 136

def git_install_run_options(options)
  git_drivers = if options[:check]
                  'check'
                elsif options[:undo]
                  'undo'
                elsif options.fetch(:scope) == 'global'
                  'global'
                elsif options.fetch(:scope) == 'include-file'
                  'include-file'
                elsif options.fetch(:profile) == 'builtin-diff'
                  'builtin-diff'
                else
                  'semantic-diff'
                end
  { git_drivers: git_drivers, dry_run: options[:dry_run] }.compact
end

.git_usage(stderr) ⇒ Object



106
107
108
109
# File 'lib/smorg/rb.rb', line 106

def git_usage(stderr)
  stderr.puts('usage: smorg-rb git install [--scope local|global|include-file] [--profile semantic-diff|builtin-diff] [--check] [--undo] [--dry-run] [--json]')
  EXIT_USER_ERROR
end

.language_from_path(path_name) ⇒ Object



815
816
817
818
819
820
# File 'lib/smorg/rb.rb', line 815

def language_from_path(path_name)
  extension = File.extname(path_name.to_s).downcase
  LANGUAGE_BY_EXTENSION.fetch(extension) do
    Ast::Merge.classify_template_target_path(path_name)[:family]
  end
end

.line_count(source) ⇒ Object



936
937
938
939
940
# File 'lib/smorg/rb.rb', line 936

def line_count(source)
  return 0 if source.empty?

  source.end_with?("\n") ? source.count("\n") : source.count("\n") + 1
end

.load_path_settings(path_name) ⇒ Object



822
823
824
825
826
827
828
829
830
# File 'lib/smorg/rb.rb', line 822

def load_path_settings(path_name)
  settings = { conflict_marker_size: 7 }
  attribute_files_for_path(path_name).each do |attributes_path|
    next unless File.file?(attributes_path)

    apply_attributes(settings, path_name, File.read(attributes_path))
  end
  settings
end

.merge3_report_fields(result) ⇒ Object



777
778
779
780
781
782
783
784
785
# File 'lib/smorg/rb.rb', line 777

def merge3_report_fields(result)
  {
    change_classifications: result.fetch(:change_classifications, []),
    conflicts: result.fetch(:conflicts, []),
    fallbacks: result.fetch(:fallbacks, []),
    provider: result.fetch(:provider, {}),
    verification: result.fetch(:verification, {})
  }
end

.merge3_result(result) ⇒ Object



754
755
756
757
758
759
760
761
762
# File 'lib/smorg/rb.rb', line 754

def merge3_result(result)
  if result[:ok] && result[:merged_source]
    return merge3_result_payload(result, true, result.fetch(:merged_source))
  elsif !result[:ok] && result[:conflicted_source]
    return merge3_result_payload(result, false, result.fetch(:conflicted_source))
  end

  merge3_result_payload(result, false, nil)
end

.merge3_result_payload(result, success, output) ⇒ Object



764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/smorg/rb.rb', line 764

def merge3_result_payload(result, success, output)
  payload = {
    ok: success,
    diagnostics: result.fetch(:diagnostics),
    owned_regions: result.fetch(:owned_regions, []),
    render_report: result.fetch(:render_report),
    profile: result.fetch(:profile),
    policies: [],
    **merge3_report_fields(result)
  }
  output ? payload.merge(output: output) : payload
end

.merge_by_path(path_name, language, conflict_marker_size, fallback_policy, ancestor_source, current_source, other_source) ⇒ Object



707
708
709
710
711
712
713
714
715
716
717
# File 'lib/smorg/rb.rb', line 707

def merge_by_path(path_name, language, conflict_marker_size, fallback_policy, ancestor_source, current_source,
                  other_source)
  normalized_language = normalize_language(language, path_name)
  provider_options = MERGE_PROVIDER_OPTIONS[normalized_language]
  return unsupported_language_result(normalized_language, path_name) unless provider_options

  merge_with_provider(
    path_name, provider_options,
    merge_options_for(ancestor_source, current_source, other_source, fallback_policy, conflict_marker_size)
  )
end

.merge_driver_fallback_eligible?(result, options) ⇒ Boolean

Returns:

  • (Boolean)


274
275
276
277
278
279
280
# File 'lib/smorg/rb.rb', line 274

def merge_driver_fallback_eligible?(result, options)
  return false if result[:ok] || options[:strict] || options[:fallback] == 'none'

  result.fetch(:diagnostics, []).any? do |diagnostic|
    (diagnostic[:category] || diagnostic['category']).to_s == 'unsupported_language'
  end
end

.merge_fallback_result(original_result, fallback_result) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
# File 'lib/smorg/rb.rb', line 343

def merge_fallback_result(original_result, fallback_result)
  original_diagnostics = original_result.fetch(:diagnostics, [])
  fallback_diagnostics = fallback_result.fetch(:diagnostics, [])
  {
    **original_result,
    ok: fallback_result[:ok],
    diagnostics: original_diagnostics + fallback_diagnostics,
    output: fallback_result[:output],
    policies: fallback_result.fetch(:policies, original_result.fetch(:policies, []))
  }
end

.merge_git_file_fallback(marker_size, ancestor_source, current_source, other_source) ⇒ Object



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
340
341
# File 'lib/smorg/rb.rb', line 292

def merge_git_file_fallback(marker_size, ancestor_source, current_source, other_source)
  require 'tempfile'

  files = Array.new(3) { Tempfile.new('smorg-rb-merge-file') }
  files[0].write(current_source)
  files[1].write(ancestor_source)
  files[2].write(other_source)
  files.each(&:flush)
  output = IO.popen(
    [
      'git',
      'merge-file',
      '-p',
      '-L',
      'ours',
      '-L',
      'base',
      '-L',
      'theirs',
      "--marker-size=#{marker_size}",
      files[0].path,
      files[1].path,
      files[2].path
    ],
    err: %i[child out],
    &:read
  )
  {
    ok: $CHILD_STATUS.success?,
    diagnostics: if $CHILD_STATUS.success?
                   []
                 else
                   [{ severity: 'error', category: 'git_merge_file_conflict',
                      message: 'git merge-file reported unresolved conflicts' }]
                 end,
    output: output,
    policies: []
  }
rescue Errno::ENOENT => e
  {
    ok: false,
    diagnostics: [{ severity: 'error', category: 'git_merge_file_unavailable', message: e.message }],
    policies: []
  }
ensure
  files&.each do |file|
    file.close
    file.unlink
  end
end

.merge_options_for(ancestor_source, current_source, other_source, fallback_policy, conflict_marker_size) ⇒ Object



719
720
721
722
723
724
725
726
727
# File 'lib/smorg/rb.rb', line 719

def merge_options_for(ancestor_source, current_source, other_source, fallback_policy, conflict_marker_size)
  {
    base_source: ancestor_source,
    ours_source: current_source,
    theirs_source: other_source,
    fallback_policy: fallback_policy,
    conflict_marker_size: conflict_marker_size
  }
end

.merge_plain_fallback(other_source, current_source) ⇒ Object



282
283
284
285
286
287
288
289
290
# File 'lib/smorg/rb.rb', line 282

def merge_plain_fallback(other_source, current_source)
  Plain::Merge.merge_text(other_source, current_source)
rescue StandardError => e
  {
    ok: false,
    diagnostics: [{ severity: 'error', category: 'plain_text_fallback_error', message: e.message }],
    policies: []
  }
end

.merge_with_provider(path_name, provider_options, merge_options) ⇒ Object



729
730
731
732
733
734
735
736
737
738
# File 'lib/smorg/rb.rb', line 729

def merge_with_provider(path_name, provider_options, merge_options)
  merge3_result(
    Ast::Merge::Git.merge3(
      **merge_options,
      path_name: path_name,
      profile_id: provider_options.fetch(:profile_id, 'source_preserving'),
      **provider_options.except(:profile_id)
    )
  )
end

.normalize_language(language, path_name) ⇒ Object



787
788
789
790
791
792
793
794
# File 'lib/smorg/rb.rb', line 787

def normalize_language(language, path_name)
  normalized_language = language.to_s.strip.downcase
  return language_from_path(path_name) if normalized_language.empty?

  LANGUAGE_ALIASES.fetch(normalized_language) do
    Ast::Merge.classify_template_target_path(path_name)[:family]
  end
end

.normalized_attribute_path(path_name) ⇒ Object



839
840
841
842
843
844
# File 'lib/smorg/rb.rb', line 839

def normalized_attribute_path(path_name)
  expanded_path = File.expand_path(path_name, Dir.pwd)
  return Pathname.new(path_name).cleanpath.to_s if expanded_path.start_with?(Dir.pwd)

  path_name
end

.parse_conflicts_diff_options(args, stderr) ⇒ Object



611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/smorg/rb.rb', line 611

def parse_conflicts_diff_options(args, stderr)
  options = { exit_code: false }
  positionals = []
  index = 0
  while index < args.length
    value = args[index]
    case value
    when '--path-name'
      index += 1
      options[:path_name] = args[index]
    when '--exit-code'
      options[:exit_code] = true
    else
      if value.start_with?('--')
        stderr.puts("unknown conflicts diff option #{value.inspect}")
        return nil
      end
      positionals << value
    end
    index += 1
  end
  if positionals.length != 1
    stderr.puts('conflicts diff requires exactly one file path')
    return nil
  end
  options.merge(file_path: positionals[0])
end

.parse_diff_driver_options(args, stderr) ⇒ Object



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/smorg/rb.rb', line 521

def parse_diff_driver_options(args, stderr)
  options = {}
  positionals = []
  index = 0
  while index < args.length
    value = args[index]
    if value == '--path-name'
      index += 1
      options[:path_name] = args[index]
    elsif value.start_with?('--')
      stderr.puts("unknown diff-driver option #{value.inspect}")
      return nil
    else
      positionals << value
    end
    index += 1
  end

  case positionals.length
  when 2
    options.merge(old_path: positionals[0], new_path: positionals[1])
  when 7, 9
    options.merge(path_name: options[:path_name] || positionals[0], old_path: positionals[1],
                  new_path: positionals[4])
  else
    stderr.puts('diff-driver requires either 2, 7, or 9 positional arguments')
    nil
  end
end

.parse_git_install_options(args, stderr) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/smorg/rb.rb', line 111

def parse_git_install_options(args, stderr)
  options = { scope: 'local', profile: 'semantic-diff', json: false, dry_run: false }
  until args.empty?
    value = args.shift
    case value
    when '--scope'
      options[:scope] = args.shift.to_s
    when '--profile'
      options[:profile] = args.shift.to_s
    when '--check'
      options[:check] = true
    when '--undo'
      options[:undo] = true
    when '--dry-run'
      options[:dry_run] = true
    when '--json'
      options[:json] = true
    else
      stderr.puts("unknown git install option #{value.inspect}")
      return nil
    end
  end
  options
end

.parse_merge_driver_options(args, stderr) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/smorg/rb.rb', line 370

def parse_merge_driver_options(args, stderr)
  options = { strict: false, fallback: 'full-file', check_only: false, exit_code: false, profile_report: false }
  positionals = []
  index = 0
  while index < args.length
    value = args[index]
    case value
    when '--ancestor'
      index += 1
      options[:ancestor] = args[index]
    when '--current'
      index += 1
      options[:current] = args[index]
    when '--other'
      index += 1
      options[:other] = args[index]
    when '--path-name'
      index += 1
      options[:path_name] = args[index]
    when '--output'
      index += 1
      options[:output] = args[index]
    when '--report'
      index += 1
      options[:report] = args[index]
    when '--strict'
      options[:strict] = true
    when '--check-only'
      options[:check_only] = true
    when '--exit-code'
      options[:exit_code] = true
    when '--profile'
      index += 1
      options[:profile_id] = args[index]
    when '--profile-report'
      options[:profile_report] = true
    when '--require-profile-status'
      index += 1
      options[:require_profile_status] = args[index]
    when '--fallback'
      index += 1
      options[:fallback] = args[index]
    else
      if value.start_with?('--fallback=')
        options[:fallback] = value.delete_prefix('--fallback=')
      elsif value.start_with?('--')
        stderr.puts("unknown merge-driver option #{value.inspect}")
        return nil
      else
        positionals << value
      end
    end
    index += 1
  end

  options[:ancestor] ||= positionals[0]
  options[:current] ||= positionals[1]
  options[:other] ||= positionals[2]
  options[:path_name] ||= positionals[3]

  unless options[:ancestor] && options[:current] && options[:other]
    stderr.puts('merge-driver requires ancestor, current, and other paths')
    return nil
  end
  unless %w[none line local full-file].include?(options[:fallback])
    stderr.puts("unsupported fallback mode #{options[:fallback].inspect}")
    return nil
  end
  options
end


928
929
930
931
932
933
934
# File 'lib/smorg/rb.rb', line 928

def print_conflict_diff(stdout, path_name, regions)
  stdout.puts("conflicts #{path_name}")
  stdout.puts("count #{regions.length}")
  regions.each_with_index do |region, index|
    stdout.puts("conflict #{index + 1} lines #{region[:start_line]}-#{region[:end_line]} separator #{region[:separator_line]}")
  end
end


942
943
944
945
946
# File 'lib/smorg/rb.rb', line 942

def print_diagnostics(stderr, result)
  result.fetch(:diagnostics, []).each do |diagnostic|
    stderr.puts("#{diagnostic[:category]}: #{diagnostic[:message]}")
  end
end


551
552
553
554
555
556
557
558
559
560
561
# File 'lib/smorg/rb.rb', line 551

def print_structured_diff(stdout, path_name, old_source, new_source)
  stdout.puts("structured-diff #{path_name}")
  if old_source == new_source
    stdout.puts('status unchanged')
  else
    stdout.puts('status changed')
    stdout.puts("old-lines #{line_count(old_source)}")
    stdout.puts("new-lines #{line_count(new_source)}")
    print_structured_diff_review_hunk(stdout, path_name, old_source, new_source)
  end
end


563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/smorg/rb.rb', line 563

def print_structured_diff_review_hunk(stdout, path_name, old_source, new_source)
  old_lines = diff_source_lines(old_source)
  new_lines = diff_source_lines(new_source)
  stdout.puts('review-diff unified')
  stdout.puts("--- a/#{path_name}")
  stdout.puts("+++ b/#{path_name}")

  file_length_difference = 0
  Diff::LCS.diff(old_lines, new_lines).each do |piece|
    hunk = Diff::LCS::Hunk.new(old_lines, new_lines, piece, REVIEW_DIFF_CONTEXT_LINES, file_length_difference)
    file_length_difference = hunk.file_length_difference
    write_diff_text(stdout, hunk.diff(:unified))
  end
end


58
59
60
61
62
63
64
65
66
# File 'lib/smorg/rb.rb', line 58

def print_usage(out)
  out.puts('usage: smorg-rb merge-driver [--path-name PATH] [--output PATH] [--report PATH] [--strict] [--fallback=none|line|local|full-file] %O %A %B [%P]')
  out.puts('       smorg-rb merge-driver --ancestor %O --current %A --other %B --path-name %P')
  out.puts('       smorg-rb diff-driver [--path-name PATH] OLD NEW')
  out.puts('       smorg-rb diff-driver PATH OLD-FILE OLD-HEX OLD-MODE NEW-FILE NEW-HEX NEW-MODE [OLD-PREFIX NEW-PREFIX]')
  out.puts('       smorg-rb conflicts diff [--path-name PATH] [--exit-code] FILE')
  out.puts('       smorg-rb languages --gitattributes')
  out.puts('       smorg-rb git install [--scope local|global|include-file] [--profile semantic-diff|builtin-diff] [--check] [--undo] [--dry-run] [--json]')
end

.report_and_enforce_profile(options, stdout, stderr) ⇒ Object



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/smorg/rb.rb', line 477

def report_and_enforce_profile(options, stdout, stderr)
  return EXIT_SUCCESS unless options[:profile_id] || options[:profile_report] || options[:require_profile_status]

  profile_id = options[:profile_id] || Ast::Merge::PROMOTION_PROFILE_JSON_KEYED_OBJECT
  evaluation = Ast::Merge::ProfilePromotionEvaluation.new(
    profile_id: profile_id,
    status: 'available',
    blocking_reasons: ['profile promotion evidence is not loaded by this CLI command'],
    diagnostics: []
  )
  decision = Ast::Merge.evaluate_profile_selection_requirement(
    Ast::Merge::ProfileSelectionRequirement.new(
      profile_id: profile_id,
      promotion_policy_id: Ast::Merge.initial_profile_promotion_policy.policy_id,
      minimum_profile_status: options[:require_profile_status] || 'available',
      enforcement_mode: options[:require_profile_status] ? 'required' : 'advisory'
    ),
    nil,
    evaluation
  )
  stdout.puts(JSON.generate(Ast::Merge.json_ready(decision.to_h))) if options[:profile_report]
  unless decision.allowed
    stderr.puts(decision.blocking_reasons.first)
    return EXIT_USER_ERROR
  end
  EXIT_SUCCESS
end

.root_attribute_path?(clean_path) ⇒ Boolean

Returns:

  • (Boolean)


846
847
848
849
# File 'lib/smorg/rb.rb', line 846

def root_attribute_path?(clean_path)
  dir = File.dirname(clean_path)
  dir == '.' || clean_path.start_with?('..') || Pathname.new(clean_path).absolute?
end

.run(args, stdout: $stdout, stderr: $stderr) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/smorg/rb.rb', line 35

def run(args, stdout: $stdout, stderr: $stderr)
  command, *rest = args
  case command
  when 'merge-driver'
    run_merge_driver(rest, stdout, stderr)
  when 'diff-driver'
    run_diff_driver(rest, stdout, stderr)
  when 'conflicts'
    run_conflicts(rest, stdout, stderr)
  when 'languages'
    run_languages(rest, stdout, stderr)
  when 'git'
    run_git(rest, stdout, stderr)
  when 'help', '-h', '--help'
    print_usage(stdout)
    EXIT_SUCCESS
  else
    stderr.puts("unknown command #{command.inspect}") if command
    print_usage(stderr)
    EXIT_USER_ERROR
  end
end

.run_conflicts(args, stdout, stderr) ⇒ Object



589
590
591
592
593
594
595
# File 'lib/smorg/rb.rb', line 589

def run_conflicts(args, stdout, stderr)
  subcommand, *rest = args
  return run_conflicts_diff(rest, stdout, stderr) if subcommand == 'diff'

  stderr.puts('conflicts requires the diff subcommand')
  EXIT_USER_ERROR
end

.run_conflicts_diff(args, stdout, stderr) ⇒ Object



597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/smorg/rb.rb', line 597

def run_conflicts_diff(args, stdout, stderr)
  options = parse_conflicts_diff_options(args, stderr)
  return EXIT_USER_ERROR unless options

  effective_path = options[:path_name] || options[:file_path]
  settings = load_path_settings(effective_path)
  regions = find_conflict_regions(File.read(options[:file_path]), settings[:conflict_marker_size])
  print_conflict_diff(stdout, effective_path, regions)
  options[:exit_code] && !regions.empty? ? EXIT_UNRESOLVED_CONFLICT : EXIT_SUCCESS
rescue Errno::ENOENT, Errno::EACCES => e
  stderr.puts("read conflicted file: #{e.message}")
  EXIT_USER_ERROR
end

.run_diff_driver(args, stdout, stderr) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/smorg/rb.rb', line 505

def run_diff_driver(args, stdout, stderr)
  options = parse_diff_driver_options(args, stderr)
  return EXIT_USER_ERROR unless options

  print_structured_diff(
    stdout,
    options[:path_name] || options[:new_path],
    File.read(options[:old_path]),
    File.read(options[:new_path])
  )
  EXIT_SUCCESS
rescue Errno::ENOENT, Errno::EACCES => e
  stderr.puts("read diff input: #{e.message}")
  EXIT_USER_ERROR
end

.run_git(args, stdout, stderr) ⇒ Object



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
# File 'lib/smorg/rb.rb', line 68

def run_git(args, stdout, stderr)
  subcommand, *rest = args
  return git_usage(stderr) unless subcommand == 'install'

  options = parse_git_install_options(rest, stderr)
  return EXIT_USER_ERROR unless options

  run_options = git_install_run_options(options)
  step = Kettle::Jem::Tasks::InstallTask.git_drivers_step(Dir.pwd, run_options)
  step = Kettle::Jem::Tasks::InstallTask.execute_orchestration_steps(
    [step],
    project_root: Dir.pwd,
    env: ENV.to_h,
    run_options: run_options,
    command_runner: Kettle::Jem::Tasks::InstallTask.method(:run_system_command)
  ).first
  report = {
    report_version: 1,
    ok: step.fetch(:status) != 'failed',
    profile: step.fetch(:profile, 'semantic-diff'),
    scope: step.fetch(:scope, run_options.fetch(:git_drivers, 'local')),
    install_steps: [step],
    missing: step.fetch(:missing, [])
  }
  if options[:json]
    stdout.puts(JSON.pretty_generate(report))
  else
    stdout.puts("git install: #{step.fetch(:status)} #{report.fetch(:profile)} #{report.fetch(:scope)}")
    step.fetch(:diagnostics, []).each do |diagnostic|
      stdout.puts("  #{diagnostic.fetch(:message)}") if diagnostic[:message]
    end
  end
  report.fetch(:ok) ? EXIT_SUCCESS : EXIT_USER_ERROR
rescue Kettle::Jem::Error => e
  stderr.puts(e.message)
  EXIT_USER_ERROR
end

.run_languages(args, stdout, stderr) ⇒ Object



639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/smorg/rb.rb', line 639

def run_languages(args, stdout, stderr)
  unless args == ['--gitattributes']
    stderr.puts('languages currently requires --gitattributes')
    return EXIT_USER_ERROR
  end

  [
    '*.bash merge=smorg-rb diff=smorg-rb smorg.language=bash',
    '*.go merge=smorg-rb diff=smorg-rb smorg.language=go',
    '*.htm merge=smorg-rb diff=smorg-rb smorg.language=html',
    '*.html merge=smorg-rb diff=smorg-rb smorg.language=html',
    '*.env merge=smorg-rb diff=smorg-rb smorg.language=dotenv',
    '.env merge=smorg-rb diff=smorg-rb smorg.language=dotenv',
    '.env.* merge=smorg-rb diff=smorg-rb smorg.language=dotenv',
    '*.json merge=smorg-rb diff=smorg-rb smorg.language=json',
    '*.jsonc merge=smorg-rb diff=smorg-rb smorg.language=jsonc',
    '*.json5 merge=smorg-rb diff=smorg-rb smorg.language=json5',
    '*.md merge=smorg-rb diff=smorg-rb smorg.language=markdown',
    '*.markdown merge=smorg-rb diff=smorg-rb smorg.language=markdown',
    '*.rb merge=smorg-rb diff=smorg-rb smorg.language=ruby',
    '*.rbs merge=smorg-rb diff=smorg-rb smorg.language=rbs',
    '*.rs merge=smorg-rb diff=smorg-rb smorg.language=rust',
    '*.sh merge=smorg-rb diff=smorg-rb smorg.language=bash',
    '*.toml merge=smorg-rb diff=smorg-rb smorg.language=toml',
    '*.ts merge=smorg-rb diff=smorg-rb smorg.language=typescript',
    '*.tsx merge=smorg-rb diff=smorg-rb smorg.language=tsx',
    '*.yml merge=smorg-rb diff=smorg-rb smorg.language=yaml',
    '*.yaml merge=smorg-rb diff=smorg-rb smorg.language=yaml'
  ].each { |line| stdout.puts(line) }
  EXIT_SUCCESS
end

.run_merge_driver(args, stdout, stderr) ⇒ Object



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
# File 'lib/smorg/rb.rb', line 153

def run_merge_driver(args, stdout, stderr)
  options = parse_merge_driver_options(args, stderr)
  return EXIT_USER_ERROR unless options

  ancestor_source = File.read(options[:ancestor])
  current_source = File.read(options[:current])
  other_source = File.read(options[:other])

  effective_path = options[:path_name] || options[:current]
  settings = load_path_settings(effective_path)
  options[:profile_id] ||= settings[:profile_id]
  options[:require_profile_status] ||= settings[:require_profile_status]
  profile_exit = report_and_enforce_profile(options, stdout, stderr)
  return profile_exit unless profile_exit == EXIT_SUCCESS

  fallback_policy = options[:strict] ? 'none' : options[:fallback]
  result = merge_by_path(effective_path, settings[:language], settings[:conflict_marker_size], fallback_policy,
                         ancestor_source, current_source, other_source)
  fallbacks = []
  if merge_driver_fallback_eligible?(result, options)
    result, fallbacks = apply_merge_fallbacks(
      result,
      options[:fallback],
      settings[:conflict_marker_size],
      ancestor_source,
      current_source,
      other_source
    )
  end
  output = result[:output]
  unless result[:ok]
    print_diagnostics(stderr, result)
    unless options[:strict] || options[:fallback] == 'none'
      output ||= full_file_conflict_output(settings[:conflict_marker_size], ancestor_source, current_source,
                                           other_source)
    end
    if output && !result[:output] && !options[:strict] && options[:fallback] != 'none'
      fallbacks << {
        mode: 'full_file',
        requested_mode: options[:fallback],
        reason: fallback_reason(result.fetch(:diagnostics, [])),
        applied: true
      }
    end
    report_exit = write_merge_driver_machine_report(options[:report], effective_path, false,
                                                    EXIT_UNRESOLVED_CONFLICT, fallbacks, result, stderr)
    return report_exit unless report_exit == EXIT_SUCCESS
    return EXIT_UNRESOLVED_CONFLICT if options[:check_only]

    File.write(options[:output] || options[:current], output) if output
    return EXIT_UNRESOLVED_CONFLICT
  end
  unless output
    stderr.puts('merge completed without output')
    return EXIT_INTERNAL_ERROR
  end

  if options[:check_only]
    exit_code = options[:exit_code] && output != current_source ? EXIT_UNRESOLVED_CONFLICT : EXIT_SUCCESS
    report_exit = write_merge_driver_machine_report(options[:report], effective_path, true, exit_code, fallbacks,
                                                    result, stderr)
    return report_exit unless report_exit == EXIT_SUCCESS

    return exit_code
  end

  File.write(options[:output] || options[:current], output)
  report_exit = write_merge_driver_machine_report(options[:report], effective_path, true, EXIT_SUCCESS, fallbacks,
                                                  result, stderr)
  return report_exit unless report_exit == EXIT_SUCCESS

  EXIT_SUCCESS
rescue Errno::ENOENT, Errno::EACCES => e
  stderr.puts("file error: #{e.message}")
  EXIT_USER_ERROR
rescue StandardError => e
  stderr.puts("internal error: #{e.message}")
  EXIT_INTERNAL_ERROR
end

.unsupported_language_result(language, path_name) ⇒ Object



740
741
742
743
744
745
746
747
748
749
750
751
752
# File 'lib/smorg/rb.rb', line 740

def unsupported_language_result(language, path_name)
  {
    ok: false,
    diagnostics: [
      {
        severity: 'error',
        category: 'unsupported_language',
        message: "no structured merge driver is configured for #{language.inspect} at #{path_name}"
      }
    ],
    policies: []
  }
end

.write_diff_text(stdout, text) ⇒ Object



582
583
584
585
586
587
# File 'lib/smorg/rb.rb', line 582

def write_diff_text(stdout, text)
  return if text.to_s.empty?

  stdout.write(text)
  stdout.write("\n") unless text.end_with?("\n")
end

.write_merge_driver_machine_report(report_path, path_name, ok, exit_code, fallbacks, result, stderr) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/smorg/rb.rb', line 441

def write_merge_driver_machine_report(report_path, path_name, ok, exit_code, fallbacks, result, stderr)
  return EXIT_SUCCESS unless report_path

  report = {
    command: 'merge-driver',
    path_name: path_name,
    ok: ok,
    exit_code: exit_code,
    fallbacks: result.fetch(:fallbacks, []) + fallbacks,
    conflicts: result.fetch(:conflicts, []),
    change_classifications: result.fetch(:change_classifications, []),
    owned_regions: result.fetch(:owned_regions, []),
    render_report: result[:render_report],
    reparse_after_render: result[:reparse_after_render],
    formatting_preservation: result[:formatting_preservation],
    secondary_formatting_metrics: result[:secondary_formatting_metrics],
    default_driver_evaluation: result[:default_driver_evaluation],
    profile: result[:profile],
    provider: result[:provider],
    verification: result[:verification],
    diagnostics: result.fetch(:diagnostics, [])
  }
  File.write(report_path, "#{JSON.pretty_generate(Ast::Merge.json_ready(report))}\n")
  EXIT_SUCCESS
rescue StandardError => e
  stderr.puts("write report: #{e.message}")
  EXIT_INTERNAL_ERROR
end