A platform for community discussion. Free, open, simple.
DEV: align bin/lint to use lefthook (#34247)
Sam720cf1cd2185
diff --git a/.github/instructions/copilot.instructions.md b/.github/instructions/copilot.instructions.mdindex ca3222aea6a..282baac7317 120000--- a/.github/instructions/copilot.instructions.md+++ b/.github/instructions/copilot.instructions.md@@ -1 +1 @@-AI-AGENTS.md\ No newline at end of file+../../AI-AGENTS.md\ No newline at end of filediff --git a/bin/lint b/bin/lintindex a210ab3d7be..79f97a72385 100755--- a/bin/lint+++ b/bin/lint@@ -2,133 +2,48 @@# frozen_string_literal: truerequire "optparse"-require "json"require "open3"-require "digest"--class Linter- BATCH_SIZE = 5000-- LINTERS = {- rb: {- rubocop: {- check: "bundle exec rubocop --force-exclusion {files}",- fix: "bundle exec rubocop --force-exclusion -A {files}",- },- syntax_tree: {- check: "bundle exec stree check Gemfile {files}",- fix: "bundle exec stree write Gemfile {files}",- },- },- rake: {- syntax_tree: {- check: "bundle exec stree check {files}",- fix: "bundle exec stree write {files}",- },- },- js: {- eslint: {- check: "pnpm eslint --quiet {files}",- fix: "pnpm eslint --fix {files}",- },- prettier: {- check: "pnpm pprettier --list-different {files}",- fix: "pnpm pprettier --write {files}",- },- },- gjs: {- eslint: {- check: "pnpm eslint --quiet {files}",- fix: "pnpm eslint --fix {files}",- },- prettier: {- check: "pnpm pprettier --list-different {files}",- fix: "pnpm pprettier --write {files}",- },- ember_template_lint: {- check: "pnpm ember-template-lint {files}",- fix: "pnpm ember-template-lint --fix {files}",- },- },- hbs: {- ember_template_lint: {- check: "pnpm ember-template-lint {files}",- fix: "pnpm ember-template-lint --fix {files}",- },- prettier: {- check: "pnpm pprettier --list-different {files}",- fix: "pnpm pprettier --write {files}",- },- },- scss: {- stylelint: {- check: "pnpm stylelint {files}",- fix: "pnpm stylelint --fix {files}",- },- prettier: {- check: "pnpm pprettier --list-different {files}",- fix: "pnpm pprettier --write {files}",- },- },- css: {- prettier: {- check: "pnpm pprettier --list-different {files}",- fix: "pnpm pprettier --write {files}",- },- },- yml: {- yaml_syntax: {- check: "bundle exec yaml-lint {files}",- },- i18n_lint: {- check: "bundle exec ruby script/i18n_lint.rb {files}",- },- },- yaml: {- yaml_syntax: {- check: "bundle exec yaml-lint {files}",- },- },- }.freeze+require "shellwords"+class LefthookLinterdef initialize(options = {})@fix = options[:fix]@recent = options[:recent]+ @staged = options[:staged]+ @unstaged = options[:unstaged]+ @wip = options[:wip]@files = options[:files] || []@verbose = options[:verbose]- @errors = []- @fixed = []end+ EVERYTHING = ["ALL FILES"]+def runfiles_to_lint = determine_files- return success_message if files_to_lint.empty?-- # Phase 1: Group files by linter type and filter appropriately- linter_files = group_files_by_linter(files_to_lint)- # Phase 2: Process each linter's files in batches- linter_files.each do |linter_name, files|- next if files.empty?-- files.each_slice(BATCH_SIZE) { |file_batch| run_linter_batch(linter_name, file_batch) }+ if @fix+ run_fix_mode(files_to_lint)+ else+ run_check_mode(files_to_lint)end-- print_summaryendprivatedef determine_filesreturn recent_files if @recent- return @files unless @files.empty?+ return staged_files if @staged+ return unstaged_files if @unstaged+ return wip_files if @wip+ return @files if [email protected]?- all_lintable_files+ EVERYTHINGenddef recent_fileslog_output, status = Open3.capture2("git", "log", "-50", "--name-only", "--pretty=format:")return [] unless status.success?+log_files = log_output.lines.map(&:strip).reject(&:empty?)tracked_out, tracked_status = Open3.capture2("git", "ls-files")@@ -144,27 +59,50 @@ class Linterlog_files.each { |f| candidates << f if tracked.include?(f) }untracked.each { |f| candidates << f }- candidates.select { |f| lintable_file?(f) }+ candidates.select { |f| File.file?(f) && lintable_file?(f) }end- def all_lintable_files- tracked_out, tracked_status = Open3.capture2("git", "ls-files")- untracked_out, untracked_status =- Open3.capture2("git", "ls-files", "--others", "--exclude-standard")- return [] unless tracked_status.success? && untracked_status.success?+ def staged_files+ git_output, status = Open3.capture2("git", "diff", "--cached", "--name-only")+ return [] unless status.success?++ git_output.lines.map(&:strip).reject(&:empty?).select { |f| File.file?(f) && lintable_file?(f) }+ end++ def unstaged_files+ git_output, status = Open3.capture2("git", "diff", "--name-only")+ return [] unless status.success?++ git_output.lines.map(&:strip).reject(&:empty?).select { |f| File.file?(f) && lintable_file?(f) }+ end++ def wip_files+ # Get files changed since main branch+ main_diff_output, main_status = Open3.capture2("git", "diff", "main...HEAD", "--name-only")+ main_files = main_status.success? ? main_diff_output.lines.map(&:strip).reject(&:empty?) : []- tracked = tracked_out.lines.map(&:strip)- untracked = untracked_out.lines.map(&:strip)+ # Get staged files+ staged_output, staged_status = Open3.capture2("git", "diff", "--cached", "--name-only")+ staged = staged_status.success? ? staged_output.lines.map(&:strip).reject(&:empty?) : []- (tracked + untracked).select { |f| File.file?(f) && lintable_file?(f) }+ # Get unstaged files+ unstaged_output, unstaged_status = Open3.capture2("git", "diff", "--name-only")+ unstaged = unstaged_status.success? ? unstaged_output.lines.map(&:strip).reject(&:empty?) : []++ # Combine all files and remove duplicates+ all_files = Set.new(main_files + staged + unstaged)+ all_files.select { |f| File.file?(f) && lintable_file?(f) }enddef lintable_file?(file)+ # Skip certain directories and filesif file.include?("node_modules") || file.include?("vendor") || file.include?("tmp") ||file.include?(".git") || file == "database.yml"return falseend+ return true if file == "Gemfile"+ext = File.extname(file)[1..]# Check for Ruby files in /bin/ directory without extensions@@ -174,164 +112,72 @@ class Linterfirst_line = File.open(file, &:readline)return true if first_line.strip == "#!/usr/bin/env ruby"rescue StandardError- # If we can't read the file, skip itreturn falseendendreturn falseend- LINTERS.key?(ext.to_sym) || (file.include?("/assets/") && %w[js scss css hbs gjs].include?(ext))+ # Check if file extension is lintable+ lintable_extensions = %w[rb rake js gjs hbs scss css yml yaml thor]+ lintable_extensions.include?(ext)end- def group_files_by_extension(files)- files- .group_by do |f|- ext = File.extname(f)[1..]- # Treat Ruby files in /bin/ without extensions as Ruby files- if (ext.nil? || ext.empty?) && f.start_with?("bin/") && File.file?(f)- begin- first_line = File.open(f, &:readline)- ext = "rb" if first_line.strip == "#!/usr/bin/env ruby"- rescue StandardError- # If we can't read the file, keep original extension- end- end- ext- end- .reject { |ext, _| ext.nil? || ext.empty? }- end-- def group_files_by_linter(files)- linter_files = {}- grouped_files = group_files_by_extension(files)-- grouped_files.each do |ext, ext_files|- linters = LINTERS[ext.to_sym]- next unless linters-- linters.each do |linter_name, _commands|- filtered_files = filter_files_for_linter(linter_name, ext_files)- next if filtered_files.empty?-- linter_files[linter_name] ||= []- linter_files[linter_name].concat(filtered_files)- end+ def run_fix_mode(files)+ if files == EVERYTHING+ puts "π§ Running linters in fix mode on all files" if @verbose+ else+ puts "π§ Running linters in fix mode on #{files.length} file/s" if @verboseend- # Remove duplicates that might occur if a file matches multiple linters- linter_files.each { |linter_name, file_list| linter_files[linter_name] = file_list.uniq }- linter_files+ if files == EVERYTHING+ # Run fix-staged on all files (no file filtering)+ run_lefthook_command("fix-staged", [])+ elsif files.empty?+ puts "No files to fix, exiting."+ else+ # Run fix-staged on specific files+ run_lefthook_command("fix-staged", files)+ endend- def run_linter_batch(linter_name, files)- # Find the command for this linter by looking through all file types- command = find_command_for_linter(linter_name)- return unless command-- # Split command into parts and replace {files} placeholder- base_command = command.gsub("{files}", "").strip.split- cmd_args = base_command + files-- puts "Running #{linter_name} on #{files.size} files..." if @verbose-- if @fix- changed_files = detect_changed_files(files, cmd_args)- @fixed.concat(changed_files)+ def run_check_mode(files)+ if files == EVERYTHING+ puts "π Running linters in check mode on all files" if @verboseelse- output, status = Open3.capture2e(*cmd_args)-- unless status.success?- failed_files = parse_failed_files(linter_name, output, files)- @errors << { linter: linter_name, files: failed_files, output: output }- puts "#{linter_name} failed on: #{failed_files.join(", ")}" if @verbose- puts output unless output.strip.empty?- end+ puts "π Running linters in check mode on #{files.length} file/s" if @verboseend- end- def find_command_for_linter(linter_name)- LINTERS.each do |_ext, linters|- linters.each do |name, commands|- return @fix ? commands[:fix] : commands[:check] if name == linter_name- end+ if files == EVERYTHING+ run_lefthook_command("lints", [])+ elsif files.empty?+ puts "No files to lint, exiting."+ else+ run_lefthook_command("pre-commit", files)end- nilend- def detect_changed_files(files, cmd_args)- file_checksums = {}- files.each { |file| file_checksums[file] = file_checksum(file) }-- Open3.capture2e(*cmd_args)+ def run_lefthook_command(hook_name, files)+ cmd = ["pnpm", "lefthook", "run", hook_name]- changed_files = []- files.each { |file| changed_files << file if file_checksum(file) != file_checksums[file] }+ # Only add file arguments if we have specific files+ # For lints and fix-staged without files, let lefthook handle all files+ files.each { |file| cmd << "--file" << file } unless files.empty?- changed_files- end-- def file_checksum(file)- return nil unless File.exist?(file)- Digest::MD5.file(file).hexdigest- end+ # Add verbose flag if requested+ cmd << "--verbose" if @verbose- def parse_failed_files(linter_name, output, all_files)- case linter_name- when :eslint- output.scan(%r{^(/[^\s:]+):\d+:\d+}).flatten.uniq- when :prettier- lines = output.lines.map(&:strip)- lines.select { |line| all_files.any? { |f| line.end_with?(File.basename(f)) } }- when :rubocop- output.scan(/^([^:]+):\d+:\d+/).flatten.uniq- when :ember_template_lint- output.scan(/^([^\s:]+):\d+:\d+/).flatten.uniq- when :stylelint- output.scan(/^([^\s:]+)\s+\d+:\d+/).flatten.uniq- when :syntax_tree- output.scan(/\[\d+m([^\[\]]+)\[0m/).flatten.uniq.select { |f| all_files.include?(f) }- when :yaml_syntax, :i18n_lint- all_files.select { |f| output.include?(f) }- else- all_files- end- end+ puts "Running: #{cmd.shelljoin}" if @verbose- def filter_files_for_linter(name, files)- case name- when :prettier, :ember_template_lint- files.select do |file|- file.include?("/assets/javascripts/") || file.include?("/plugins/") ||- file.include?("/themes/")- end- when :i18n_lint- files.select { |file| file.match?(%r{/(client|server)\..*\.yml$}) }- when :yaml_syntax- files.select { |file| !file.end_with?("database.yml") }- when :syntax_tree- # syntax_tree doesn't handle files without extensions well, skip for bin/ files- files.select { |file| !file.start_with?("bin/") || File.extname(file) != "" }- else- files- end- end+ # Use system to preserve colored output and proper exit codes+ success = system(*cmd)- def print_summary- if @errors.empty?- if @fix && @fixed.any?- puts "β Fixed #{@fixed.size} files"- else- puts "β All files passed linting"- end- else- puts "β Linting failed on #{@errors.map { |e| e[:files] }.flatten.uniq.size} files"+ unless success+ puts "β Linting failed"exit 1end- end- def success_message- puts "No files to lint"+ puts "β All linting checks passed" if @verboseendend@@ -346,10 +192,16 @@ def parse_optionsputs parserputsputs "Examples:"- puts " bin/lint # Lint all files"- puts " bin/lint --recent # Lint recently changed files"- puts " bin/lint --fix app.rb # Fix specific file"- puts " bin/lint app/models/*.rb # Lint multiple files"+ puts " bin/lint # Lint all files"+ puts " bin/lint --recent # Lint recently changed files"+ puts " bin/lint --staged # Lint only staged files"+ puts " bin/lint --unstaged # Lint only unstaged files"+ puts " bin/lint --wip # Lint staged + unstaged + files changed since main"+ puts " bin/lint --fix app.rb file2.js # Fix specific file/s"+ puts " bin/lint app/models/*.rb # Lint multiple files"+ puts+ puts "Note: This script now uses lefthook to run linters."+ puts "Check lefthook.yml for linting configuration."exitend@@ -359,6 +211,14 @@ def parse_optionsoptions[:recent] = trueend+ parser.on("--staged", "Lint only staged files") { options[:staged] = true }++ parser.on("--unstaged", "Lint only unstaged files") { options[:unstaged] = true }++ parser.on("--wip", "Lint work-in-progress: staged + unstaged + files changed since main") do+ options[:wip] = true+ end+parser.on("-v", "--verbose", "Show verbose output") { options[:verbose] = true }end.parse!@@ -369,6 +229,6 @@ endif __FILE__ == $0options = parse_options- linter = Linter.new(options)+ linter = LefthookLinter.new(options)linter.runenddiff --git a/lefthook.yml b/lefthook.ymlindex 87ee39b957d..73886650005 100644--- a/lefthook.yml+++ b/lefthook.yml@@ -9,25 +9,21 @@ pre-commit:- rebasecommands:rubocop:- glob: "*.rb"+ glob: "*.{rb,rake,thor}"run: bundle exec rubocop --force-exclusion {staged_files}syntax_tree:- glob: "*.{rb,rake}"+ glob: "*.{rb,rake,thor}"run: bundle exec stree check Gemfile {staged_files}prettier:- glob: "*.js"- include: "app/assets/javascripts|plugins/.+?/assets/javascripts"- run: pnpm pprettier --list-different {staged_files}- prettier-scss:- glob: "*.scss"- include: "app/assets/stylesheets|plugins/.+?/assets/stylesheets"+ glob: "*.{js,gjs,hbs,scss,css,cjs,mjs}"+ include: "app/assets|plugins/.+?/assets|themes"run: pnpm pprettier --list-different {staged_files}eslint:- glob: "*.js"+ glob: "*.{js,gjs}"include: "app/assets/javascripts|plugins/.+?/assets/javascripts"run: pnpm eslint --quiet {staged_files}ember-template-lint:- glob: "*.hbs"+ glob: "*.{hbs,gjs}"include: "app/assets/javascripts|plugins/.+?/assets/javascripts"run: pnpm ember-template-lint {staged_files}yaml-syntax:@@ -38,19 +34,35 @@ pre-commit:i18n-lint:glob: "**/{client,server}.en.yml"run: bundle exec ruby script/i18n_lint.rb {staged_files}+ stylelint:+ glob: "*.scss"+ include: "app/assets/stylesheets|plugins/.+?/assets/stylesheets|themes"+ run: pnpm stylelint {staged_files}fix-staged:parallel: falsecommands:prettier:- glob: "*.js"- include: "app/assets/javascripts|plugins/.+?/assets/javascripts"+ glob: "*.{js,gjs,hbs,scss,css,cjs,mjs}"+ include: "app/assets|plugins/.+?/assets|themes"run: pnpm pprettier --write {staged_files}+ eslint:+ glob: "*.{js,gjs}"+ include: "app/assets/javascripts|plugins/.+?/assets/javascripts|themes"+ run: pnpm eslint --fix {staged_files}+ ember-template-lint:+ glob: "*.{gjs,hbs}"+ include: "app/assets/javascripts|plugins/.+?/assets/javascripts|themes"+ run: pnpm ember-template-lint --fix {staged_files}+ stylelint:+ glob: "*.scss"+ include: "app/assets/stylesheets|plugins/.+?/assets/stylesheets|themes"+ run: pnpm stylelint --fix {staged_files}rubocop:- glob: "*.rb"+ glob: "*.{rb,rake,thor}"run: bundle exec rubocop --force-exclusion -A {staged_files}syntax_tree:- glob: "*.{rb,rake}"+ glob: "*.{rb,rake,thor}"run: bundle exec stree write Gemfile {staged_files}lints:@@ -60,13 +72,13 @@ lints:glob: "*.rb"run: bundle exec rubocopprettier:- run: pnpm pprettier --list-different **/*.js- prettier-scss:- run: pnpm pprettier --list-different **/*.scss+ run: pnpm lint:prettiereslint:- run: pnpm eslint -f compact --quiet --ext .js .+ run: pnpm lint:jsember-template-lint:- run: pnpm ember-template-lint .+ run: pnpm lint:hbs+ stylelint:+ run: pnpm lint:cssyaml-syntax:glob: "*.{yaml,yml}"# database.yml is an erb file not a yaml file@@ -75,3 +87,5 @@ lints:i18n-lint:glob: "**/{client,server}.en.yml"run: bundle exec ruby script/i18n_lint.rb {all_files}+ glint:+ run: pnpm glint -p jsconfig.json --noEmit