Module: Kettle::Jem::Tasks::InstallTask

Defined in:
lib/kettle/jem/tasks/install_task.rb

Constant Summary collapse

CURATED_BINSTUB_GEMS =
%w[appraisal2 rake rbs rspec-core yard kettle-dev kettle-test kettle-soup-cover kettle-gha-pins stone_checksums].freeze
CURATED_BINSTUB_DISCRETE_EXECUTABLES =
%w[
  kettle-drift
  yard
].freeze
GIT_OPERATION_LOCK_ENV_KEYS =
%w[KETTLE_JEM_GIT_LOCK KETTLE_JEM_GIT_COMMIT_LOCK].freeze
GIT_OPERATION_LOCK_RETRY_ATTEMPTS =
5
GIT_OPERATION_LOCK_RETRY_SLEEP_SECONDS =
0.25
DEFAULT_GIT_DRIVER_DEFINITIONS =
Ractor.make_shareable([
  {
    language: "ruby",
    pattern: "*.rb",
    diff: "smorg-rb",
    merge: "smorg-rb",
    diff_command: "smorg-rb diff-driver",
    merge_command: "smorg-rb merge-driver %O %A %B %P"
  },
  {
    language: "go",
    pattern: "*.go",
    diff: "smorg-go",
    merge: "smorg-go",
    diff_command: "smorg-go diff-driver",
    merge_command: "smorg-go merge-driver %O %A %B %P"
  },
  {
    language: "rust",
    pattern: "*.rs",
    diff: "smorg-rs",
    merge: "smorg-rs",
    diff_command: "smorg-rs diff-driver",
    merge_command: "smorg-rs merge-driver %O %A %B %P"
  }
])
GIT_DRIVER_LANGUAGE_REGISTRY =
Ractor.make_shareable(DEFAULT_GIT_DRIVER_DEFINITIONS.to_h { |definition| [definition.fetch(:language), definition] })
BUILTIN_GIT_DIFF_ATTRIBUTES =
Ractor.make_shareable([
  {path: ".gitattributes", pattern: "*.rb", attributes: {"diff" => "ruby"}},
  {path: ".gitattributes", pattern: "*.go", attributes: {"diff" => "golang"}},
  {path: ".gitattributes", pattern: "*.rs", attributes: {"diff" => "rust"}}
])

Class Method Summary collapse

Class Method Details

.apply_direct_sibling_lockfile_env!(project_root, command_env) ⇒ Object



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
# File 'lib/kettle/jem/tasks/install_task.rb', line 999

def apply_direct_sibling_lockfile_env!(project_root, command_env)
  gemspec_path = Dir.glob(File.join(project_root.to_s, "*.gemspec")).min
  return unless gemspec_path

   = Kettle::Jem.send(:project_gemspec_metadata, project_root, gemspec_path)
  package_name = [:gem_name] || ["gem_name"] || File.basename(gemspec_path, ".gemspec")
  direct_sibling_gems = Kettle::Jem.send(
    :direct_sibling_runtime_gems,
    project_root,
    ,
    package_name: package_name
  )
  return if direct_sibling_gems.empty?

  source_url = [:source_code_uri] || ["source_code_uri"] ||
    [:homepage] || ["homepage"]
  workspace_slug = Kettle::Jem.send(:direct_sibling_workspace_slug, source_url, project_root)
  prefix = workspace_slug.to_s.upcase.tr("-", "_")
  prefix = "LOCAL" if prefix.empty?
  dev_env = "#{prefix}_DEV"
  command_env[dev_env] = File.expand_path("..", project_root.to_s) if local_env_disabled?(command_env[dev_env])
end

.apply_kettle_family_appraisal_workers!(command_env) ⇒ Object

Appraisal generation is an install finishing step, so it runs after template recipe/file pools have completed. In a family template wave, keep its worker count within the same member budget unless the caller deliberately selected APPRAISAL_JOBS.



1347
1348
1349
1350
1351
1352
# File 'lib/kettle/jem/tasks/install_task.rb', line 1347

def apply_kettle_family_appraisal_workers!(command_env)
  return if command_env.key?("APPRAISAL_JOBS")
  return unless Kettle::Jem::Tasks::TemplateTask.family_wave_jobs(command_env)

  command_env["APPRAISAL_JOBS"] = Kettle::Jem::Tasks::TemplateTask.default_thread_worker_count(command_env).to_s
end

.apply_kettle_family_local_install_env!(command_env) ⇒ Object



1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
# File 'lib/kettle/jem/tasks/install_task.rb', line 1328

def apply_kettle_family_local_install_env!(command_env)
  return unless command_env.fetch("K_JEM_TEMPLATING", "false").casecmp("true").zero?

  marker = kettle_family_local_install_marker(command_env)
  return unless Array(marker["installed_members"]).include?("kettle-jem")

  members_root = marker["members_root"].to_s
  if !command_env.key?("STRUCTUREDMERGE_DEV") && Dir.exist?(File.join(members_root, "kettle-jem"))
    command_env["STRUCTUREDMERGE_DEV"] = members_root
  end

  kettle_root = kettle_family_dependency_root(marker)
  command_env["KETTLE_DEV_DEV"] = kettle_root if kettle_root && !command_env.key?("KETTLE_DEV_DEV")
end

.appraisal_generate_step(project_root, env: nil, run_options: {}) ⇒ Object



688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/kettle/jem/tasks/install_task.rb', line 688

def appraisal_generate_step(project_root, env: nil, run_options: {})
  if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_appraisal_generate])
    return {
      name: "appraisal_generate",
      status: "skipped",
      reason: "skip_appraisal_generate"
    }
  end

  unless Array((run_options || {})[:only]).empty?
    return {
      name: "appraisal_generate",
      status: "skipped",
      reason: "template_selection"
    }
  end

  unless File.file?(File.join(project_root.to_s, "Appraisals")) && File.file?(File.join(project_root.to_s, "bin", "rake"))
    return {
      name: "appraisal_generate",
      status: "skipped",
      reason: "missing_appraisals_entrypoint"
    }
  end

  unless rake_task_available?(project_root, "appraisal:generate", env: env)
    return {
      name: "appraisal_generate",
      status: "skipped",
      reason: "missing_appraisal_generate_task"
    }
  end

  {
    name: "appraisal_generate",
    command: ["bin/rake", "appraisal:generate"],
    status: "ready",
    reason: "post_template_appraisal_generation"
  }
end

.bin_setup_command(project_root, quiet:) ⇒ Object



1905
1906
1907
1908
1909
# File 'lib/kettle/jem/tasks/install_task.rb', line 1905

def bin_setup_command(project_root, quiet:)
  command = [File.join("bin", "setup")]
  command << "--quiet" if quiet && File.exist?(File.join(project_root, "bin", "setup"))
  command
end

.binstub_files(bin_dir) ⇒ Object



1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/kettle/jem/tasks/install_task.rb', line 1166

def binstub_files(bin_dir)
  return [] unless File.directory?(bin_dir)

  Dir.glob(File.join(bin_dir, "*")).select do |path|
    next false unless File.file?(path)
    next false if File.basename(path) == "setup"

    content = File.read(path, 256)
    content.start_with?("#!") && content.include?("ruby")
  rescue
    false
  end
end

.bootstrap_commit_step(project_root, run_options:) ⇒ Object



1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
# File 'lib/kettle/jem/tasks/install_task.rb', line 1813

def bootstrap_commit_step(project_root, run_options:)
  if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_commit])
    return {
      name: "bootstrap_commit",
      status: "skipped",
      reason: "skip_commit"
    }
  end

  unless git_success?(project_root, "rev-parse", "--is-inside-work-tree")
    return {
      name: "bootstrap_commit",
      status: "unavailable",
      reason: "not_git_repository"
    }
  end

  dirty_entries = git_output(project_root, "status", "--porcelain").lines.map(&:chomp).reject(&:empty?)
  if dirty_entries.empty?
    return {
      name: "bootstrap_commit",
      status: "clean_noop",
      dirty_entries: []
    }
  end

  commands = []
  commands << %w[git add -A -- .]
  commands << ["git", "commit", "-m", "🎨 Template bootstrap by kettle-jem v#{Kettle::Jem::Version::VERSION}"]
  {
    name: "bootstrap_commit",
    status: "ready",
    dirty_entries: dirty_entries,
    commands: commands,
    reason: "ready_for_orchestration"
  }
end

.bundle_binstubs_command(project_root = Dir.pwd, env: ENV) ⇒ Object



729
730
731
# File 'lib/kettle/jem/tasks/install_task.rb', line 729

def bundle_binstubs_command(project_root = Dir.pwd, env: ENV)
  %w[bundle binstubs] + curated_binstub_gems_in_bundle(project_root, env: env)
end

.bundle_env_fingerprint(env) ⇒ Object



1320
1321
1322
# File 'lib/kettle/jem/tasks/install_task.rb', line 1320

def bundle_env_fingerprint(env)
  env.to_h.transform_values { |value| value&.to_s }.reject { |key, _value| ignored_bundle_env_key?(key) }
end

.bundle_includes_gem?(project_root, gem_name, env: ENV) ⇒ Boolean

Returns:

  • (Boolean)


741
742
743
744
745
746
# File 'lib/kettle/jem/tasks/install_task.rb', line 741

def bundle_includes_gem?(project_root, gem_name, env: ENV)
  stdout, _stderr, status = Open3.capture3(env.to_h, "bundle", "list", "--name-only", chdir: project_root.to_s)
  return true unless status.success?

  stdout.lines.map(&:strip).include?(gem_name.to_s)
end

.bundled_handoff_command(run_options) ⇒ Object



1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
# File 'lib/kettle/jem/tasks/install_task.rb', line 1885

def bundled_handoff_command(run_options)
  [
    "bundle",
    "exec",
    "ruby",
    "-e",
    %(load Gem.bin_path("kettle-jem", "kettle-jem")),
    "--"
  ] + handoff_argv(run_options)
end

.bundled_handoff_step(project_root:, env:, run_options:) ⇒ Object



1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
# File 'lib/kettle/jem/tasks/install_task.rb', line 1778

def bundled_handoff_step(project_root:, env:, run_options:)
  if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:bootstrap_mode])
    return {
      name: "bundled_handoff",
      status: "skipped",
      reason: "bootstrap_mode"
    }
  end

  bundle_gemfile = (env || {})["BUNDLE_GEMFILE"].to_s.strip
  project_gemfile = File.expand_path(File.join(project_root.to_s, "Gemfile"))
  if !bundle_gemfile.empty? && File.expand_path(bundle_gemfile) == project_gemfile
    return {
      name: "bundled_handoff",
      status: "already_bundled",
      bundle_gemfile: bundle_gemfile
    }
  end

  unless bundle_includes_gem?(project_root, "kettle-jem", env: setup_command_env(project_root, env))
    return {
      name: "bundled_handoff",
      status: "skipped",
      reason: "kettle_jem_not_in_bundle"
    }
  end

  {
    name: "bundled_handoff",
    command: bundled_handoff_command(run_options),
    status: "ready",
    reason: "ready_for_orchestration"
  }
end

.bundler_binstub_gem_name(path) ⇒ Object



1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/kettle/jem/tasks/install_task.rb', line 1194

def bundler_binstub_gem_name(path)
  content = File.read(path)
  return unless content.include?("This file was generated by Bundler")

  Kettle::Jem.ruby_call_records(content, :bin_path).filter_map do |call|
    next unless call.receiver&.slice == "Gem"

    argument = call.arguments&.arguments&.first
    next unless argument.is_a?(::Prism::StringNode)

    argument.unescaped
  end.first
rescue
  nil
end

.bundler_command_env(project_root, env) ⇒ Object



1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
# File 'lib/kettle/jem/tasks/install_task.rb', line 1302

def bundler_command_env(project_root, env)
  command_env = (env || {}).to_h.dup
  requested_bundler_version = command_env["KJ_BUNDLER_VERSION"].to_s.strip
  disable_checksum_validation = command_env["BUNDLE_DISABLE_CHECKSUM_VALIDATION"]
  strip_inherited_bundler_activation!(command_env)
  command_env["BUNDLER_VERSION"] = requested_bundler_version unless requested_bundler_version.empty?
  gemfile = File.join(project_root.to_s, "Gemfile")
  command_env["BUNDLE_GEMFILE"] = gemfile if File.file?(gemfile)
  command_env["BUNDLE_DISABLE_CHECKSUM_VALIDATION"] = disable_checksum_validation unless disable_checksum_validation.nil?
  command_env["K_JEM_TEMPLATING"] = "false" unless command_env.key?("K_JEM_TEMPLATING")
  apply_kettle_family_local_install_env!(command_env)
  command_env
end

.bundler_generated_binstub?(path) ⇒ Boolean

Returns:

  • (Boolean)


1188
1189
1190
1191
1192
# File 'lib/kettle/jem/tasks/install_task.rb', line 1188

def bundler_generated_binstub?(path)
  File.read(path, 512).include?("This file was generated by Bundler")
rescue
  false
end

.cleanup_legacy_rubocop_lts_local_env(project_root) ⇒ Object



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/kettle/jem/tasks/install_task.rb', line 327

