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: :js,
    label: 'JS/TS/Node',
    extensions: %w[.js .jsx .mjs .cjs .ts .tsx .json .jsonc .css],
    tools: [
      Tool.new(name: 'biome', bin: 'biome', argv: ['format', '--write', '%{files}']),
      Tool.new(name: 'prettier', bin: 'prettier', argv: ['--write', '%{files}'])
    ]
  ),
  Language.new(
    id: :prettier_docs,
    label: 'Prettier (markup/docs)',
    extensions: %w[.scss .less .html .md .mdx .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



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

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



137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/kk/git/auto_format.rb', line 137

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)


75
76
77
# File 'lib/kk/git/auto_format.rb', line 75

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

.executable?(path) ⇒ Boolean

Returns:

  • (Boolean)


192
193
194
# File 'lib/kk/git/auto_format.rb', line 192

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

.format_all?Boolean

Returns:

  • (Boolean)


79
80
81
# File 'lib/kk/git/auto_format.rb', line 79

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

.group_files(files) ⇒ Object



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

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



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

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



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

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



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/kk/git/auto_format.rb', line 83

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



196
197
198
199
200
# File 'lib/kk/git/auto_format.rb', line 196

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



133
134
135
# File 'lib/kk/git/auto_format.rb', line 133

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

.which(cmd) ⇒ Object



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

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

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