Module: KKGit::AutoFormat

Defined in:
lib/kk/git/auto_format.rb

Overview

Best-effort format changed files before commit; skip missing tools.

Defined Under Namespace

Classes: Language, Tool

Constant Summary collapse

LANGUAGES =
[
  Language.new(
    id: :ruby,
    label: 'Ruby',
    extensions: %w[.rb],
    tools: [
      Tool.new(name: 'rubocop', bin: 'rubocop', argv: ['-A', '--force-exclusion', '%{files}'])
    ]
  ),
  Language.new(
    id: :python,
    label: 'Python',
    extensions: %w[.py],
    tools: [
      Tool.new(name: 'ruff', bin: 'ruff', argv: ['format', '%{files}']),
      Tool.new(name: 'black', bin: 'black', argv: ['%{files}'])
    ]
  ),
  Language.new(
    id: :go,
    label: 'Go',
    extensions: %w[.go],
    tools: [
      Tool.new(name: 'gofmt', bin: 'gofmt', argv: ['-w', '%{files}'])
    ]
  ),
  Language.new(
    id: :bash,
    label: 'Bash',
    extensions: %w[.sh .bash],
    tools: [
      Tool.new(name: 'shfmt', bin: 'shfmt', argv: ['-w', '%{files}'])
    ]
  ),
  Language.new(
    id: :prettier,
    label: 'JS/TS/Node',
    extensions: %w[.js .jsx .mjs .cjs .ts .tsx .json .css .scss .less .html .md .yaml .yml],
    tools: [
      Tool.new(name: 'prettier', bin: 'prettier', argv: ['--write', '%{files}'])
    ]
  )
].freeze

Class Method Summary collapse

Class Method Details

.all_tracked_files(repo_dir:) ⇒ Object



142
143
144
145
146
147
# File 'lib/kk/git/auto_format.rb', line 142

def all_tracked_files(repo_dir:)
  out, _err, ok = GitOps.run_cmd('git', 'ls-files', '-z', chdir: repo_dir)
  return [] unless ok

  out.split("\0").reject(&:empty?)
end

.changed_files(repo_dir:) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/kk/git/auto_format.rb', line 128

def changed_files(repo_dir:)
  out, _err, ok = GitOps.run_cmd('git', 'status', '--porcelain', '-z', chdir: repo_dir)
  return [] unless ok

  out.split("\0").filter_map do |entry|
    next if entry.nil? || entry.empty?

    path = entry[3..]
    next if path.nil? || path.empty? || path.end_with?('/')

    path
  end.uniq
end

.enabled?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/kk/git/auto_format.rb', line 66

def enabled?
  ENV['KK_GIT_SKIP_FORMAT'] != '1'
end

.executable?(path) ⇒ Boolean

Returns:

  • (Boolean)


183
184
185
# File 'lib/kk/git/auto_format.rb', line 183

def executable?(path)
  path && File.file?(path) && File.executable?(path)
end

.format_all?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/kk/git/auto_format.rb', line 70

def format_all?
  ENV['KK_GIT_FORMAT_ALL'] == '1'
end

.group_files(files) ⇒ Object



149
150
151
152
153
154
155
156
157
# File 'lib/kk/git/auto_format.rb', line 149

def group_files(files)
  grouped = Hash.new { |h, k| h[k] = [] }
  files.each do |path|
    ext = File.extname(path)
    language = LANGUAGES.find { |lang| lang.extensions.include?(ext) }
    grouped[language.id] << path if language
  end
  grouped.transform_values { |paths| paths.uniq.sort }
end

.pick_tool(language, _files, repo_dir:) ⇒ Object



159
160
161
162
163
# File 'lib/kk/git/auto_format.rb', line 159

def pick_tool(language, _files, repo_dir:)
  language.tools.find do |tool|
    resolve_bin(tool.bin, repo_dir: repo_dir)
  end
end

.resolve_bin(name, repo_dir:) ⇒ Object



165
166
167
168
169
170
171
172
173
# File 'lib/kk/git/auto_format.rb', line 165

def resolve_bin(name, repo_dir:)
  path = which(name)
  return path if executable?(path)

  local = File.expand_path(File.join(repo_dir, 'node_modules', '.bin', name))
  return local if executable?(local)

  nil
end

.run!(repo_dir: '.', dry_run: GitOps.dry_run?) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/kk/git/auto_format.rb', line 74

def run!(repo_dir: '.', dry_run: GitOps.dry_run?)
  return { ran: [], skipped: [], failed: [] } unless enabled?

  files = target_files(repo_dir: repo_dir)
  grouped = group_files(files)
  return { ran: [], skipped: [], failed: [] } if grouped.empty?

  ran = []
  skipped = []
  failed = []

  grouped.each do |lang_id, paths|
    language = LANGUAGES.find { |l| l.id == lang_id }
    next unless language

    tool = pick_tool(language, paths, repo_dir: repo_dir)
    unless tool
      skipped << "#{language.label}: no formatter (#{language.tools.map(&:name).join(' / ')})"
      next
    end

    cmd = tool.build(paths, repo_dir: repo_dir)
    label = "#{language.label} (#{tool.name})"
    if dry_run
      puts "[dry-run] format #{label}: #{cmd.join(' ')}"
      ran << label
      next
    end

    unless executable?(cmd&.first)
      skipped << "#{label}: not found (#{tool.name})"
      next
    end

    out, err, ok = run_command(cmd, repo_dir: repo_dir)
    if ok
      puts "Formatted #{label}: #{paths.length} file(s)"
      ran << label
    else
      msg = err.to_s.strip.empty? ? out.to_s.strip : err.to_s.strip
      warn "Format failed #{label} (continuing): #{msg.lines.first}"
      failed << label
    end
  end

  skipped.each { |line| puts "Format skip: #{line}" }

  { ran: ran, skipped: skipped, failed: failed }
end

.run_command(cmd, repo_dir:) ⇒ Object



187
188
189
190
191
# File 'lib/kk/git/auto_format.rb', line 187

def run_command(cmd, repo_dir:)
  Open3.capture3(*cmd, chdir: repo_dir)
rescue Errno::ENOENT, Errno::EACCES => e
  ['', e.message, false]
end

.target_files(repo_dir:) ⇒ Object



124
125
126
# File 'lib/kk/git/auto_format.rb', line 124

def target_files(repo_dir:)
  format_all? ? all_tracked_files(repo_dir: repo_dir) : changed_files(repo_dir: repo_dir)
end

.which(cmd) ⇒ Object



175
176
177
178
179
180
181
# File 'lib/kk/git/auto_format.rb', line 175

def which(cmd)
  out, _, ok = Open3.capture3('command', '-v', cmd)
  return nil unless ok

  path = out.strip
  path.empty? ? nil : path
end