def cleanup_legacy_rubocop_lts_local_env(project_root)
  path = File.join(project_root.to_s, "mise.toml")
  return nil unless File.file?(path)

  parsed = TomlRB.parse(File.read(path))
  return {name: "legacy_rubocop_lts_local_env_cleanup", path: "mise.toml", status: "already_current"} unless parsed.fetch("env", {}).key?("RUBOCOP_LTS_LOCAL")

  in_env_table = false
  changed = false
  rewritten = File.readlines(path).reject do |line|
    stripped = line.strip
    in_env_table = stripped == "[env]" if stripped.start_with?("[") && stripped.end_with?("]")
    remove = in_env_table && stripped.split("=", 2).first.to_s.strip == "RUBOCOP_LTS_LOCAL"
    changed ||= remove
    remove
  end
  return {name: "legacy_rubocop_lts_local_env_cleanup", path: "mise.toml", status: "already_current"} unless changed

  File.write(path, rewritten.join)
  {
    name: "legacy_rubocop_lts_local_env_cleanup",
    path: "mise.toml",
    status: "applied",
    removed_key: "RUBOCOP_LTS_LOCAL"
  }
rescue TomlRB::ParseError
  {name: "legacy_rubocop_lts_local_env_cleanup", path: "mise.toml", status: "skipped", reason: "invalid_mise_toml"}
end

.cleanup_legacy_ruby_version_files(project_root) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/kettle/jem/tasks/install_task.rb', line 310

def cleanup_legacy_ruby_version_files(project_root)
  return nil unless File.file?(File.join(project_root.to_s, "mise.toml"))

  removed = %w[.ruby-version .ruby-gemset .tool-versions].filter_map do |relative_path|
    path = File.join(project_root.to_s, relative_path)
    next unless File.exist?(path)

    FileUtils.rm_f(path)
    relative_path
  end
  {
    name: "legacy_ruby_version_file_cleanup",
    status: removed.empty? ? "already_current" : "applied",
    removed_files: removed
  }
end

.config_bootstrap_changed?(report) ⇒ Boolean

Returns:

  • (Boolean)


106
107
108
109
110
# File 'lib/kettle/jem/tasks/install_task.rb', line 106

def config_bootstrap_changed?(report)
  report.fetch(:recipe_reports, []).any? do |recipe_report|
    recipe_report.fetch(:relative_path, nil) == Kettle::Jem::KETTLE_CONFIG_PATH && recipe_report.fetch(:changed, false)
  end
end

.configured_project_grapheme(project_root, env) ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/kettle/jem/tasks/install_task.rb', line 434

def configured_project_grapheme(project_root, env)
  env_value = (env || {})["KJ_PROJECT_EMOJI"].to_s.strip
  return first_grapheme(env_value) unless env_value.empty? || Kettle::Jem::DecisionPolicy.falsey?(env_value)

  config_path = Kettle::Jem.kettle_jem_config_path(project_root.to_s)
  return nil unless File.file?(config_path)

  config = YAML.safe_load_file(config_path, permitted_classes: [], aliases: false)
  value = config["project_emoji"].to_s.strip if config.is_a?(Hash)
  value.to_s.empty? ? nil : first_grapheme(value)
rescue
  nil
end

.conflicting_git_attribute_diagnostics(content, updates, managed_block:) ⇒ Object



1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
# File 'lib/kettle/jem/tasks/install_task.rb', line 1749

def conflicting_git_attribute_diagnostics(content, updates, managed_block:)
  lines = remove_git_attribute_managed_block(content, managed_block: managed_block).fetch(:lines)
  updates.filter_map do |update|
    conflict = lines.find { |line| git_attribute_line_conflicts?(line, update) }
    next unless conflict

    {
      key: "conflicting_attributes",
      severity: "error",
      blocking: true,
      path: update.fetch(:path, ".gitattributes"),
      pattern: update.fetch(:pattern),
      line: conflict
    }
  end
end

.curated_binstub?(path) ⇒ Boolean

Returns:

  • (Boolean)


1180
1181
1182
1183
1184
1185
1186
# File 'lib/kettle/jem/tasks/install_task.rb', line 1180

def curated_binstub?(path)
  basename = File.basename(path)
  return true if CURATED_BINSTUB_DISCRETE_EXECUTABLES.include?(basename)

  gem_name = bundler_binstub_gem_name(path)
  !gem_name.to_s.empty? && CURATED_BINSTUB_GEMS.include?(gem_name)
end

.curated_binstub_gems_in_bundle(project_root = Dir.pwd, env: ENV) ⇒ Object



733
734
735
736
737
738
739
# File 'lib/kettle/jem/tasks/install_task.rb', line 733

def curated_binstub_gems_in_bundle(project_root = Dir.pwd, env: ENV)
  stdout, _stderr, status = Open3.capture3(env.to_h, "bundle", "list", "--name-only", chdir: project_root.to_s)
  return CURATED_BINSTUB_GEMS unless status.success?

  bundled = stdout.lines.map(&:strip).reject(&:empty?)
  CURATED_BINSTUB_GEMS & bundled
end

.current_git_branch(path) ⇒ Object



972
973
974
975
976
977
# File 'lib/kettle/jem/tasks/install_task.rb', line 972

def current_git_branch(path)
  stdout, _stderr, status = Open3.capture3("git", "-C", path.to_s, "branch", "--show-current")
  return "" unless status.success?

  stdout.to_s.strip
end

.decorative_grapheme?(grapheme) ⇒ Boolean

Returns:

  • (Boolean)


515
516
517
518
519
520
# File 'lib/kettle/jem/tasks/install_task.rb', line 515

def decorative_grapheme?(grapheme)
  value = grapheme.to_s
  return false if value.empty?

  !value.match?(/\A[[:alnum:][:space:]]\z/u)
end

.default_git_driver_global_commands ⇒ Object



1627
1628
1629
1630
1631
1632
1633
1634
1635
# File 'lib/kettle/jem/tasks/install_task.rb', line 1627

def default_git_driver_global_commands
  DEFAULT_GIT_DRIVER_DEFINITIONS.flat_map do |definition|
    [
      ["git", "config", "--global", "diff.#{definition.fetch(:diff)}.command", definition.fetch(:diff_command)],
      ["git", "config", "--global", "merge.#{definition.fetch(:merge)}.driver", definition.fetch(:merge_command)],
      ["git", "config", "--global", "merge.#{definition.fetch(:merge)}.name", "StructuredMerge #{definition.fetch(:language)} merge driver"]
    ]
  end
end

.development_dependency_names(content) ⇒ Object



179
180
181
182
183
184
# File 'lib/kettle/jem/tasks/install_task.rb', line 179

def development_dependency_names(content)
  Kettle::Jem.gemspec_dependency_records(content)
    .select { |dependency| dependency.fetch(:kind) == "add_development_dependency" }
    .map { |dependency| dependency.fetch(:name) }
    .uniq
end

.dirty_git_attribute_managed_block?(content, managed_block) ⇒ Boolean

Returns:

  • (Boolean)


1742
1743
1744
1745
1746
1747
# File 'lib/kettle/jem/tasks/install_task.rb', line 1742

def dirty_git_attribute_managed_block?(content, managed_block)
  start_line = git_attribute_block_start(managed_block)
  end_line = git_attribute_block_end(managed_block)
  content.lines.any? { |line| line.chomp == start_line } &&
    content.lines.none? { |line| line.chomp == end_line }
end

.distinct_bundle_install_step(project_root, env:, setup_env:) ⇒ Object



835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
# File 'lib/kettle/jem/tasks/install_task.rb', line 835

def distinct_bundle_install_step(project_root, env:, setup_env:)
  bundle_env = bundler_command_env(project_root, env)
  if same_bundle_env?(bundle_env, setup_env)
    return {
      name: "bundle_install_requested_env",
      status: "skipped",
      reason: "same_as_setup_bundle_env"
    }
  end

  {
    name: "bundle_install_requested_env",
    command: %w[bundle install],
    status: "ready",
    env: bundle_env,
    reason: "distinct_bundle_env"
  }
end

.ensure_bin_setup_executable(project_root) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/kettle/jem/tasks/install_task.rb', line 246

def ensure_bin_setup_executable(project_root)
  path = File.join(project_root, "bin", "setup")
  return {name: "bin_setup_executable", path: "bin/setup", status: "missing"} unless File.exist?(path)

  before = File.stat(path).mode
  FileUtils.chmod(before | 0o111, path)
  after = File.stat(path).mode
  {
    name: "bin_setup_executable",
    path: "bin/setup",
    status: ((before == after) ? "already_executable" : "updated")
  }
end

.ensure_curated_binstubs_executable(project_root) ⇒ Object



1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/kettle/jem/tasks/install_task.rb', line 1104

def ensure_curated_binstubs_executable(project_root)
  bin_dir = File.join(project_root.to_s, "bin")
  executable_binstubs = binstub_files(bin_dir).select { |path| curated_binstub?(path) }
  updated = executable_binstubs.filter_map do |path|
    next if File.executable?(path)

    FileUtils.chmod("+x", path)
    File.basename(path)
  end

  {
    name: "curated_binstubs_executable",
    status: updated.empty? ? "already_executable" : "updated",
    path: "bin",
    executable_binstubs: executable_binstubs.map { |path| File.basename(path) }.sort,
    updated_binstubs: updated.sort
  }
end

.ensure_env_local_gitignore(project_root) ⇒ Object



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'lib/kettle/jem/tasks/install_task.rb', line 623

def ensure_env_local_gitignore(project_root)
  return nil unless File.file?(File.join(project_root.to_s, ".env.local.example"))

  gitignore_path = File.join(project_root.to_s, ".gitignore")
  content = File.file?(gitignore_path) ? File.read(gitignore_path) : ""
  if content.lines.any? { |line| line.strip == ".env.local" }
    return {
      name: "env_local_gitignore",
      path: ".gitignore",
      status: "already_current"
    }
  end

  addition = [
    "# Local environment overrides (KEY=value, loaded by mise via dotenvy)",
    ".env.local"
  ].join("\n")
  updated = content.dup
  updated << "\n" unless updated.empty? || updated.end_with?("\n")
  updated << addition << "\n"
  File.write(gitignore_path, updated)
  {
    name: "env_local_gitignore",
    path: ".gitignore",
    status: "applied"
  }
end

.execute_bootstrap_commit_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
# File 'lib/kettle/jem/tasks/install_task.rb', line 2018

def execute_bootstrap_commit_step(step, project_root:, env:, quiet:, command_runner:)
  with_git_operation_lock(env, metadata_key: :git_commit_lock) do
    execute_unlocked_ready_commands_step(
      step,
      project_root: project_root,
      env: env,
      quiet: quiet,
      command_runner: command_runner
    )
  end
end

.execute_git_drivers_check_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object

Raises:



2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
# File 'lib/kettle/jem/tasks/install_task.rb', line 2197

def execute_git_drivers_check_step(step, project_root:, env:, quiet:, command_runner:)
  missing = []
  content = File.file?(File.join(project_root.to_s, ".gitattributes")) ? File.read(File.join(project_root.to_s, ".gitattributes")) : ""
  Array(step[:attribute_updates]).each do |update|
    next if content.include?(render_git_attribute_line(update))

    missing << {kind: "attributes", path: update.fetch(:path), pattern: update.fetch(:pattern)}
  end
  Array(step[:config_checks]).each do |check|
    result = command_runner.call(check.fetch(:argv), chdir: project_root, env: env, quiet: quiet)
    next if result.fetch(:success) && result.fetch(:stdout).to_s.strip == check.fetch(:expected)

    missing << {kind: "local_config", key: check.fetch(:key)}
  end
  status = missing.empty? ? "succeeded" : "failed"
  report = step.merge(status: status, ok: missing.empty?, missing: missing, reason: "checked")
  return report if missing.empty?

  raise Kettle::Jem::Error, "git_drivers check failed: #{missing.map { |entry| entry.fetch(:kind) }.uniq.join(", ")} missing"
end

.execute_git_drivers_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
# File 'lib/kettle/jem/tasks/install_task.rb', line 2142

def execute_git_drivers_step(step, project_root:, env:, quiet:, command_runner:)
  return step unless step.fetch(:status) == "ready"

  if step.fetch(:mode) == "check"
    return execute_git_drivers_check_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
  end

  with_git_operation_lock(env, metadata_key: :git_lock) do
    execute_unlocked_git_drivers_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
  end
end

.execute_hook_templates_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
# File 'lib/kettle/jem/tasks/install_task.rb', line 2121

def execute_hook_templates_step(step, project_root:, env:, quiet:, command_runner:)
  return step unless step.fetch(:status) == "ready"

  step.fetch(:chmod_paths, []).each do |relative_path|
    path = File.join(project_root.to_s, relative_path)
    FileUtils.chmod(0o755, path) if File.file?(path)
  end
  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = command_runner.call(step.fetch(:command), chdir: project_root, env: env, quiet: quiet)
  duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000.0).round(3)
  unless result.fetch(:success)
    raise Kettle::Jem::Error, "hook_templates failed: #{step.fetch(:command).join(" ")}\n#{result[:stderr]}"
  end
  step.merge(
    status: "succeeded",
    exitstatus: result[:exitstatus],
    duration_ms: duration_ms,
    reason: "executed"
  )
end

.execute_lockfile_platform_normalization_step(step, project_root:) ⇒ Object



1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'lib/kettle/jem/tasks/install_task.rb', line 1265

def execute_lockfile_platform_normalization_step(step, project_root:)
  return step unless step.fetch(:status) == "ready"

  result = normalize_lockfile_platforms(project_root)
  step.merge(
    status: "succeeded",
    reason: result.fetch(:changed) ? "local_platform_added" : "local_platform_already_present",
    platforms: result.fetch(:platforms)
  )
rescue Bundler::LockfileError, Errno::ENOENT => error
  step.merge(status: "failed", reason: "lockfile_platform_normalization_failed", stderr: error.message)
end

.execute_orchestration_steps(install_steps, project_root:, env:, run_options:, command_runner:, event_phase: "install") ⇒ Object



1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
# File 'lib/kettle/jem/tasks/install_task.rb', line 1224

def execute_orchestration_steps(install_steps, project_root:, env:, run_options:, command_runner:, event_phase: "install")
  quiet = Kettle::Jem::DecisionPolicy.value_to_boolean(run_options[:quiet])
  events = Kettle::Jem.event_stream_from_options(run_options)
  install_steps.map do |step|
    Kettle::Jem.emit_step_event(
      events,
      "command_step",
      step.merge(status: "started"),
      phase: event_phase
    )
    result = case step.fetch(:name)
    when "mise_trust"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "bundled_handoff"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "bundle_lock_normalization"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "lockfile_platform_normalization"
      execute_lockfile_platform_normalization_step(step, project_root: project_root)
    when "rubocop_lts_local_branch"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "bundle_install_requested_env"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "appraisal_generate"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "rubocop_gradual_autocorrect"
      execute_ready_command_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "hook_templates"
      execute_hook_templates_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "git_drivers"
      execute_git_drivers_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    when "bootstrap_commit"
      execute_ready_commands_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
    else
      step
    end
    Kettle::Jem.emit_step_event(events, "command_step", result, phase: event_phase)
    result
  end
end

.execute_ready_command_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
# File 'lib/kettle/jem/tasks/install_task.rb', line 1993

def execute_ready_command_step(step, project_root:, env:, quiet:, command_runner:)
  return step unless step.fetch(:status) == "ready"

  command_env = step.fetch(:env, env)
  result = run_ready_step_command(step.fetch(:name), step.fetch(:command), project_root: project_root, env: command_env, quiet: quiet, command_runner: command_runner)
  step.merge(
    status: "succeeded",
    exitstatus: result[:exitstatus],
    duration_ms: result.fetch(:duration_ms),
    reason: "executed"
  ).tap do |report|
    report[:attempts] = result.fetch(:attempts) if result.fetch(:attempts) > 1
  end
end

.execute_ready_commands_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2008
2009
2010
2011
2012
2013
2014
2015
2016
# File 'lib/kettle/jem/tasks/install_task.rb', line 2008

def execute_ready_commands_step(step, project_root:, env:, quiet:, command_runner:)
  return step unless step.fetch(:status) == "ready"

  if step.fetch(:name) == "bootstrap_commit"
    return execute_bootstrap_commit_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
  end

  execute_unlocked_ready_commands_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
end

.execute_unlocked_git_drivers_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
# File 'lib/kettle/jem/tasks/install_task.rb', line 2154

def execute_unlocked_git_drivers_step(step, project_root:, env:, quiet:, command_runner:)
  changed_files = []
  if step.fetch(:mode) == "include-file"
    include_path = File.join(project_root.to_s, step.fetch(:include_file))
    FileUtils.mkdir_p(File.dirname(include_path))
    before = File.file?(include_path) ? File.read(include_path) : ""
    after = render_git_driver_include_config(step.fetch(:config_entries))
    if before != after
      File.write(include_path, after)
      changed_files << step.fetch(:include_file)
    end
  end
  Array(step[:attribute_removals]).each do |removal|
    path = File.join(project_root.to_s, removal.fetch(:path))
    next unless File.file?(path)

    before = File.read(path)
    after = remove_git_attribute_managed_block(before, managed_block: removal.fetch(:managed_block)).fetch(:lines).join("\n")
    after = "#{after}\n" unless after.empty?
    next if after == before

    File.write(path, after)
    changed_files << removal.fetch(:path)
  end

  unless Array(step[:attribute_updates]).empty?
    path = File.join(project_root.to_s, ".gitattributes")
    before = File.file?(path) ? File.read(path) : ""
    after = render_git_attributes(before, step.fetch(:attribute_updates), managed_block: step.fetch(:managed_block))
    if after != before
      File.write(path, after)
      changed_files << ".gitattributes"
    end
  end

  command_step = execute_ready_commands_step(step, project_root: project_root, env: env, quiet: quiet, command_runner: command_runner)
  command_step.merge(
    status: "succeeded",
    changed_files: changed_files.uniq,
    reason: "executed"
  )
end

.execute_unlocked_ready_commands_step(step, project_root:, env:, quiet:, command_runner:) ⇒ Object



2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
# File 'lib/kettle/jem/tasks/install_task.rb', line 2030

def execute_unlocked_ready_commands_step(step, project_root:, env:, quiet:, command_runner:)
  if step.fetch(:name) == "bootstrap_commit"
    dirty_entries = git_output(project_root, "status", "--porcelain").lines.map(&:chomp).reject(&:empty?)
    if dirty_entries.empty?
      return step.merge(
        status: "clean_noop",
        dirty_entries: [],
        reason: "clean_before_execution"
      )
    end
  end

  command_env = step.fetch(:env, env)
  results = step.fetch(:commands).map do |command|
    result = run_ready_step_command(step.fetch(:name), command, project_root: project_root, env: command_env, quiet: quiet, command_runner: command_runner)
    {
      command: command,
      exitstatus: result[:exitstatus],
      duration_ms: result.fetch(:duration_ms)
    }.tap do |report|
      report[:attempts] = result.fetch(:attempts) if result.fetch(:attempts) > 1
    end
  end
  step.merge(
    status: "succeeded",
    command_results: results,
    duration_ms: results.sum { |result| result.fetch(:duration_ms, 0).to_f }.round(3),
    reason: "executed"
  )
end

.first_grapheme(text) ⇒ Object



511
512
513
# File 'lib/kettle/jem/tasks/install_task.rb', line 511

def first_grapheme(text)
  text.to_s.strip[/\A\X/u].to_s
end

.followup_apply_after_config_bootstrap(project_root, env:, run_options:, report:) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
# File 'lib/kettle/jem/tasks/install_task.rb', line 94

def followup_apply_after_config_bootstrap(project_root, env:, run_options:, report:)
  return report unless config_bootstrap_changed?(report)

  followup = Kettle::Jem.apply_project(project_root, env: env, run_options: run_options)
  merge_apply_reports(report, followup).merge(
    bootstrap_followup_apply: {
      status: "applied",
      reason: "canonical_config_bootstrapped"
    }
  )
end

.gemspec_dependency_sync_step(report) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/kettle/jem/tasks/install_task.rb', line 159

def gemspec_dependency_sync_step(report)
  gemspec_report = report.fetch(:recipe_reports, []).find do |recipe_report|
    recipe_report.fetch(:relative_path, "").end_with?(".gemspec")
  end
  unless gemspec_report
    return {
      name: "gemspec_dependency_sync",
      status: "unavailable",
      reason: "no_gemspec_recipe"
    }
  end

  {
    name: "gemspec_dependency_sync",
    path: gemspec_report.fetch(:relative_path),
    status: gemspec_report.fetch(:changed, false) ? "applied" : "already_current",
    development_dependencies: development_dependency_names(gemspec_report.fetch(:final_content, ""))
  }
end

.gemspec_grapheme_assignment_replacements(content, grapheme) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/kettle/jem/tasks/install_task.rb', line 472

def gemspec_grapheme_assignment_replacements(content, grapheme)
  Kettle::Jem.ruby_call_records(content, nil).filter_map do |call|
    next unless %i[summary= description=].include?(call.name)
    next unless call.receiver&.slice == "spec"

    argument = call.arguments&.arguments&.first
    next unless argument.is_a?(::Prism::StringNode) && argument.content_loc

    replacement = "#{grapheme} #{strip_leading_decorative_graphemes(argument.unescaped)}"
    [
      argument.content_loc.start_character_offset,
      argument.content_loc.end_character_offset,
      ruby_string_literal_content(replacement, argument.opening_loc&.slice)
    ]
  end
end

.gemspec_name(content, gemspec_path) ⇒ Object



616
617
618
619
620
621
# File 'lib/kettle/jem/tasks/install_task.rb', line 616

def gemspec_name(content, gemspec_path)
  Kettle::Jem.gemspec_assignment_records(content, receiver: "spec")
    .find { |record| record.fetch(:field) == "name" }
    &.fetch(:value) ||
    File.basename(gemspec_path, ".gemspec")
end

.git_attribute_block_end(managed_block) ⇒ Object



2268
2269
2270
# File 'lib/kettle/jem/tasks/install_task.rb', line 2268

def git_attribute_block_end(managed_block)
  "# <</#{managed_block}>>"
end

.git_attribute_block_start(managed_block) ⇒ Object



2264
2265
2266
# File 'lib/kettle/jem/tasks/install_task.rb', line 2264

def git_attribute_block_start(managed_block)
  "# <<#{managed_block}>> do not edit below this line"
end

.git_attribute_line_conflicts?(line, update) ⇒ Boolean

Returns:

  • (Boolean)


1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
# File 'lib/kettle/jem/tasks/install_task.rb', line 1766

def git_attribute_line_conflicts?(line, update)
  parts = line.to_s.strip.split
  return false if parts.empty? || parts.first.start_with?("#")
  return false unless parts.first == update.fetch(:pattern)

  attributes = update.fetch(:attributes)
  parts.drop(1).any? do |token|
    key, value = token.split("=", 2)
    attributes.key?(key) && attributes.fetch(key) != value
  end
end

.git_driver_attribute_diagnostics(project_root, updates, managed_block:) ⇒ Object



1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
# File 'lib/kettle/jem/tasks/install_task.rb', line 1723

def git_driver_attribute_diagnostics(project_root, updates, managed_block:)
  path = File.join(project_root.to_s, ".gitattributes")
  return [] unless File.file?(path)

  content = File.read(path)
  diagnostics = []
  if dirty_git_attribute_managed_block?(content, managed_block)
    diagnostics << {
      key: "dirty_managed_block",
      severity: "error",
      blocking: true,
      path: ".gitattributes",
      managed_block: managed_block
    }
  end
  diagnostics.concat(conflicting_git_attribute_diagnostics(content, updates, managed_block: managed_block))
  diagnostics
end

.git_driver_attribute_reason(diagnostics, dry_run:, ready:) ⇒ Object



1716
1717
1718
1719
1720
1721
# File 'lib/kettle/jem/tasks/install_task.rb', line 1716

def git_driver_attribute_reason(diagnostics, dry_run:, ready:)
  return "git_driver_attribute_conflict" if diagnostics.any? { |diagnostic| diagnostic.fetch(:key) == "conflicting_attributes" }
  return "dirty_managed_block" if diagnostics.any? { |diagnostic| diagnostic.fetch(:key) == "dirty_managed_block" }

  dry_run ? "dry_run_git_driver_attributes" : ready
end

.git_driver_attribute_status(diagnostics, dry_run:) ⇒ Object



1710
1711
1712
1713
1714
# File 'lib/kettle/jem/tasks/install_task.rb', line 1710

def git_driver_attribute_status(diagnostics, dry_run:)
  return "blocked" if diagnostics.any? { |diagnostic| diagnostic.fetch(:blocking, false) }

  dry_run ? "planned" : "ready"
end

.git_driver_attribute_updates(manifest, profile) ⇒ Object



1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
# File 'lib/kettle/jem/tasks/install_task.rb', line 1601

def git_driver_attribute_updates(manifest, profile)
  profile_hash = git_driver_manifest_profile(manifest, profile)
  return semantic_git_driver_attribute_updates if profile == "semantic-diff" && !profile_hash
  return BUILTIN_GIT_DIFF_ATTRIBUTES if profile == "builtin-diff" && !profile_hash

  Array(profile_hash.fetch("attributes", [])).map do |entry|
    attributes = entry.except("pattern").transform_values(&:to_s)
    {path: ".gitattributes", pattern: entry.fetch("pattern"), attributes: attributes}
  end
end

.git_driver_forge_warning_diagnostic ⇒ Object



1592
1593
1594
1595
1596
1597
1598
1599
# File 'lib/kettle/jem/tasks/install_task.rb', line 1592

def git_driver_forge_warning_diagnostic
  {
    key: "forge_ignores_external_diff_drivers",
    severity: "advisory",
    blocking: false,
    message: "External StructuredMerge diff drivers are local Git configuration and are generally not honored by hosted forges."
  }
end

.git_driver_global_commands(manifest = nil, profile = "semantic-diff") ⇒ Object



1612
1613
1614
1615
1616
1617
1618
1619
# File 'lib/kettle/jem/tasks/install_task.rb', line 1612

def git_driver_global_commands(manifest = nil, profile = "semantic-diff")
  profile_hash = git_driver_manifest_profile(manifest, profile)
  return default_git_driver_global_commands unless profile_hash

  Array(profile_hash.fetch("git_config", [])).map do |entry|
    ["git", "config", "--global", entry.fetch("key"), entry.fetch("value")]
  end
end

.git_driver_global_config_checks(manifest = nil, profile = "semantic-diff") ⇒ Object



1647
1648
1649
1650
1651
# File 'lib/kettle/jem/tasks/install_task.rb', line 1647

def git_driver_global_config_checks(manifest = nil, profile = "semantic-diff")
  git_driver_global_commands(manifest, profile).map do |command|
    {key: command[3], expected: command[4], argv: ["git", "config", "--global", "--get", command[3]]}
  end
end

.git_driver_global_unset_commands ⇒ Object



1637
1638
1639
1640
1641
1642
1643
1644
1645
# File 'lib/kettle/jem/tasks/install_task.rb', line 1637

def git_driver_global_unset_commands
  DEFAULT_GIT_DRIVER_DEFINITIONS.flat_map do |definition|
    [
      ["git", "config", "--global", "--unset-all", "diff.#{definition.fetch(:diff)}.command"],
      ["git", "config", "--global", "--unset-all", "merge.#{definition.fetch(:merge)}.driver"],
      ["git", "config", "--global", "--unset-all", "merge.#{definition.fetch(:merge)}.name"]
    ]
  end
end

.git_driver_local_commands(manifest = nil, profile = "semantic-diff") ⇒ Object



1621
1622
1623
1624
1625
# File 'lib/kettle/jem/tasks/install_task.rb', line 1621

def git_driver_local_commands(manifest = nil, profile = "semantic-diff")
  git_driver_global_commands(manifest, profile).map do |command|
    ["git", "config", "--local", command[3], command[4]]
  end
end

.git_driver_local_config_checks(manifest = nil, profile = "semantic-diff") ⇒ Object



1653
1654
1655
1656
1657
# File 'lib/kettle/jem/tasks/install_task.rb', line 1653

def git_driver_local_config_checks(manifest = nil, profile = "semantic-diff")
  git_driver_local_commands(manifest, profile).map do |command|
    {key: command[3], expected: command[4], argv: ["git", "config", "--local", "--get", command[3]]}
  end
end

.git_driver_manifest(project_root) ⇒ Object



1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
# File 'lib/kettle/jem/tasks/install_task.rb', line 1659

def git_driver_manifest(project_root)
  path = File.join(project_root.to_s, ".structuredmerge", "git-drivers.toml")
  return nil unless File.file?(path)

  manifest = TomlRB.parse(File.read(path))
  validate_git_driver_manifest!(manifest)
  manifest
rescue TomlRB::ParseError => error
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: #{error.message}"
end

.git_driver_manifest_profile(manifest, profile) ⇒ Object



1670
1671
1672
1673
1674
# File 'lib/kettle/jem/tasks/install_task.rb', line 1670

def git_driver_manifest_profile(manifest, profile)
  return nil unless manifest

  manifest.fetch("profiles").fetch(profile)
end

.git_drivers_step(project_root, run_options) ⇒ Object



1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
# File 'lib/kettle/jem/tasks/install_task.rb', line 1472

def git_drivers_step(project_root, run_options)
  mode = normalize_git_drivers_mode((run_options || {})[:git_drivers])
  dry_run = Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:dry_run])
  manifest = git_driver_manifest(project_root)
  if mode == "none"
    return {
      name: "git_drivers",
      status: "skipped",
      reason: "not_requested",
      mode: mode
    }
  end

  case mode
  when "check"
    {
      name: "git_drivers",
      status: "ready",
      mode: mode,
      profile: "semantic-diff",
      scope: "check",
      attribute_updates: git_driver_attribute_updates(manifest, "semantic-diff"),
      config_checks: git_driver_local_config_checks(manifest, "semantic-diff"),
      reason: "ready_for_git_driver_check"
    }
  when "undo"
    {
      name: "git_drivers",
      status: dry_run ? "planned" : "ready",
      mode: mode,
      profile: "all",
      scope: "local",
      attribute_removals: [
        {path: ".gitattributes", managed_block: "structuredmerge:git-drivers"},
        {path: ".gitattributes", managed_block: "structuredmerge:git-builtins"}
      ],
      commands: git_driver_global_unset_commands,
      reason: dry_run ? "dry_run_git_driver_undo" : "ready_for_git_driver_undo"
    }
  when "global"
    {
      name: "git_drivers",
      status: dry_run ? "planned" : "ready",
      mode: mode,
      profile: "semantic-diff",
      scope: "global",
      commands: git_driver_global_commands(manifest, "semantic-diff"),
      diagnostics: [git_driver_forge_warning_diagnostic],
      reason: dry_run ? "dry_run_global_git_drivers" : "ready_for_global_git_drivers"
    }
  when "include-file"
    {
      name: "git_drivers",
      status: dry_run ? "planned" : "ready",
      mode: mode,
      profile: "semantic-diff",
      scope: "include-file",
      include_file: ".git/smorg/config",
      config_entries: git_driver_global_commands(manifest, "semantic-diff").map { |command| {key: command[3], value: command[4]} },
      commands: [["git", "config", "--local", "include.path", ".git/smorg/config"]],
      diagnostics: [git_driver_forge_warning_diagnostic],
      reason: dry_run ? "dry_run_git_driver_include_file" : "ready_for_git_driver_include_file"
    }
  when "builtin-diff"
    updates = git_driver_attribute_updates(manifest, "builtin-diff")
    diagnostics = git_driver_attribute_diagnostics(project_root, updates, managed_block: "structuredmerge:git-builtins")
    {
      name: "git_drivers",
      status: git_driver_attribute_status(diagnostics, dry_run: dry_run),
      mode: mode,
      profile: "builtin-diff",
      scope: "local",
      attribute_updates: updates,
      managed_block: "structuredmerge:git-builtins",
      commands: [],
      diagnostics: diagnostics,
      reason: git_driver_attribute_reason(diagnostics, dry_run: dry_run, ready: "ready_for_builtin_git_attributes")
    }
  else
    updates = git_driver_attribute_updates(manifest, "semantic-diff")
    diagnostics = git_driver_attribute_diagnostics(project_root, updates, managed_block: "structuredmerge:git-drivers")
    {
      name: "git_drivers",
      status: git_driver_attribute_status(diagnostics, dry_run: dry_run),
      mode: "local",
      profile: "semantic-diff",
      scope: "local",
      attribute_updates: updates,
      managed_block: "structuredmerge:git-drivers",
      commands: git_driver_local_commands(manifest, "semantic-diff"),
      diagnostics: diagnostics + [git_driver_forge_warning_diagnostic],
      reason: git_driver_attribute_reason(diagnostics, dry_run: dry_run, ready: "ready_for_local_git_drivers")
    }
  end
end

.git_lock_conflict?(stderr) ⇒ Boolean

Returns:

  • (Boolean)


2092
2093
2094
2095
2096
2097
2098
# File 'lib/kettle/jem/tasks/install_task.rb', line 2092

def git_lock_conflict?(stderr)
  text = stderr.to_s
  text.include?("could not lock config file") ||
    text.include?("config.lock") ||
    text.include?("index.lock") ||
    text.include?("Unable to create") && text.include?(".lock")
end

.git_operation_lock_path(env) ⇒ Object



2100
2101
2102
2103
2104
2105
2106
# File 'lib/kettle/jem/tasks/install_task.rb', line 2100

def git_operation_lock_path(env)
  GIT_OPERATION_LOCK_ENV_KEYS.each do |key|
    value = env.fetch(key, nil).to_s
    return value unless value.empty?
  end
  nil
end

.git_operation_step_name?(step_name) ⇒ Boolean

Returns:

  • (Boolean)


2088
2089
2090
# File 'lib/kettle/jem/tasks/install_task.rb', line 2088

def git_operation_step_name?(step_name)
  %w[bootstrap_commit git_drivers].include?(step_name.to_s)
end

.git_output(project_root, *args) ⇒ Object



1856
1857
1858
1859
# File 'lib/kettle/jem/tasks/install_task.rb', line 1856

def git_output(project_root, *args)
  stdout, _stderr, status = Open3.capture3("git", "-C", project_root.to_s, *args)
  status.success? ? stdout : ""
end

.git_success?(project_root, *args) ⇒ Boolean

Returns:

  • (Boolean)


1851
1852
1853
1854
# File 'lib/kettle/jem/tasks/install_task.rb', line 1851

def git_success?(project_root, *args)
  _stdout, _stderr, status = Open3.capture3("git", "-C", project_root.to_s, *args)
  status.success?
end

.git_toplevel(project_root) ⇒ Object



1210
1211
1212
1213
# File 'lib/kettle/jem/tasks/install_task.rb', line 1210

def git_toplevel(project_root)
  stdout, _stderr, status = Open3.capture3("git", "-C", project_root.to_s, "rev-parse", "--show-toplevel")
  status.success? ? stdout.strip : nil
end

.github_org_from_env(env) ⇒ Object



590
591
592
593
594
595
596
# File 'lib/kettle/jem/tasks/install_task.rb', line 590

def github_org_from_env(env)
  %w[FORGE_ORG KJ_GH_ORG GITHUB_ORG].each do |key|
    value = (env || {})[key].to_s.strip
    return value unless value.empty? || Kettle::Jem::DecisionPolicy.falsey?(value)
  end
  nil
end

.github_org_from_origin(project_root) ⇒ Object



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/kettle/jem/tasks/install_task.rb', line 598

def github_org_from_origin(project_root)
  stdout, _stderr, status = Open3.capture3("git", "-C", project_root.to_s, "remote", "get-url", "origin")
  return nil unless status.success?

  remote = stdout.to_s.strip
  path = if remote.start_with?("[email protected]:")
    remote.split(":", 2).last
  else
    uri = URI.parse(remote)
    return nil unless uri.host == "github.com"

    uri.path
  end
  path.to_s.delete_prefix("/").split("/").first
rescue URI::InvalidURIError
  nil
end

.github_workflow_paths(project_root) ⇒ Object



391
392
393
394
395
396
397
398
# File 'lib/kettle/jem/tasks/install_task.rb', line 391

def github_workflow_paths(project_root)
  workflow_root = File.join(project_root.to_s, ".github", "workflows")
  return [] unless Dir.exist?(workflow_root)

  Dir.glob(File.join(workflow_root, "*.{yml,yaml}")).map do |path|
    Pathname(path).relative_path_from(Pathname(project_root.to_s)).to_s
  end.sort
end

.handoff_argv(run_options) ⇒ Object



1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
# File 'lib/kettle/jem/tasks/install_task.rb', line 1861

def handoff_argv(run_options)
  options = run_options || {}
  argv = []
  argv << "--accept-config" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:accept_config])
  argv << "--skip-commit" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:skip_commit])
  argv << "--skip-drift-check" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:skip_drift_check])
  argv << "--skip-rubocop-gradual" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:skip_rubocop_gradual])
  argv << "--skip-binstubs" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:skip_binstubs])
  argv << "--quiet" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:quiet])
  argv << "--verbose" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:verbose])
  argv << "--force" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:force])
  argv << "--accept" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:accept])
  argv << "--interactive" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:interactive])
  argv << "--dry-run" if Kettle::Jem::DecisionPolicy.value_to_boolean(options[:dry_run])
  argv.concat(value_arg("--checksums", options[:checksums]))
  argv.concat(value_arg("--failure-mode", options[:failure_mode]))
  argv.concat(value_arg("--allowed", options[:allowed]))
  argv.concat(value_arg("--hook-templates", options[:hook_templates]))
  argv.concat(value_arg("--git-drivers", options[:git_drivers]))
  argv.concat(list_arg("--only", options[:only]))
  argv.concat(list_arg("--include", options[:include]))
  argv
end

.hook_templates_step(project_root, run_options) ⇒ Object



1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
# File 'lib/kettle/jem/tasks/install_task.rb', line 1389

def hook_templates_step(project_root, run_options)
  mode = normalize_hook_templates_mode((run_options || {})[:hook_templates])
  if mode.empty? || mode == "none"
    return {
      name: "hook_templates",
      status: "skipped",
      reason: "not_requested"
    }
  end

  if mode == "global"
    return {
      name: "hook_templates",
      status: "unsupported",
      reason: "global_hooks_not_implemented",
      requested: mode
    }
  end

  hooks_dir = File.join(project_root.to_s, ".git-hooks")
  missing_hooks = %w[commit-msg prepare-commit-msg].reject { |hook| File.file?(File.join(hooks_dir, hook)) }
  unless missing_hooks.empty?
    return {
      name: "hook_templates",
      status: "unavailable",
      reason: "missing_local_hook_templates",
      missing_hooks: missing_hooks
    }
  end

  {
    name: "hook_templates",
    status: "ready",
    command: %w[git config core.hooksPath .git-hooks],
    chmod_paths: %w[.git-hooks/commit-msg .git-hooks/prepare-commit-msg],
    reason: "ready_for_local_hooks"
  }
end

.ignored_bundle_env_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


1324
1325
1326
# File 'lib/kettle/jem/tasks/install_task.rb', line 1324

def ignored_bundle_env_key?(key)
  key.to_s.match?(/\A(?:BUNDLE_BIN_PATH|BUNDLE_LOCKFILE|BUNDLER_SETUP|BUNDLER_VERSION|RUBYLIB|RUBYOPT)\z/)
end

.install_phase_reports(install_steps) ⇒ Object



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
# File 'lib/kettle/jem/tasks/install_task.rb', line 195

def install_phase_reports(install_steps)
  phases = {
    "template_apply" => %w[gemspec_dependency_sync],
    "post_template" => %w[
      kettle_config_migration
      version_gem_bootstrap
      version_gem_cleanup
      legacy_rbs_consolidation
      mise_trust
      legacy_ruby_version_file_cleanup
      readme_compatibility_badges
      readme_gemspec_grapheme_sync
      gemspec_homepage_literal
      env_local_gitignore
      hook_templates
      git_drivers
      rubocop_lts_local_branch
      bundle_install_requested_env
      appraisal_generate
      bin_setup_executable
      bin_setup
      bundle_binstubs
      curated_binstubs_executable
      bundle_binstub_pruning
      bundle_binstub_location_validation
      rubocop_gradual_autocorrect
      bundle_lock_normalization
    ],
    "orchestration" => %w[bundled_handoff bootstrap_commit]
  }
  phases.map do |phase, names|
    steps = install_steps.select { |step| names.include?(step.fetch(:name).to_s) }
    {
      phase: phase,
      steps: steps.map { |step| step.fetch(:name) },
      statuses: steps.to_h { |step| [step.fetch(:name), step.fetch(:status)] }
    }
  end
end

.install_run_options(env, run_options) ⇒ Object



90
91
92
# File 'lib/kettle/jem/tasks/install_task.rb', line 90

def install_run_options(env, run_options)
  Kettle::Jem::Tasks::TemplateTask.templating_run_options(env || {}, run_options || {})
end

.install_step_summary(install_steps) ⇒ Object



235
236
237
238
239
240
241
242
243
244
# File 'lib/kettle/jem/tasks/install_task.rb', line 235

def install_step_summary(install_steps)
  statuses = install_steps.each_with_object(Hash.new(0)) do |step, counts|
    counts[step.fetch(:status, "unknown").to_s] += 1
  end.sort.to_h
  {
    steps: install_steps.length,
    statuses: statuses,
    summary: "install steps #{install_steps.length}; #{statuses.map { |status, count| "#{status} #{count}" }.join("; ")}"
  }
end

.kettle_config_migration_step(project_root) ⇒ Object



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
# File 'lib/kettle/jem/tasks/install_task.rb', line 123

def kettle_config_migration_step(project_root)
  canonical_relative = Kettle::Jem::KETTLE_CONFIG_PATH
  legacy_relative = Kettle::Jem::LEGACY_KETTLE_CONFIG_PATH
  canonical = File.join(project_root.to_s, canonical_relative)
  legacy = File.join(project_root.to_s, legacy_relative)
  return nil unless File.exist?(legacy)

  if File.exist?(canonical)
    return {
      name: "kettle_config_migration",
      status: "blocked",
      reason: "legacy_kettle_config_conflict",
      canonical_path: canonical_relative,
      legacy_path: legacy_relative,
      diagnostics: [{
        key: "legacy_kettle_config_conflict",
        severity: "warning",
        blocking: false,
        path: legacy_relative,
        canonical_path: canonical_relative
      }]
    }
  end

  FileUtils.mkdir_p(File.dirname(canonical))
  FileUtils.mv(legacy, canonical)
  {
    name: "kettle_config_migration",
    status: "migrated",
    reason: "legacy_kettle_config_migrated",
    canonical_path: canonical_relative,
    legacy_path: legacy_relative,
    changed_files: [legacy_relative, canonical_relative]
  }
end

.kettle_family_dependency_root(marker) ⇒ Object



1364
1365
1366
1367
1368
1369
# File 'lib/kettle/jem/tasks/install_task.rb', line 1364

def kettle_family_dependency_root(marker)
  Array(marker["local_dependencies"]).map(&:to_s).each do |path|
    return File.dirname(path) if File.basename(path) == "kettle-dev"
  end
  nil
end

.kettle_family_local_install_marker(command_env) ⇒ Object



1354
1355
1356
1357
1358
1359
1360
1361
1362
# File 'lib/kettle/jem/tasks/install_task.rb', line 1354

def kettle_family_local_install_marker(command_env)
  path = command_env["KETTLE_FAMILY_LOCAL_INSTALL_MARKER"].to_s
  path = File.join(Dir.home, ".kettle-family", "local-install.json") if path.empty?
  return {} unless File.file?(path)

  JSON.parse(File.read(path))
rescue JSON::ParserError
  {}
end

.list_arg(flag, value) ⇒ Object



1900
1901
1902
1903
# File 'lib/kettle/jem/tasks/install_task.rb', line 1900

def list_arg(flag, value)
  values = Array(value).flat_map { |entry| entry.to_s.split(",") }.map(&:strip).reject(&:empty?)
  values.empty? ? [] : [flag, values.join(",")]
end

.literal_github_homepage?(assigned) ⇒ Boolean

Returns:

  • (Boolean)


576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/kettle/jem/tasks/install_task.rb', line 576

def literal_github_homepage?(assigned)
  value = assigned.to_s.strip
  return false if value.include?('#{')

  if (value.start_with?('"') && value.end_with?('"')) || (value.start_with?("'") && value.end_with?("'"))
    value = value[1..-2]
  end
  uri = URI.parse(value)
  segments = uri.path.to_s.split("/").reject(&:empty?)
  %w[http https].include?(uri.scheme) && uri.host == "github.com" && segments.length == 2
rescue URI::InvalidURIError
  false
end

.local_env_disabled?(value) ⇒ Boolean

Returns:

  • (Boolean)


1371
1372
1373
1374
# File 'lib/kettle/jem/tasks/install_task.rb', line 1371

def local_env_disabled?(value)
  raw_value = value.to_s.strip
  raw_value.empty? || Kettle::Jem::DecisionPolicy.falsey?(raw_value)
end

.local_path_development_env?(env) ⇒ Boolean

Returns:

  • (Boolean)


1376
1377
1378
1379
1380
# File 'lib/kettle/jem/tasks/install_task.rb', line 1376

def local_path_development_env?(env)
  (env || {}).any? do |key, value|
    key.to_s.end_with?("_DEV", "_LOCAL") && !local_env_disabled?(value)
  end
end

.lockfile_normalization_command(project_root) ⇒ Object



822
823
824
825
# File 'lib/kettle/jem/tasks/install_task.rb', line 822

def lockfile_normalization_command(project_root)
  platforms = lockfile_normalization_platforms(project_root)
  ["bundle", "lock", *platforms.map { |platform| "--add-platform=#{platform}" }, "--update", "--add-checksums"]
end

.lockfile_normalization_platforms(project_root) ⇒ Object



827
828
829
830
831
832
833
# File 'lib/kettle/jem/tasks/install_task.rb', line 827

def lockfile_normalization_platforms(project_root)
  lock_path = File.join(project_root.to_s, "Gemfile.lock")
  existing = Bundler::LockfileParser.new(Bundler.read_file(lock_path)).platforms.map(&:to_s)
  (existing + [Gem::Platform.local.to_s]).reject(&:empty?).uniq.sort
rescue Bundler::LockfileError, Errno::ENOENT
  [Gem::Platform.local.to_s]
end

.merge_apply_reports(initial, followup) ⇒ Object



112
113
114
115
116
117
118
119
120
121
# File 'lib/kettle/jem/tasks/install_task.rb', line 112

def merge_apply_reports(initial, followup)
  merged = followup.merge(
    changed_files: (initial.fetch(:changed_files, []) + followup.fetch(:changed_files, [])).uniq,
    recipe_reports: initial.fetch(:recipe_reports, []) + followup.fetch(:recipe_reports, []),
    post_apply_steps: initial.fetch(:post_apply_steps, []) + followup.fetch(:post_apply_steps, []),
    diagnostics: initial.fetch(:diagnostics, []) + followup.fetch(:diagnostics, [])
  )
  merged[:changed] = initial.fetch(:changed, false) || followup.fetch(:changed, false) if initial.key?(:changed) || followup.key?(:changed)
  merged
end

.mise_installed?(env) ⇒ Boolean

Returns:

  • (Boolean)


290
291
292
293
294
295
296
297
# File 'lib/kettle/jem/tasks/install_task.rb', line 290

def mise_installed?(env)
  path = (env || {})["PATH"].to_s
  path = ENV["PATH"].to_s if path.empty?
  path.split(File::PATH_SEPARATOR).any? do |dir|
    candidate = File.join(dir, "mise")
    File.file?(candidate) && File.executable?(candidate)
  end
end

.mise_trust_step(project_root, report, env:, install_steps: []) ⇒ Object



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
# File 'lib/kettle/jem/tasks/install_task.rb', line 260

def mise_trust_step(project_root, report, env:, install_steps: [])
  mise_report = report.fetch(:recipe_reports, []).find do |recipe_report|
    recipe_report.fetch(:relative_path, "") == "mise.toml"
  end
  mise_migrated = Array(install_steps).any? do |step|
    step.fetch(:name, "") == "legacy_rubocop_lts_local_env_cleanup" && step.fetch(:status, "") == "applied"
  end
  return nil unless mise_report&.fetch(:changed, false) || mise_migrated

  command = ["mise", "trust", "-C", project_root.to_s]
  if mise_installed?(env)
    return {
      name: "mise_trust",
      path: "mise.toml",
      command: command,
      status: "ready",
      reason: "mise_toml_changed"
    }
  end

  {
    name: "mise_trust",
    path: "mise.toml",
    command: command,
    status: "unavailable",
    reason: "mise_not_installed",
    install_url: "https://mise.jdx.dev/getting-started.html"
  }
end

.normal_lockfile_env(project_root, env) ⇒ Object



979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
# File 'lib/kettle/jem/tasks/install_task.rb', line 979

def normal_lockfile_env(project_root, env)
  command_env = (env || {}).to_h.dup
  strip_inherited_bundler_activation!(command_env)
  command_env["K_JEM_TEMPLATING"] = "false"
  %w[KETTLE_DEV_DEV GALTZO_FLOSS_DEV STRUCTUREDMERGE_DEV].each do |key|
    command_env[key] = "false" if command_env.key?(key)
  end
  gemfile = File.join(project_root.to_s, "Gemfile")
  command_env["BUNDLE_GEMFILE"] = gemfile if File.file?(gemfile)
  apply_direct_sibling_lockfile_env!(project_root, command_env)
  %w[
    BUNDLE_PATH
    BUNDLE_WITH
    BUNDLE_WITHOUT
  ].each do |key|
    command_env[key] = nil
  end
  command_env
end

.normalize_gemspec_grapheme(content, grapheme) ⇒ Object



467
468
469
470
# File 'lib/kettle/jem/tasks/install_task.rb', line 467

def normalize_gemspec_grapheme(content, grapheme)
  replacements = gemspec_grapheme_assignment_replacements(content, grapheme)
  replace_character_ranges(content.to_s, replacements)
end

.normalize_git_drivers_mode(value) ⇒ Object



1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
# File 'lib/kettle/jem/tasks/install_task.rb', line 1568

def normalize_git_drivers_mode(value)
  normalized = value.to_s.strip.downcase.tr("_", "-")
  return "local" if normalized.empty?
  return "none" if %w[0 false f no n none off skip].include?(normalized)
  return "local" if %w[1 true t yes y on l local semantic semantic-diff].include?(normalized)
  return "global" if %w[g global].include?(normalized)
  return "include-file" if %w[include include-file].include?(normalized)
  return "builtin-diff" if %w[b builtin builtin-diff].include?(normalized)
  return "check" if normalized == "check"
  return "undo" if normalized == "undo"

  normalized
end

.normalize_hook_templates_mode(value) ⇒ Object



1428
1429
1430
1431
1432
1433
1434
1435
1436
# File 'lib/kettle/jem/tasks/install_task.rb', line 1428

def normalize_hook_templates_mode(value)
  normalized = value.to_s.strip.downcase
  return "" if normalized.empty?
  return "none" if %w[0 false f no n none off skip].include?(normalized)
  return "local" if %w[1 true t yes y on l local].include?(normalized)
  return "global" if %w[g global].include?(normalized)

  normalized
end

.normalize_lockfile_platforms(project_root) ⇒ Object

Raises:

  • (Bundler::LockfileError)


794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/kettle/jem/tasks/install_task.rb', line 794

def normalize_lockfile_platforms(project_root)
  lock_path = File.join(project_root.to_s, "Gemfile.lock")
  contents = Bundler.read_file(lock_path)
  platforms = (Bundler::LockfileParser.new(contents).platforms.map(&:to_s) + [Gem::Platform.local.to_s]).reject(&:empty?).uniq.sort
  lines = contents.lines
  platforms_index = lines.index { |line| line == "PLATFORMS\n" }
  raise Bundler::LockfileError, "Gemfile.lock does not contain a PLATFORMS section" unless platforms_index

  next_section_index = lines.each_index.find do |index|
    index > platforms_index && !lines[index].start_with?("  ") && lines[index] != "\n"
  end
  raise Bundler::LockfileError, "Gemfile.lock PLATFORMS section has no following section" unless next_section_index

  normalized_section = ["PLATFORMS\n", *platforms.map { |platform| "  #{platform}\n" }, "\n"]
  return {changed: false, platforms: platforms} if lines[platforms_index...next_section_index] == normalized_section

  # Bundler exposes a parser but no public platform-only writer. Keep the
  # locked dependency graph byte-for-byte intact while rewriting this
  # validated, line-oriented section.
  lines[platforms_index...next_section_index] = normalized_section
  File.write(lock_path, lines.join)
  {changed: true, platforms: platforms}
end

.normalize_lockfile_platforms_step(project_root, env:, run_options: {}) ⇒ Object



782
783
784
785
786
787
788
789
790
791
792
# File 'lib/kettle/jem/tasks/install_task.rb', line 782

def normalize_lockfile_platforms_step(project_root, env:, run_options: {})
  return skipped_lockfile_normalization_step("lockfile_platform_normalization", "skip_lock_normalization") if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_lock_normalization])
  return skipped_lockfile_normalization_step("lockfile_platform_normalization", "local_path_development_env") if local_path_development_env?(env)
  return skipped_lockfile_normalization_step("lockfile_platform_normalization", "missing_Gemfile.lock") unless File.file?(File.join(project_root.to_s, "Gemfile.lock"))

  {
    name: "lockfile_platform_normalization",
    status: "ready",
    reason: "preserve_locked_dependencies_and_add_local_platform"
  }
end

.normalize_lockfile_step(project_root, env:, run_options: {}) ⇒ Object



748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/kettle/jem/tasks/install_task.rb', line 748

def normalize_lockfile_step(project_root, env:, run_options: {})
  if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_lock_normalization])
    return {
      name: "bundle_lock_normalization",
      status: "skipped",
      reason: "skip_lock_normalization"
    }
  end

  if local_path_development_env?(env)
    return {
      name: "bundle_lock_normalization",
      status: "skipped",
      reason: "local_path_development_env"
    }
  end

  unless File.file?(File.join(project_root.to_s, "Gemfile.lock"))
    return {
      name: "bundle_lock_normalization",
      status: "skipped",
      reason: "missing Gemfile.lock"
    }
  end

  {
    name: "bundle_lock_normalization",
    command: lockfile_normalization_command(project_root),
    status: "ready",
    env: normal_lockfile_env(project_root, env),
    reason: "bundle_lock_update_preserving_platforms_without_templating_overrides"
  }
end

.normalize_readme_h1_grapheme(content, grapheme) ⇒ Object



456
457
458
459
460
461
462
463
464
465
# File 'lib/kettle/jem/tasks/install_task.rb', line 456

def normalize_readme_h1_grapheme(content, grapheme)
  lines = content.to_s.split("\n", -1)
  h1 = Kettle::Jem.markdown_heading_owners(content, source_label: "README.md").find { |owner| owner.level == 1 }
  return content unless h1

  index = h1.location.start_line - 1
  rest = h1.heading_text
  lines[index] = "# #{grapheme} #{strip_leading_decorative_graphemes(rest)}".rstrip
  lines.join("\n")
end

.post_template_project_fix_steps(project_root, report, env:) ⇒ Object



299
300
301
302
303
304
305
306
307
308
# File 'lib/kettle/jem/tasks/install_task.rb', line 299

def post_template_project_fix_steps(project_root, report, env:)
  [
    cleanup_legacy_ruby_version_files(project_root),
    cleanup_legacy_rubocop_lts_local_env(project_root),
    trim_readme_compatibility_badges(project_root, report),
    sync_readme_gemspec_grapheme(project_root, env),
    repair_gemspec_homepage(project_root, env),
    ensure_env_local_gitignore(project_root)
  ].compact
end

.prune_unwanted_bundler_binstubs(project_root) ⇒ Object



1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'lib/kettle/jem/tasks/install_task.rb', line 1123

def prune_unwanted_bundler_binstubs(project_root)
  bin_dir = File.join(project_root.to_s, "bin")
  removed = []
  preserved = []
  binstub_files(bin_dir).each do |path|
    basename = File.basename(path)
    next if curated_binstub?(path)
    next unless bundler_generated_binstub?(path)

    if tracked_binstub?(project_root, path)
      preserved << basename
      next
    end

    FileUtils.rm_f(path)
    removed << basename
  end

  {
    name: "bundle_binstub_pruning",
    status: removed.empty? ? "already_current" : "pruned",
    reason: removed.empty? ? "no_unwanted_bundler_binstubs" : "removed_unwanted_bundler_binstubs",
    removed_binstubs: removed.sort,
    preserved_binstubs: preserved.sort
  }
end

.quiet_command(command, quiet:) ⇒ Object



2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
# File 'lib/kettle/jem/tasks/install_task.rb', line 2285

def quiet_command(command, quiet:)
  argv = command.map(&:to_s)
  return argv unless quiet
  return argv unless argv.first == "bundle"
  return argv if argv.include?("--quiet")

  subcommand = argv[1]
  return [*argv, "--quiet"] if %w[install update].include?(subcommand)

  argv
end

.quiet_command_env(env) ⇒ Object



2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
# File 'lib/kettle/jem/tasks/install_task.rb', line 2297

def quiet_command_env(env)
  (env || {}).to_h.merge(
    "DEBUG" => "false",
    "KETTLE_JEM_DEBUG" => "false",
    "KETTLE_DEV_DEBUG" => "false",
    "BUNDLE_IGNORE_MESSAGES" => "true",
    "BUNDLE_SILENCE_DEPRECATIONS" => "true",
    "BUNDLE_SILENCE_ROOT_WARNING" => "true",
    "BUNDLE_VERBOSE" => "false"
  )
end

.rake_task_available?(project_root, task_name, env: nil) ⇒ Boolean

Returns:

  • (Boolean)


905
906
907
908
909
910
# File 'lib/kettle/jem/tasks/install_task.rb', line 905

def rake_task_available?(project_root, task_name, env: nil)
  stdout, _stderr, status = Open3.capture3((env || {}).to_h, "bin/rake", "--tasks", chdir: project_root.to_s)
  status.success? && stdout.lines.any? { |line| line.include?(task_name.to_s) }
rescue Errno::EACCES, Errno::ENOENT
  false
end

.readme_h1_grapheme(content) ⇒ Object



448
449
450
451
452
453
454
# File 'lib/kettle/jem/tasks/install_task.rb', line 448

def readme_h1_grapheme(content)
  h1 = Kettle::Jem.markdown_heading_owners(content, source_label: "README.md").find { |owner| owner.level == 1 }
  return nil unless h1

  first = first_grapheme(h1.heading_text)
  decorative_grapheme?(first) ? first : nil
end

.relative_or_absolute_path(path, project_root) ⇒ Object



1215
1216
1217
1218
1219
1220
1221
1222
# File 'lib/kettle/jem/tasks/install_task.rb', line 1215

def relative_or_absolute_path(path, project_root)
  expanded_path = File.expand_path(path.to_s)
  expanded_root = File.expand_path(project_root.to_s)
  return "." if expanded_path == expanded_root
  return expanded_path.delete_prefix("#{expanded_root}/") if expanded_path.start_with?("#{expanded_root}/")

  expanded_path
end

.remove_git_attribute_managed_block(content, managed_block:) ⇒ Object



2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
# File 'lib/kettle/jem/tasks/install_task.rb', line 2238

def remove_git_attribute_managed_block(content, managed_block:)
  start_line = git_attribute_block_start(managed_block)
  end_line = git_attribute_block_end(managed_block)
  skipping = false
  removed = false
  lines = []
  content.lines(chomp: true).each do |line|
    if line == start_line
      skipping = true
      removed = true
      next
    end
    if skipping
      skipping = false if line == end_line
      next
    end
    lines << line
  end
  {lines: lines, removed: removed}
end

.render_git_attribute_line(update) ⇒ Object



2259
2260
2261
2262
# File 'lib/kettle/jem/tasks/install_task.rb', line 2259

def render_git_attribute_line(update)
  attributes = update.fetch(:attributes).map { |key, value| "#{key}=#{value}" }.join(" ")
  "#{update.fetch(:pattern)} #{attributes}"
end

.render_git_attributes(content, updates, managed_block:) ⇒ Object



2229
2230
2231
2232
2233
2234
2235
2236
# File 'lib/kettle/jem/tasks/install_task.rb', line 2229

def render_git_attributes(content, updates, managed_block:)
  unmanaged_lines = remove_git_attribute_managed_block(content, managed_block: managed_block).fetch(:lines)
  rendered_lines = unmanaged_lines.reject { |line| line.empty? && unmanaged_lines.last == line }
  rendered_lines << git_attribute_block_start(managed_block)
  updates.each { |update| rendered_lines << render_git_attribute_line(update) }
  rendered_lines << git_attribute_block_end(managed_block)
  "#{rendered_lines.join("\n")}\n"
end

.render_git_driver_include_config(config_entries) ⇒ Object



2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
# File 'lib/kettle/jem/tasks/install_task.rb', line 2218

def render_git_driver_include_config(config_entries)
  lines = ["# Generated by kettle-jem; do not commit this file."]
  Array(config_entries).each do |entry|
    section, name = entry.fetch(:key).split(".", 2)
    lines << ""
    lines << "[#{section} \"#{name.split(".").first}\"]"
    lines << "\t#{name.split(".").drop(1).join(".")} = #{entry.fetch(:value).inspect}"
  end
  "#{lines.join("\n")}\n"
end

.repair_gemspec_homepage(project_root, env) ⇒ Object



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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/kettle/jem/tasks/install_task.rb', line 522

def repair_gemspec_homepage(project_root, env)
  gemspec_path = Dir.glob(File.join(project_root.to_s, "*.gemspec")).min
  return nil unless gemspec_path

  content = File.read(gemspec_path)
  homepage_record = Kettle::Jem.gemspec_assignment_records(content, receiver: "spec")
    .find { |record| record.fetch(:field) == "homepage" }
  unless homepage_record
    return {
      name: "gemspec_homepage_literal",
      status: "skipped",
      reason: "missing_homepage"
    }
  end

  assigned = homepage_record[:value]
  if literal_github_homepage?(assigned)
    return {
      name: "gemspec_homepage_literal",
      path: File.basename(gemspec_path),
      status: "already_current"
    }
  end

  org = github_org_from_env(env) || github_org_from_origin(project_root)
  gem_name = gemspec_name(content, gemspec_path)
  if org.to_s.empty? || gem_name.to_s.empty?
    return {
      name: "gemspec_homepage_literal",
      path: File.basename(gemspec_path),
      status: "skipped",
      reason: "missing_github_org"
    }
  end

  homepage = "https://github.com/#{org}/#{gem_name}"
  receiver = homepage_record.fetch(:receiver)
  field = homepage_record.fetch(:field)
  indent = Kettle::Jem.leading_whitespace(homepage_record.fetch(:source))
  updated = Kettle::Jem.replace_source_range_lines(
    content,
    homepage_record.fetch(:start_line),
    homepage_record.fetch(:end_line),
    "#{indent}#{receiver}.#{field} = #{homepage.dump}\n"
  )
  File.write(gemspec_path, updated) if updated != content
  {
    name: "gemspec_homepage_literal",
    path: File.basename(gemspec_path),
    status: (updated == content) ? "already_current" : "applied",
    homepage: homepage
  }
end

.replace_character_ranges(content, replacements) ⇒ Object



494
495
496
497
498
# File 'lib/kettle/jem/tasks/install_task.rb', line 494

def replace_character_ranges(content, replacements)
  replacements.sort_by(&:first).reverse.reduce(content.to_s) do |updated, (start_character_offset, end_character_offset, replacement)|
    "#{updated[0...start_character_offset]}#{replacement}#{updated[end_character_offset..]}"
  end
end

.retry_after_unsupported_templating_platform(name:, command:, project_root:, env:, quiet:, command_runner:, failure:) ⇒ Object



1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
# File 'lib/kettle/jem/tasks/install_task.rb', line 1949

def retry_after_unsupported_templating_platform(name:, command:, project_root:, env:, quiet:, command_runner:, failure:)
  platform = unsupported_templating_platform(failure[:stderr], project_root)
  return unless platform

  recovery_command = ["bundle", "lock", "--remove-platform=#{platform}"]
  recovery = command_runner.call(recovery_command, chdir: project_root, env: env, quiet: quiet)
  return unless recovery.fetch(:success)

  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  retried = command_runner.call(command, chdir: project_root, env: env, quiet: quiet)
  return unless retried.fetch(:success)

  {
    name: name,
    command: command,
    status: "succeeded",
    exitstatus: retried[:exitstatus],
    duration_ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000.0).round(3),
    recovered: true,
    recovery: {
      command: recovery_command,
      platform: platform,
      status: "succeeded",
      changed_files: ["Gemfile.lock"]
    }
  }
end

.rewrite_yard_binstub(project_root) ⇒ Object



1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
# File 'lib/kettle/jem/tasks/install_task.rb', line 1052

def rewrite_yard_binstub(project_root)
  yard_binstub = File.join(project_root.to_s, "bin", "yard")
  unless File.file?(yard_binstub)
    return {
      name: "yard_binstub_rake_handoff",
      status: "skipped",
      reason: "missing_yard_binstub",
      path: "bin/yard"
    }
  end

  content = yard_binstub_rake_handoff_content
  if File.read(yard_binstub) == content
    return {
      name: "yard_binstub_rake_handoff",
      status: "already_current",
      reason: "yard_binstub_already_runs_rake_yard",
      path: "bin/yard"
    }
  end

  executable = File.executable?(yard_binstub)
  File.write(yard_binstub, content)
  FileUtils.chmod("+x", yard_binstub) if executable
  {
    name: "yard_binstub_rake_handoff",
    status: "updated",
    reason: "yard_plugins_require_rake_yard_postprocess_hooks",
    path: "bin/yard"
  }
end

.rubocop_gradual_autocorrect_command ⇒ Object



901
902
903
# File 'lib/kettle/jem/tasks/install_task.rb', line 901

def rubocop_gradual_autocorrect_command
  ["sh", "-c", "rm -f .rubocop_gradual.lock && bin/rake rubocop_gradual:autocorrect"]
end

.rubocop_gradual_autocorrect_step(project_root, env: nil, run_options: {}) ⇒ Object



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
# File 'lib/kettle/jem/tasks/install_task.rb', line 867

def rubocop_gradual_autocorrect_step(project_root, env: nil, run_options: {})
  if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_rubocop_gradual])
    return {
      name: "rubocop_gradual_autocorrect",
      status: "skipped",
      reason: "skip_rubocop_gradual"
    }
  end

  rakefile = File.join(project_root.to_s, "Rakefile")
  bin_rake = File.join(project_root.to_s, "bin", "rake")
  unless File.file?(rakefile) && File.file?(bin_rake)
    return {
      name: "rubocop_gradual_autocorrect",
      status: "skipped",
      reason: "missing_rake_entrypoint"
    }
  end
  unless rake_task_available?(project_root, "rubocop_gradual:autocorrect", env: env)
    return {
      name: "rubocop_gradual_autocorrect",
      status: "skipped",
      reason: "missing_rubocop_gradual_task"
    }
  end

  {
    name: "rubocop_gradual_autocorrect",
    command: rubocop_gradual_autocorrect_command,
    status: "ready",
    reason: "post_template_style_normalization"
  }
end

.rubocop_lts_local_branch_step(report, env:, project_root: nil) ⇒ Object



912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
# File 'lib/kettle/jem/tasks/install_task.rb', line 912

def rubocop_lts_local_branch_step(report, env:, project_root: nil)
  local_root = rubocop_lts_local_root(env)
  return nil unless local_root

  ruby_gem = report.dig(:facts, :templates, :tokens, "KJ|RUBOCOP_RUBY_GEM").to_s
  branch = Kettle::Rb::CompatMatrix.rubocop_lts_branch_for_gem(ruby_gem)
  unless branch
    raise Kettle::Jem::Error, "Cannot select RUBOCOP_LTS_DEV branch for #{ruby_gem.inspect}"
  end

  checkout = File.join(local_root, "rubocop-lts")
  if project_root && same_path?(project_root, checkout)
    return {
      name: "rubocop_lts_local_branch",
      status: "skipped",
      path: checkout,
      branch: branch,
      reason: "destination_is_rubocop_lts_checkout"
    }
  end

  current = current_git_branch(checkout)
  if current == branch
    return {
      name: "rubocop_lts_local_branch",
      status: "already_current",
      path: checkout,
      branch: branch
    }
  end

  {
    name: "rubocop_lts_local_branch",
    command: %W[git -C #{checkout} switch #{branch}],
    status: "ready",
    path: checkout,
    current_branch: current,
    branch: branch,
    reason: "rubocop_lts_local_branch_matrix"
  }
end

.rubocop_lts_local_root(env) ⇒ Object



960
961
962
963
964
965
966
967
968
969
970
# File 'lib/kettle/jem/tasks/install_task.rb', line 960

def rubocop_lts_local_root(env)
  env ||= {}
  # RUBOCOP_LTS_LOCAL is a compatibility alias for projects generated
  # before the workspace selector was normalized to *_DEV.
  value = env.fetch("RUBOCOP_LTS_DEV", env["RUBOCOP_LTS_LOCAL"]).to_s.strip
  return nil if value.empty? || Kettle::Jem::DecisionPolicy.falsey?(value)
  return File.join((env || {})["HOME"].to_s.empty? ? Dir.home : (env || {})["HOME"].to_s, "src", "rubocop-lts") if value.casecmp("true").zero? || value == "1" || value.casecmp("yes").zero? || value.casecmp("on").zero?
  return value if value.start_with?("/")

  File.join((env || {})["HOME"].to_s.empty? ? Dir.home : (env || {})["HOME"].to_s, value)
end

.ruby_string_literal_content(value, quote) ⇒ Object



489
490
491
492
# File 'lib/kettle/jem/tasks/install_task.rb', line 489

def ruby_string_literal_content(value, quote)
  escaped = value.to_s.gsub("\\", "\\\\\\\\")
  quote.to_s.empty? ? escaped : escaped.gsub(quote.to_s, "\\#{quote}")
end

.run(project_root: Dir.pwd, env: ENV, run_options: {}, command_runner: method(:run_system_command)) ⇒ Object



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
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
# File 'lib/kettle/jem/tasks/install_task.rb', line 28

def run(project_root: Dir.pwd, env: ENV, run_options: {}, command_runner: method(:run_system_command))
  effective_run_options = install_run_options(env, run_options)
  config_migration_step = kettle_config_migration_step(project_root)
  report = Kettle::Jem.apply_project(project_root, env: env, run_options: effective_run_options)
  report = followup_apply_after_config_bootstrap(project_root, env: env, run_options: effective_run_options, report: report)
  install_steps = []
  install_steps << config_migration_step if config_migration_step
  install_steps << gemspec_dependency_sync_step(report)
  install_steps.concat(version_gem_bootstrap_steps(project_root, report))
  install_steps.concat(post_template_project_fix_steps(project_root, report, env: env))
  mise_step = mise_trust_step(project_root, report, env: env, install_steps: install_steps)
  install_steps << mise_step if mise_step
  install_steps << hook_templates_step(project_root, effective_run_options)
  install_steps << git_drivers_step(project_root, effective_run_options)
  install_steps << ensure_bin_setup_executable(project_root)
  setup_env = setup_command_env(project_root, env)
  rubocop_lts_branch_step = rubocop_lts_local_branch_step(report, env: setup_env, project_root: project_root)
  install_steps << rubocop_lts_branch_step if rubocop_lts_branch_step
  install_steps << run_distinct_bundle_install_step(project_root, env: env, setup_env: setup_env, run_options: effective_run_options, command_runner: command_runner)
  install_steps.concat(run_bundle_setup_commands(project_root, env: setup_env, run_options: effective_run_options, command_runner: command_runner))
  install_steps << appraisal_generate_step(project_root, env: setup_env, run_options: effective_run_options)
  install_steps << rubocop_gradual_autocorrect_step(project_root, env: setup_env, run_options: effective_run_options)
  install_steps << normalize_lockfile_platforms_step(project_root, env: setup_env, run_options: effective_run_options)
  install_steps << normalize_lockfile_step(project_root, env: setup_env, run_options: effective_run_options)
  install_steps << bundled_handoff_step(project_root: project_root, env: env, run_options: effective_run_options)
  install_steps = execute_orchestration_steps(install_steps, project_root: project_root, env: setup_env, run_options: effective_run_options, command_runner: command_runner)

  final_report = report.merge(
    mode: "install",
    installed: true,
    install_steps: install_steps,
    install_phase_reports: install_phase_reports(install_steps),
    install_summary: install_step_summary(install_steps),
    diagnostics: report.fetch(:diagnostics) + [{
      severity: "advisory",
      message: "kettle:jem:install applied templates, completed local post-template checks, and executed available orchestration steps."
    }]
  )
  final_report = Kettle::Jem::MaintenanceChangelog.record_template_run(
    project_root: project_root,
    report: final_report,
    run_options: effective_run_options
  )
  bootstrap_commit = bootstrap_commit_step(project_root, run_options: effective_run_options)
  install_steps.concat(
    execute_orchestration_steps(
      [bootstrap_commit],
      project_root: project_root,
      env: setup_env,
      run_options: effective_run_options,
      command_runner: command_runner
    )
  )
  final_report = final_report.merge(
    install_steps: install_steps,
    install_phase_reports: install_phase_reports(install_steps),
    install_summary: install_step_summary(install_steps)
  )
  Kettle::Jem.emit_summary_event(Kettle::Jem.event_stream_from_options(effective_run_options), final_report)
  final_report
end

.run_bundle_setup_commands(project_root, env:, run_options:, command_runner:) ⇒ Object



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/kettle/jem/tasks/install_task.rb', line 651

def run_bundle_setup_commands(project_root, env:, run_options:, command_runner:)
  quiet = Kettle::Jem::DecisionPolicy.value_to_boolean(run_options[:quiet])
  steps = [
    run_command_step(
      "bin_setup",
      bin_setup_command(project_root, quiet: quiet),
      project_root: project_root,
      env: env,
      quiet: quiet,
      command_runner: command_runner
    )
  ]
  steps << if Kettle::Jem::DecisionPolicy.value_to_boolean((run_options || {})[:skip_binstubs])
    {
      name: "bundle_binstubs",
      status: "skipped",
      reason: "skip_binstubs"
    }
  else
    run_command_step(
      "bundle_binstubs",
      bundle_binstubs_command(project_root, env: env),
      project_root: project_root,
      env: env,
      quiet: quiet,
      command_runner: command_runner
    )
  end
  if steps.any? { |step| step.fetch(:name) == "bundle_binstubs" && step.fetch(:status) == "succeeded" }
    steps << rewrite_yard_binstub(project_root)
    steps << prune_unwanted_bundler_binstubs(project_root)
    steps << ensure_curated_binstubs_executable(project_root)
    steps << validate_bundle_binstub_location(project_root)
  end
  steps
end

.run_command_step(name, command, project_root:, env:, quiet:, command_runner:) ⇒ Object

Raises:



1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
# File 'lib/kettle/jem/tasks/install_task.rb', line 1911

def run_command_step(name, command, project_root:, env:, quiet:, command_runner:)
  if command.first == File.join("bin", "setup") && !File.exist?(File.join(project_root, "bin", "setup"))
    return {
      name: name,
      command: command,
      status: "skipped",
      reason: "missing bin/setup"
    }
  end

  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = command_runner.call(command, chdir: project_root, env: env, quiet: quiet)
  duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000.0).round(3)
  success = result.fetch(:success)
  if success
    return {
      name: name,
      command: command,
      status: "succeeded",
      exitstatus: result[:exitstatus],
      duration_ms: duration_ms
    }
  end

  recovered = retry_after_unsupported_templating_platform(
    name: name,
    command: command,
    project_root: project_root,
    env: env,
    quiet: quiet,
    command_runner: command_runner,
    failure: result
  )
  return recovered if recovered

  raise Kettle::Jem::Error, "#{name} failed: #{command.join(" ")}\n#{result[:stderr]}"
end

.run_distinct_bundle_install_step(project_root, env:, setup_env:, run_options:, command_runner:) ⇒ Object



854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/kettle/jem/tasks/install_task.rb', line 854

def run_distinct_bundle_install_step(project_root, env:, setup_env:, run_options:, command_runner:)
  step = distinct_bundle_install_step(project_root, env: env, setup_env: setup_env)
  return step unless step.fetch(:status) == "ready"

  execute_ready_command_step(
    step,
    project_root: project_root,
    env: setup_env,
    quiet: Kettle::Jem::DecisionPolicy.value_to_boolean(run_options[:quiet]),
    command_runner: command_runner
  )
end

.run_ready_step_command(step_name, command, project_root:, env:, quiet:, command_runner:) ⇒ Object

Raises:



2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
# File 'lib/kettle/jem/tasks/install_task.rb', line 2061

def run_ready_step_command(step_name, command, project_root:, env:, quiet:, command_runner:)
  attempts = git_operation_step_name?(step_name) ? GIT_OPERATION_LOCK_RETRY_ATTEMPTS : 1
  attempt = 0
  last_result = nil
  last_duration_ms = 0.0
  loop do
    attempt += 1
    started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    last_result = command_runner.call(command, chdir: project_root, env: env, quiet: quiet)
    last_duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000.0).round(3)
    if last_result.fetch(:success)
      return {
        success: true,
        exitstatus: last_result[:exitstatus],
        duration_ms: last_duration_ms,
        attempts: attempt
      }
    end

    break unless attempt < attempts && git_lock_conflict?(last_result[:stderr])

    sleep(GIT_OPERATION_LOCK_RETRY_SLEEP_SECONDS * attempt)
  end

  raise Kettle::Jem::Error, "#{step_name} failed: #{command.join(" ")}\n#{last_result[:stderr]}"
end

.run_system_command(command, chdir:, env:, quiet:) ⇒ Object



2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
# File 'lib/kettle/jem/tasks/install_task.rb', line 2272

def run_system_command(command, chdir:, env:, quiet:)
  command_env = quiet ? quiet_command_env(env) : (env || {})
  stdout, stderr, status = Open3.capture3(command_env, *quiet_command(command, quiet: quiet), chdir: chdir)
  $stdout.print(stdout) if !quiet && !stdout.empty?
  $stderr.print(stderr) if !quiet && !stderr.empty?
  {
    success: status.success?,
    exitstatus: status.exitstatus,
    stdout: stdout,
    stderr: stderr
  }
end

.same_bundle_env?(left, right) ⇒ Boolean

Returns:

  • (Boolean)


1316
1317
1318
# File 'lib/kettle/jem/tasks/install_task.rb', line 1316

def same_bundle_env?(left, right)
  bundle_env_fingerprint(left) == bundle_env_fingerprint(right)
end

.same_path?(left, right) ⇒ Boolean

Returns:

  • (Boolean)


954
955
956
957
958
# File 'lib/kettle/jem/tasks/install_task.rb', line 954

def same_path?(left, right)
  File.realpath(left.to_s) == File.realpath(right.to_s)
rescue Errno::ENOENT
  File.expand_path(left.to_s) == File.expand_path(right.to_s)
end

.semantic_git_driver_attribute_updates ⇒ Object



1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'lib/kettle/jem/tasks/install_task.rb', line 1582

def semantic_git_driver_attribute_updates
  GIT_DRIVER_LANGUAGE_REGISTRY.values.map do |definition|
    {
      path: ".gitattributes",
      pattern: definition.fetch(:pattern),
      attributes: {"diff" => definition.fetch(:diff)}
    }
  end
end

.setup_command_env(project_root, env) ⇒ Object



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/kettle/jem/tasks/install_task.rb', line 1278

def setup_command_env(project_root, env)
  command_env = (env || {}).to_h.dup
  templating_requested = command_env.fetch("K_JEM_TEMPLATING", "false").casecmp("true").zero?
  requested_bundler_version = command_env["KJ_BUNDLER_VERSION"].to_s.strip
  requested_gemfile = command_env["BUNDLE_GEMFILE"].to_s
  disable_checksum_validation = command_env["BUNDLE_DISABLE_CHECKSUM_VALIDATION"]
  strip_inherited_bundler_activation!(command_env)
  command_env["BUNDLER_VERSION"] = requested_bundler_version unless requested_bundler_version.empty?
  gemfile = File.join(project_root.to_s, "Gemfile")
  if File.file?(gemfile) || (!requested_gemfile.empty? && same_path?(requested_gemfile, gemfile))
    command_env["BUNDLE_GEMFILE"] = gemfile
  end
  command_env["K_JEM_TEMPLATING"] = "true" if templating_requested
  command_env["BUNDLE_DISABLE_CHECKSUM_VALIDATION"] = disable_checksum_validation unless disable_checksum_validation.nil?
  apply_kettle_family_local_install_env!(command_env)
  apply_kettle_family_appraisal_workers!(command_env)
  command_env["K_JEM_TEMPLATING"] = if templating_requested && local_path_development_env?(command_env)
    "true"
  else
    "false"
  end
  command_env
end

.skipped_lockfile_normalization_step(name, reason) ⇒ Object



818
819
820
# File 'lib/kettle/jem/tasks/install_task.rb', line 818

def skipped_lockfile_normalization_step(name, reason)
  {name: name, status: "skipped", reason: reason}
end

.strip_inherited_bundler_activation!(command_env) ⇒ Object



1382
1383
1384
1385
1386
1387
# File 'lib/kettle/jem/tasks/install_task.rb', line 1382

def strip_inherited_bundler_activation!(command_env)
  (ENV.keys + command_env.keys).grep(/\ABUNDLE_/).each { |key| command_env[key] = nil }
  (ENV.keys + command_env.keys).grep(/\ABUNDLER_/).each { |key| command_env[key] = nil }
  (ENV.keys + command_env.keys).grep(/\AGIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)\z/).each { |key| command_env[key] = nil }
  %w[RUBYLIB RUBYOPT].each { |key| command_env[key] = nil }
end

.strip_leading_decorative_graphemes(text) ⇒ Object



500
501
502
503
504
505
506
507
508
509
# File 'lib/kettle/jem/tasks/install_task.rb', line 500

def strip_leading_decorative_graphemes(text)
  remaining = text.to_s.sub(/\A\s+/, "")
  loop do
    first = first_grapheme(remaining)
    break unless decorative_grapheme?(first)

    remaining = remaining[first.length..].to_s.sub(/\A\s+/, "")
  end
  remaining
end

.sync_readme_gemspec_grapheme(project_root, env) ⇒ Object



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
# File 'lib/kettle/jem/tasks/install_task.rb', line 400

def sync_readme_gemspec_grapheme(project_root, env)
  readme_path = File.join(project_root.to_s, "README.md")
  gemspec_path = Dir.glob(File.join(project_root.to_s, "*.gemspec")).min
  return nil unless File.file?(readme_path) && gemspec_path

  readme = File.read(readme_path)
  gemspec = File.read(gemspec_path)
  grapheme = configured_project_grapheme(project_root, env) || readme_h1_grapheme(readme)
  if grapheme.to_s.empty?
    return {
      name: "readme_gemspec_grapheme_sync",
      status: "skipped",
      reason: "missing_grapheme"
    }
  end

  updated_readme = normalize_readme_h1_grapheme(readme, grapheme)
  updated_gemspec = normalize_gemspec_grapheme(gemspec, grapheme)
  File.write(readme_path, updated_readme) if updated_readme != readme
  File.write(gemspec_path, updated_gemspec) if updated_gemspec != gemspec
  {
    name: "readme_gemspec_grapheme_sync",
    paths: ["README.md", File.basename(gemspec_path)],
    status: (updated_readme == readme && updated_gemspec == gemspec) ? "already_current" : "applied",
    grapheme: grapheme
  }
rescue => error
  {
    name: "readme_gemspec_grapheme_sync",
    status: "skipped",
    reason: error.message
  }
end

.tracked_binstub?(project_root, path) ⇒ Boolean

Returns:

  • (Boolean)


1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'lib/kettle/jem/tasks/install_task.rb', line 1150

def tracked_binstub?(project_root, path)
  relative_path = path.to_s.delete_prefix("#{File.expand_path(project_root.to_s)}/")
  _stdout, _stderr, status = Open3.capture3(
    "git",
    "-C",
    project_root.to_s,
    "ls-files",
    "--error-unmatch",
    "--",
    relative_path
  )
  status.success?
rescue
  false
end

.trim_readme_compatibility_badges(project_root, report) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/kettle/jem/tasks/install_task.rb', line 356

def trim_readme_compatibility_badges(project_root, report)
  readme_path = File.join(project_root.to_s, "README.md")
  return nil unless File.file?(readme_path)

  min_ruby = report.dig(:facts, :rubygems, :min_ruby)
  if min_ruby.to_s.empty?
    return {
      name: "readme_compatibility_badges",
      status: "skipped",
      reason: "missing_min_ruby"
    }
  end

  before = File.read(readme_path)
  after = Kettle::Jem::ReadmePostProcessor.process(
    content: before,
    min_ruby: Gem::Version.new(Kettle::Jem.minimum_ruby_token(min_ruby)),
    engines: report.dig(:facts, :rubygems, :engines),
    workflow_paths: github_workflow_paths(project_root)
  )
  File.write(readme_path, after) if after != before
  {
    name: "readme_compatibility_badges",
    path: "README.md",
    status: (after == before) ? "already_current" : "applied"
  }
rescue => error
  {
    name: "readme_compatibility_badges",
    path: "README.md",
    status: "skipped",
    reason: error.message
  }
end

.unsafe_git_driver_command_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


1706
1707
1708
# File 'lib/kettle/jem/tasks/install_task.rb', line 1706

def unsafe_git_driver_command_value?(value)
  value.include?("$(") || value.include?("${") || value.include?("`")
end

.unsupported_templating_platform(stderr, project_root) ⇒ Object



1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
# File 'lib/kettle/jem/tasks/install_task.rb', line 1977

def unsupported_templating_platform(stderr, project_root)
  # Bundler exposes this compatibility failure only as stderr text; match
  # its exact quoted diagnostic rather than guessing from lockfile content.
  match = /Could not find gem 'tree_sitter_language_pack' with platform '([^']+)'/.match(stderr.to_s)
  return unless match

  lock_path = File.join(project_root.to_s, "Gemfile.lock")
  return unless File.file?(lock_path)

  platforms = Bundler::LockfileParser.new(Bundler.read_file(lock_path)).platforms.map(&:to_s)
  platform = match[1]
  platforms.include?(platform) ? platform : nil
rescue Bundler::LockfileError
  nil
end

.validate_bundle_binstub_location(project_root) ⇒ Object



1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# File 'lib/kettle/jem/tasks/install_task.rb', line 1022

def validate_bundle_binstub_location(project_root)
  destination_bin = File.join(project_root.to_s, "bin")
  destination_binstubs = binstub_files(destination_bin)
  parent_root = git_toplevel(project_root)
  parent_binstubs = if parent_root && File.expand_path(parent_root) != File.expand_path(project_root.to_s)
    binstub_files(File.join(parent_root, "bin"))
  else
    []
  end

  if destination_binstubs.empty? && parent_binstubs.any?
    return {
      name: "bundle_binstub_location_validation",
      status: "warning",
      reason: "parent_bin_has_binstubs_but_destination_bin_has_none",
      destination_bin: relative_or_absolute_path(destination_bin, project_root),
      parent_bin: relative_or_absolute_path(File.join(parent_root, "bin"), project_root),
      parent_binstubs: parent_binstubs.map { |path| File.basename(path) }.sort
    }
  end

  {
    name: "bundle_binstub_location_validation",
    status: destination_binstubs.empty? ? "unverified" : "succeeded",
    reason: destination_binstubs.empty? ? "no_destination_binstubs_found" : "destination_bin_has_binstubs",
    destination_bin: relative_or_absolute_path(destination_bin, project_root),
    destination_binstubs: destination_binstubs.map { |path| File.basename(path) }.sort
  }
end

.validate_git_driver_manifest!(manifest) ⇒ Object

Raises:



1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
# File 'lib/kettle/jem/tasks/install_task.rb', line 1676

def validate_git_driver_manifest!(manifest)
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: root must be a mapping" unless manifest.is_a?(Hash)
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: version must be 1" unless manifest["version"] == 1

  profiles = manifest["profiles"]
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profiles must be a mapping" unless profiles.is_a?(Hash)

  profiles.each do |profile_name, profile|
    validate_git_driver_profile!(profile_name, profile)
  end
end

.validate_git_driver_profile!(profile_name, profile) ⇒ Object

Raises:



1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
# File 'lib/kettle/jem/tasks/install_task.rb', line 1688

def validate_git_driver_profile!(profile_name, profile)
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profile name is required" if profile_name.to_s.empty?
  raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profile #{profile_name} must be a mapping" unless profile.is_a?(Hash)

  Array(profile.fetch("attributes", [])).each do |entry|
    raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profile #{profile_name} attribute pattern is required" if entry["pattern"].to_s.empty?
  end
  Array(profile.fetch("git_config", [])).each do |entry|
    raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profile #{profile_name} git_config scope must be global" unless entry["scope"] == "global"
    raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: profile #{profile_name} git_config key is required" if entry["key"].to_s.empty?
    if entry["key"].to_s.end_with?(".cachetextconv") && !profile_name.to_s.include?("textconv")
      raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: cachetextconv requires an explicit textconv profile"
    end
    value = entry["value"].to_s
    raise Kettle::Jem::Error, "Invalid .structuredmerge/git-drivers.toml: unsafe command interpolation" if unsafe_git_driver_command_value?(value)
  end
end

.value_arg(flag, value) ⇒ Object



1896
1897
1898
# File 'lib/kettle/jem/tasks/install_task.rb', line 1896

def value_arg(flag, value)
  value.to_s.strip.empty? ? [] : [flag, value.to_s]
end

.version_gem_bootstrap_steps(project_root, report) ⇒ Object



186
187
188
189
190
191
192
193
# File 'lib/kettle/jem/tasks/install_task.rb', line 186

def version_gem_bootstrap_steps(project_root, report)
  existing = report.fetch(:post_apply_steps, []).select do |step|
    %w[version_gem_bootstrap version_gem_cleanup legacy_rbs_consolidation].include?(step.fetch(:name, nil))
  end
  return existing unless existing.empty?

  [Kettle::Jem.template_version_gem_bootstrap_step(project_root, report)].flatten.compact
end

.with_git_operation_lock(env, metadata_key:) ⇒ Object



2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
# File 'lib/kettle/jem/tasks/install_task.rb', line 2108

def with_git_operation_lock(env, metadata_key:)
  lock_path = git_operation_lock_path(env || {})
  return yield if lock_path.to_s.empty?

  FileUtils.mkdir_p(File.dirname(lock_path))
  File.open(lock_path, File::RDWR | File::CREAT, 0o644) do |lock|
    lock.flock(File::LOCK_EX)
    yield.merge( => lock_path)
  ensure
    lock&.flock(File::LOCK_UN)
  end
end

.yard_binstub_rake_handoff_content ⇒ Object



1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
# File 'lib/kettle/jem/tasks/install_task.rb', line 1084

def yard_binstub_rake_handoff_content
  <<~RUBY
    #!/usr/bin/env ruby
    # frozen_string_literal: true

    # Generated by kettle-jem after curated `bundle binstubs`.
    #
    # Bundler's normal yard binstub executes the raw YARD CLI. That skips
    # Rake task enhancements installed by documentation plugins such as
    # yard-timekeeper. Those plugins run after YARD finishes and may restore
    # checked-in docs files whose only diff is generated timestamp churn.
    #
    # The canonical docs entrypoint is therefore the Rake task, not raw
    # `yard` / `bin/yard`. Keep this binstub as a handoff to the task so
    # humans and tools that reach for `bin/yard` still run the full docs
    # workflow with post-processing hooks.
    exec("bundle", "exec", "rake", "yard")
  RUBY
end