From a2886e026011c2a90b5b0fcf0a77d513bcb92c3c Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Mon, 30 Nov 2026 13:00:42 -0800 Subject: [PATCH 1/2] Add rubocop-gusto Inherit the shared rubocop-gusto config, as packs, pack_stats and packwerk-extensions already do. - Add rubocop-gusto as a development dependency - Inherit rubocop-gusto's config/default.yml and load its plugin - Exclude bin/ (generated binstubs) - Enforce double-quoted string literals (Style/StringLiterals) - Apply all safe autocorrections (double quotes, sigils, trailing commas, %w()/%x() literals, blank lines between rspec groups, etc.) - Record the remaining unsafe/non-correctable offenses in .rubocop_todo.yml --- .rubocop.yml | 19 + .rubocop_todo.yml | 98 ++++ Gemfile | 4 +- Rakefile | 6 +- code_ownership.gemspec | 69 +-- ext/code_ownership/extconf.rb | 9 +- lib/code_ownership.rb | 36 +- lib/code_ownership/cli.rb | 68 +-- .../private/file_path_finder.rb | 36 +- .../private/file_path_team_cache.rb | 8 +- .../private/for_file_output_builder.rb | 10 +- .../permit_pack_owner_top_level_key.rb | 4 +- lib/code_ownership/private/team_finder.rb | 6 +- lib/code_ownership/version.rb | 2 +- rakelib/compile.rake | 7 +- rakelib/env.rake | 9 +- rakelib/helpers.rake | 3 +- rakelib/pkg.rake | 59 +-- rakelib/spec.rake | 5 +- spec/lib/code_ownership/cli_spec.rb | 214 ++++----- .../private/file_path_finder_spec.rb | 47 +- .../private/file_path_team_cache_spec.rb | 27 +- .../permit_pack_owner_top_level_key_spec.rb | 5 +- .../private/team_finder_spec.rb | 23 +- spec/lib/code_ownership_spec.rb | 431 +++++++++--------- spec/spec_helper.rb | 23 +- spec/support/application_fixtures.rb | 55 +-- 27 files changed, 721 insertions(+), 562 deletions(-) create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 3f995f96..fec12d19 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,3 +1,17 @@ +inherit_from: .rubocop_todo.yml + +inherit_mode: + merge: + - Exclude + - Include + +inherit_gem: + rubocop-gusto: + - config/default.yml + +plugins: + - rubocop-gusto + # The behavior of RuboCop can be controlled via the .rubocop.yml # configuration file. It makes it possible to enable/disable # certain cops (checks) and to alter their behavior if they accept @@ -11,6 +25,7 @@ AllCops: NewCops: enable Exclude: + - bin/**/* - vendor/bundle/**/** - tmp/**/** - target/**/** @@ -123,3 +138,7 @@ Style/HashSyntax: Gemspec/DevelopmentDependencies: Enabled: true EnforcedStyle: gemspec + +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 00000000..3bca2e43 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,98 @@ +# This configuration was generated by +# `rubocop --auto-gen-config --exclude-limit 10000` +# on 2026-11-30 21:03:24 UTC using RuboCop version 1.93.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 8 +# This cop supports unsafe autocorrection (--autocorrect-all). +Gusto/DescribedClassConstantReference: + Exclude: + - 'spec/lib/code_ownership/cli_spec.rb' + +# Offense count: 1 +Gusto/NoRescueErrorMessageChecking: + Exclude: + - 'lib/code_ownership.rb' + +# Offense count: 12 +# This cop supports unsafe autocorrection (--autocorrect-all). +RSpec/BeEq: + Exclude: + - 'spec/lib/code_ownership/cli_spec.rb' + - 'spec/lib/code_ownership_spec.rb' + +# Offense count: 16 +# Configuration parameters: Prefixes, AllowedPatterns. +# Prefixes: when, with, without +RSpec/ContextWording: + Exclude: + - 'spec/lib/code_ownership/cli_spec.rb' + - 'spec/lib/code_ownership/private/file_path_finder_spec.rb' + - 'spec/lib/code_ownership_spec.rb' + - 'spec/support/application_fixtures.rb' + +# Offense count: 1 +RSpec/LeakyConstantDeclaration: + Exclude: + - 'spec/lib/code_ownership/private/file_path_finder_spec.rb' + +# Offense count: 2 +RSpec/RemoveConst: + Exclude: + - 'spec/support/application_fixtures.rb' + +# Offense count: 2 +RSpec/RepeatedExampleGroupDescription: + Exclude: + - 'spec/lib/code_ownership_spec.rb' + +# Offense count: 1 +# Configuration parameters: CustomTransform, IgnoreMethods, IgnoreMetadata, InflectorPath, EnforcedInflector. +# SupportedInflectors: default, active_support +RSpec/SpecFilePathFormat: + Exclude: + - 'spec/lib/code_ownership/private/permit_pack_owner_top_level_key_spec.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Rake/Desc: + Exclude: + - 'Rakefile' + +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +Sorbet/BlockMethodDefinition: + Exclude: + - 'spec/lib/code_ownership_spec.rb' + - 'spec/support/application_fixtures.rb' + +# Offense count: 9 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: SuggestedStrictness. +Sorbet/StrictSigil: + Exclude: + - 'ext/code_ownership/extconf.rb' + - 'lib/code_ownership/cli.rb' + - 'rakelib/compile.rake' + - 'rakelib/env.rake' + - 'rakelib/helpers.rake' + - 'rakelib/pkg.rake' + - 'rakelib/spec.rake' + - 'spec/spec_helper.rb' + - 'spec/support/application_fixtures.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle, Recursive. +# SupportedStyles: literals, strict +Style/MutableConstant: + Exclude: + - 'lib/code_ownership/private/for_file_output_builder.rb' + +# Offense count: 2 +Style/Send: + Exclude: + - 'spec/support/application_fixtures.rb' diff --git a/Gemfile b/Gemfile index b932afa4..ab524048 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ # frozen_string_literal: true -source 'https://rubygems.org' +source "https://rubygems.org" gemspec -gem 'rake-compiler', '~> 1.3.0' +gem "rake-compiler", "~> 1.3.0" diff --git a/Rakefile b/Rakefile index a1d237a2..69da6d11 100644 --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,7 @@ # frozen_string_literal: true -GEMSPEC = Gem::Specification.load('code_ownership.gemspec') +GEMSPEC = Gem::Specification.load("code_ownership.gemspec") -task build: 'pkg:ruby' +task build: "pkg:ruby" -task default: %w[env:dev compile spec] +task default: %w(env:dev compile spec) diff --git a/code_ownership.gemspec b/code_ownership.gemspec index 23a7f671..a8a0fb7b 100644 --- a/code_ownership.gemspec +++ b/code_ownership.gemspec @@ -1,53 +1,54 @@ # frozen_string_literal: true -require_relative 'lib/code_ownership/version' +require_relative "lib/code_ownership/version" Gem::Specification.new do |spec| - spec.name = 'code_ownership' + spec.name = "code_ownership" spec.version = CodeOwnership::VERSION - spec.authors = ['Gusto Engineers'] - spec.email = ['dev@gusto.com'] - spec.summary = 'A gem to help engineering teams declare ownership of code' - spec.description = 'A gem to help engineering teams declare ownership of code' - spec.homepage = 'https://github.com/rubyatscale/code_ownership' - spec.license = 'MIT' + spec.authors = ["Gusto Engineers"] + spec.email = ["dev@gusto.com"] + spec.summary = "A gem to help engineering teams declare ownership of code" + spec.description = "A gem to help engineering teams declare ownership of code" + spec.homepage = "https://github.com/rubyatscale/code_ownership" + spec.license = "MIT" if spec.respond_to?(:metadata) - spec.metadata['homepage_uri'] = spec.homepage - spec.metadata['source_code_uri'] = 'https://github.com/rubyatscale/code_ownership' - spec.metadata['changelog_uri'] = 'https://github.com/rubyatscale/code_ownership/releases' - spec.metadata['allowed_push_host'] = 'https://rubygems.org' - spec.metadata['cargo_crate_name'] = 'code_ownership' + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/rubyatscale/code_ownership" + spec.metadata["changelog_uri"] = "https://github.com/rubyatscale/code_ownership/releases" + spec.metadata["allowed_push_host"] = "https://rubygems.org" + spec.metadata["cargo_crate_name"] = "code_ownership" else - raise 'RubyGems 2.0 or newer is required to protect against ' \ - 'public gem pushes.' + raise "RubyGems 2.0 or newer is required to protect against " \ + "public gem pushes." end - spec.required_ruby_version = Gem::Requirement.new('>= 3.3', '< 4.1.dev') + spec.required_ruby_version = Gem::Requirement.new(">= 3.3", "< 4.1.dev") # https://guides.rubygems.org/make-your-own-gem/#adding-an-executable # and # https://bundler.io/blog/2015/03/20/moving-bins-to-exe.html - spec.executables = ['codeownership'] + spec.executables = ["codeownership"] # Specify which files should be added to the gem when it is released. - spec.files = Dir['{lib,ext}/**/*', 'LICENSE', 'README.md', 'Cargo.*'] + spec.files = Dir["{lib,ext}/**/*", "LICENSE", "README.md", "Cargo.*"] spec.files.reject! { |f| File.directory?(f) } spec.files.reject! { |f| f =~ /\.(dll|so|dylib|lib|bundle)\Z/ } - spec.require_paths = ['lib'] - spec.extensions = ['ext/code_ownership/Cargo.toml'] - - spec.add_dependency 'code_teams', '~> 1.0' - spec.add_dependency 'packs-specification' - spec.add_dependency 'sorbet-runtime', '>= 0.6.12763' - - spec.add_development_dependency 'debug' - spec.add_development_dependency 'packwerk' - spec.add_development_dependency 'railties' - spec.add_development_dependency 'rake' - spec.add_development_dependency 'rb_sys', '~> 0.9.63' - spec.add_development_dependency 'rspec', '~> 3.0' - spec.add_development_dependency 'rubocop' - spec.add_development_dependency 'sorbet' - spec.add_development_dependency 'tapioca' + spec.require_paths = ["lib"] + spec.extensions = ["ext/code_ownership/Cargo.toml"] + + spec.add_dependency "code_teams", "~> 1.0" + spec.add_dependency "packs-specification" + spec.add_dependency "sorbet-runtime", ">= 0.6.12763" + + spec.add_development_dependency "debug" + spec.add_development_dependency "packwerk" + spec.add_development_dependency "railties" + spec.add_development_dependency "rake" + spec.add_development_dependency "rb_sys", "~> 0.9.63" + spec.add_development_dependency "rspec", "~> 3.0" + spec.add_development_dependency "rubocop" + spec.add_development_dependency "rubocop-gusto" + spec.add_development_dependency "sorbet" + spec.add_development_dependency "tapioca" end diff --git a/ext/code_ownership/extconf.rb b/ext/code_ownership/extconf.rb index d15d8184..3f0e09e9 100644 --- a/ext/code_ownership/extconf.rb +++ b/ext/code_ownership/extconf.rb @@ -1,10 +1,11 @@ +# typed: false # frozen_string_literal: true -require 'mkmf' -require 'rb_sys/mkmf' +require "mkmf" +require "rb_sys/mkmf" ruby_minor = RUBY_VERSION[/\d+\.\d+/] create_rust_makefile("code_ownership/#{ruby_minor}/code_ownership") do |ext| - ext.extra_cargo_args += ['--crate-type', 'cdylib'] - ext.extra_cargo_args += ['--package', 'code_ownership'] + ext.extra_cargo_args += ["--crate-type", "cdylib"] + ext.extra_cargo_args += ["--package", "code_ownership"] end diff --git a/lib/code_ownership.rb b/lib/code_ownership.rb index 31b4614a..9a0d199e 100644 --- a/lib/code_ownership.rb +++ b/lib/code_ownership.rb @@ -1,26 +1,26 @@ -# frozen_string_literal: true # typed: strict +# frozen_string_literal: true -require 'code_teams' -require 'sorbet-runtime' -require 'json' -require 'packs-specification' -require 'code_ownership/version' -require 'code_ownership/private/file_path_finder' -require 'code_ownership/private/file_path_team_cache' -require 'code_ownership/private/team_finder' -require 'code_ownership/private/for_file_output_builder' -require 'code_ownership/cli' +require "code_teams" +require "sorbet-runtime" +require "json" +require "packs-specification" +require "code_ownership/version" +require "code_ownership/private/file_path_finder" +require "code_ownership/private/file_path_team_cache" +require "code_ownership/private/team_finder" +require "code_ownership/private/for_file_output_builder" +require "code_ownership/cli" begin RUBY_VERSION =~ /(\d+\.\d+)/ require "code_ownership/#{Regexp.last_match(1)}/code_ownership" rescue LoadError - require 'code_ownership/code_ownership' + require "code_ownership/code_ownership" end if defined?(Packwerk) - require 'code_ownership/private/permit_pack_owner_top_level_key' + require "code_ownership/private/permit_pack_owner_top_level_key" end module CodeOwnership @@ -36,8 +36,10 @@ module CodeOwnership # Returns the version of the code_ownership gem and the codeowners-rs gem. sig { returns(T::Array[String]) } def self.version - ["code_ownership version: #{VERSION}", - "codeowners-rs version: #{::RustCodeOwners.version}"] + [ + "code_ownership version: #{VERSION}", + "codeowners-rs version: #{::RustCodeOwners.version}", + ] end # Returns the owning team for a given file path. @@ -281,12 +283,12 @@ def self.remove_file_annotation!(filename) # Remove the team annotation and any trailing newlines after it team_pattern = %r{\A(?:#|//|-#) @team .*\n+} - new_content = content.sub(team_pattern, '') + new_content = content.sub(team_pattern, "") filepath.write(new_content) if new_content != content rescue ArgumentError => e # Handle invalid byte sequences gracefully - raise unless e.message.include?('invalid byte sequence') + raise unless e.message.include?("invalid byte sequence") end # Given a backtrace from either `Exception#backtrace` or `caller`, find the diff --git a/lib/code_ownership/cli.rb b/lib/code_ownership/cli.rb index 79c064d4..c5c34d44 100644 --- a/lib/code_ownership/cli.rb +++ b/lib/code_ownership/cli.rb @@ -1,25 +1,25 @@ # typed: true # frozen_string_literal: true -require 'optparse' -require 'pathname' -require 'fileutils' +require "optparse" +require "pathname" +require "fileutils" module CodeOwnership class Cli - EXECUTABLE = 'bin/codeownership' + EXECUTABLE = "bin/codeownership" def self.run!(argv) command = argv.shift - if command == 'validate' + if command == "validate" validate!(argv) - elsif command == 'for_file' + elsif command == "for_file" for_file(argv) - elsif command == 'for_team' + elsif command == "for_team" for_team(argv) - elsif command == 'version' + elsif command == "version" version - elsif [nil, 'help'].include?(command) + elsif [nil, "help"].include?(command) puts <<~USAGE Usage: #{EXECUTABLE} @@ -40,19 +40,19 @@ def self.validate!(argv) parser = OptionParser.new do |opts| opts.banner = "Usage: #{EXECUTABLE} validate [options] [files...]" - opts.on('--skip-autocorrect', 'Skip automatically correcting any errors, such as the .github/CODEOWNERS file') do + opts.on("--skip-autocorrect", "Skip automatically correcting any errors, such as the .github/CODEOWNERS file") do options[:skip_autocorrect] = true end - opts.on('-d', '--diff', 'Only run validations with staged files') do + opts.on("-d", "--diff", "Only run validations with staged files") do options[:diff] = true end - opts.on('-s', '--skip-stage', 'Skips staging the CODEOWNERS file') do + opts.on("-s", "--skip-stage", "Skips staging the CODEOWNERS file") do options[:skip_stage] = true end - opts.on('--help', 'Shows this prompt') do + opts.on("--help", "Shows this prompt") do puts opts exit end @@ -61,23 +61,23 @@ def self.validate!(argv) parser.parse!(args) # Collect any remaining arguments as file paths - specified_files = argv.reject { |arg| arg.start_with?('--') } + specified_files = argv.reject { |arg| arg.start_with?("--") } files = if !specified_files.empty? - # Files explicitly provided on command line - if options[:diff] - warn 'Warning: Ignoring --diff flag because explicit files were provided' - end - specified_files.select { |file| File.exist?(file) } - elsif options[:diff] - # Staged files from git - ENV.fetch('CODEOWNERS_GIT_STAGED_FILES') { `git diff --staged --name-only` }.split("\n").select do |file| - File.exist?(file) - end - else - # No files specified, validate all - nil - end + # Files explicitly provided on command line + if options[:diff] + warn "Warning: Ignoring --diff flag because explicit files were provided" + end + specified_files.select { |file| File.exist?(file) } + elsif options[:diff] + # Staged files from git + ENV.fetch("CODEOWNERS_GIT_STAGED_FILES") { %x(git diff --staged --name-only) }.split("\n").select do |file| + File.exist?(file) + end + else + # No files specified, validate all + nil + end CodeOwnership.validate!( files: files, @@ -98,20 +98,20 @@ def self.for_file(argv) # Long-term, we probably want to use something like `thor` so we don't have to implement logic # like this. In the short-term, this is a simple way for us to use the built-in OptionParser # while having an ergonomic CLI. - files = argv.reject { |arg| arg.start_with?('--') } + files = argv.reject { |arg| arg.start_with?("--") } parser = OptionParser.new do |opts| opts.banner = "Usage: #{EXECUTABLE} for_file [options]" - opts.on('--json', 'Output as JSON') do + opts.on("--json", "Output as JSON") do options[:json] = true end - opts.on('--verbose', 'Output verbose information') do + opts.on("--verbose", "Output verbose information") do options[:verbose] = true end - opts.on('--help', 'Shows this prompt') do + opts.on("--help", "Shows this prompt") do puts opts exit end @@ -130,12 +130,12 @@ def self.for_team(argv) parser = OptionParser.new do |opts| opts.banner = "Usage: #{EXECUTABLE} for_team 'Team Name'" - opts.on('--help', 'Shows this prompt') do + opts.on("--help", "Shows this prompt") do puts opts exit end end - teams = argv.reject { |arg| arg.start_with?('--') } + teams = argv.reject { |arg| arg.start_with?("--") } args = parser.order!(argv) parser.parse!(args) diff --git a/lib/code_ownership/private/file_path_finder.rb b/lib/code_ownership/private/file_path_finder.rb index e14523f4..4911fede 100644 --- a/lib/code_ownership/private/file_path_finder.rb +++ b/lib/code_ownership/private/file_path_finder.rb @@ -1,5 +1,5 @@ -# frozen_string_literal: true # typed: strict +# frozen_string_literal: true module CodeOwnership module Private @@ -45,23 +45,23 @@ def self.from_backtrace(backtrace) # # ./app/controllers/some_controller.rb:43:in `block (3 levels) in create' # - backtrace_line = if RUBY_VERSION >= '3.4.0' - %r{\A(#{pwd}/|\./)? - (?.+) # Matches 'app/controllers/some_controller.rb' - : - (?\d+) # Matches '43' - :in\s - '(?.*)' # Matches "`block (3 levels) in create'" - \z}x - else - %r{\A(#{pwd}/|\./)? - (?.+) # Matches 'app/controllers/some_controller.rb' - : - (?\d+) # Matches '43' - :in\s - `(?.*)' # Matches "`block (3 levels) in create'" - \z}x - end + backtrace_line = if RUBY_VERSION >= "3.4.0" + %r{\A(#{pwd}/|\./)? + (?.+) # Matches 'app/controllers/some_controller.rb' + : + (?\d+) # Matches '43' + :in\s + '(?.*)' # Matches "`block (3 levels) in create'" + \z}x + else + %r{\A(#{pwd}/|\./)? + (?.+) # Matches 'app/controllers/some_controller.rb' + : + (?\d+) # Matches '43' + :in\s + `(?.*)' # Matches "`block (3 levels) in create'" + \z}x + end backtrace.lazy.filter_map do |line| match = line.match(backtrace_line) diff --git a/lib/code_ownership/private/file_path_team_cache.rb b/lib/code_ownership/private/file_path_team_cache.rb index dfe207dc..db627721 100644 --- a/lib/code_ownership/private/file_path_team_cache.rb +++ b/lib/code_ownership/private/file_path_team_cache.rb @@ -1,5 +1,5 @@ -# frozen_string_literal: true # typed: strict +# frozen_string_literal: true module CodeOwnership module Private @@ -28,8 +28,10 @@ def self.bust_cache! sig { returns(T::Hash[String, T.nilable(CodeTeams::Team)]) } def self.cache - @cache ||= T.let(@cache, - T.nilable(T::Hash[String, T.nilable(CodeTeams::Team)])) + @cache ||= T.let( + @cache, + T.nilable(T::Hash[String, T.nilable(CodeTeams::Team)]) + ) @cache ||= {} end end diff --git a/lib/code_ownership/private/for_file_output_builder.rb b/lib/code_ownership/private/for_file_output_builder.rb index a8edb63f..a7ea715d 100644 --- a/lib/code_ownership/private/for_file_output_builder.rb +++ b/lib/code_ownership/private/for_file_output_builder.rb @@ -1,5 +1,5 @@ -# frozen_string_literal: true # typed: strict +# frozen_string_literal: true module CodeOwnership module Private @@ -22,8 +22,8 @@ def self.build(file_path:, json:, verbose:) UNOWNED_OUTPUT = T.let( { - team_name: 'Unowned', - team_yml: 'Unowned' + team_name: "Unowned", + team_yml: "Unowned", }, T::Hash[Symbol, T.untyped] ) @@ -47,7 +47,7 @@ def build_verbose { team_name: result[:team_name], team_yml: result[:team_config_yml], - description: result[:reasons] + description: result[:reasons], } end @@ -60,7 +60,7 @@ def build_terse else { team_name: team.name, - team_yml: team.config_yml + team_yml: team.config_yml, } end end diff --git a/lib/code_ownership/private/permit_pack_owner_top_level_key.rb b/lib/code_ownership/private/permit_pack_owner_top_level_key.rb index c5b7b895..5a76cf23 100644 --- a/lib/code_ownership/private/permit_pack_owner_top_level_key.rb +++ b/lib/code_ownership/private/permit_pack_owner_top_level_key.rb @@ -1,7 +1,7 @@ # typed: strict # frozen_string_literal: true -require 'packwerk' +require "packwerk" module CodeOwnership module Private @@ -16,7 +16,7 @@ def call(package_set, configuration) sig { override.returns(T::Array[String]) } def permitted_keys - %w[owner] + %w(owner) end end end diff --git a/lib/code_ownership/private/team_finder.rb b/lib/code_ownership/private/team_finder.rb index 3a035f11..39c3287d 100644 --- a/lib/code_ownership/private/team_finder.rb +++ b/lib/code_ownership/private/team_finder.rb @@ -1,5 +1,5 @@ -# frozen_string_literal: true # typed: strict +# frozen_string_literal: true module CodeOwnership module Private @@ -8,7 +8,7 @@ module TeamFinder sig { params(file_path: String, allow_raise: T::Boolean).returns(T.nilable(CodeTeams::Team)) } def self.for_file(file_path, allow_raise: false) - return nil if file_path.start_with?('./') + return nil if file_path.start_with?("./") return FilePathTeamCache.get(file_path) if FilePathTeamCache.cached?(file_path) @@ -60,7 +60,7 @@ def self.for_class(klass) sig { params(package: Packs::Pack).returns(T.nilable(::CodeTeams::Team)) } def self.for_package(package) - owner_name = package.raw_hash['owner'] || package.metadata['owner'] + owner_name = package.raw_hash["owner"] || package.metadata["owner"] return nil if owner_name.nil? find_team!(owner_name, allow_raise: true) diff --git a/lib/code_ownership/version.rb b/lib/code_ownership/version.rb index 4deded73..4dc50e4e 100644 --- a/lib/code_ownership/version.rb +++ b/lib/code_ownership/version.rb @@ -2,5 +2,5 @@ # frozen_string_literal: true module CodeOwnership - VERSION = '2.2.1' + VERSION = "2.2.1" end diff --git a/rakelib/compile.rake b/rakelib/compile.rake index e5ea612e..1831cf1d 100644 --- a/rakelib/compile.rake +++ b/rakelib/compile.rake @@ -1,7 +1,8 @@ +# typed: false # frozen_string_literal: true -require 'rb_sys/extensiontask' +require "rb_sys/extensiontask" -RbSys::ExtensionTask.new('code_ownership', GEMSPEC) do |ext| - ext.lib_dir = 'lib/code_ownership' +RbSys::ExtensionTask.new("code_ownership", GEMSPEC) do |ext| + ext.lib_dir = "lib/code_ownership" end diff --git a/rakelib/env.rake b/rakelib/env.rake index fe30728e..24defed3 100644 --- a/rakelib/env.rake +++ b/rakelib/env.rake @@ -1,15 +1,16 @@ +# typed: false # frozen_string_literal: true namespace :env do desc 'Sets up environment variables "dev" builds' task :dev do - ENV['RUST_BACKTRACE'] = '1' - ENV['WASMTIME_BACKTRACE_DETAILS'] = '1' - ENV['RB_SYS_CARGO_PROFILE'] ||= 'dev' + ENV["RUST_BACKTRACE"] = "1" + ENV["WASMTIME_BACKTRACE_DETAILS"] = "1" + ENV["RB_SYS_CARGO_PROFILE"] ||= "dev" end desc 'Sets up environment variables "release" builds' task :release do - ENV['RB_SYS_CARGO_PROFILE'] = 'release' + ENV["RB_SYS_CARGO_PROFILE"] = "release" end end diff --git a/rakelib/helpers.rake b/rakelib/helpers.rake index ca4e3d8a..7756f7b2 100644 --- a/rakelib/helpers.rake +++ b/rakelib/helpers.rake @@ -1,3 +1,4 @@ +# typed: false # frozen_string_literal: true REPO_FILES = Rake::FileList.new @@ -15,7 +16,7 @@ def filesize(*files) end def repo_files - REPO_FILES.include(`git ls-files`.split("\n")) if REPO_FILES.empty? + REPO_FILES.include(%x(git ls-files).split("\n")) if REPO_FILES.empty? REPO_FILES end diff --git a/rakelib/pkg.rake b/rakelib/pkg.rake index 6d77abbf..d547c45c 100644 --- a/rakelib/pkg.rake +++ b/rakelib/pkg.rake @@ -1,32 +1,33 @@ +# typed: false # frozen_string_literal: true -CLOBBER.include('pkg/**/*.gem') -CLEAN.include('tmp/pkg') -CLEAN.include('tmp/pkg') +CLOBBER.include("pkg/**/*.gem") +CLEAN.include("tmp/pkg") +CLEAN.include("tmp/pkg") def gem_install_test(dotgem) - dotgem = File.expand_path(File.join('..', dotgem), __dir__) + dotgem = File.expand_path(File.join("..", dotgem), __dir__) tmpdir = File.expand_path("../tmp/pkg-test-#{Time.now.to_i}", __dir__) sh "gem install --verbose --install-dir #{tmpdir} #{dotgem}" wrapper = if defined?(Bundler) - ->(&blk) { Bundler.with_unbundled_env { blk.call } } - else - ->(&blk) { blk.call } - end + -> (&blk) { Bundler.with_unbundled_env { blk.call } } + else + -> (&blk) { blk.call } + end - testrun = lambda do |cmd| + testrun = -> (cmd) do cmd = cmd.chomp wrapper.call do - old = ENV.fetch('GEM_HOME', nil) - ENV['GEM_HOME'] = tmpdir + old = ENV.fetch("GEM_HOME", nil) + ENV["GEM_HOME"] = tmpdir ruby "-rcode_ownership -e '(#{cmd}) || abort'" puts "✅ Passed (#{cmd})" - rescue StandardError + rescue abort "❌ Failed (#{cmd})" ensure - ENV['GEM_HOME'] = old + ENV["GEM_HOME"] = old end end @@ -42,20 +43,20 @@ def gem_install_test(dotgem) end namespace :pkg do - directory 'pkg' + directory "pkg" desc "Build the source gem (#{GEMSPEC.name}-#{GEMSPEC.version}.gem)" - task ruby: 'pkg' do + task ruby: "pkg" do slug = "#{GEMSPEC.name}-#{GEMSPEC.version}" output_gempath = File.expand_path("../pkg/#{slug}.gem", __dir__) - gemspec_path = 'code_ownership.gemspec' - base_dir = File.join('tmp/pkg', slug) - staging_dir = File.join(base_dir, 'stage') - unpacked_dir = File.join(base_dir, 'unpacked') - vendor_dir = 'ext/cargo-vendor' # this file gets cleaned up during gem install + gemspec_path = "code_ownership.gemspec" + base_dir = File.join("tmp/pkg", slug) + staging_dir = File.join(base_dir, "stage") + unpacked_dir = File.join(base_dir, "unpacked") + vendor_dir = "ext/cargo-vendor" # this file gets cleaned up during gem install staging_gem_path = File.join(staging_dir, "#{slug}.gem") - puts 'Building source gem...' + puts "Building source gem..." rm(output_gempath) if File.exist?(output_gempath) rm_rf(staging_dir) @@ -70,20 +71,20 @@ namespace :pkg do end Dir.chdir(staging_dir) do - cargo_config_path = '.cargo/config' + cargo_config_path = ".cargo/config" final_gemspec = Gem::Specification.load(File.basename(gemspec_path)) puts "Vendoring cargo dependencies to #{cargo_config_path}..." - mkdir_p '.cargo' + mkdir_p ".cargo" sh "cargo vendor --versioned-dirs --locked #{vendor_dir} >> #{cargo_config_path} 2>/dev/null" vendor_files = dirglob("./#{vendor_dir}/**/*").reject { |f| File.directory?(f) } # Ensure that all vendor files have the right read permissions, # which are needed to build the gem. # The permissions that we want _at least_ is readable by all for example `.rw-r--r--` - vendor_files.each { |f| FileUtils.chmod('a+r', f) } + vendor_files.each { |f| FileUtils.chmod("a+r", f) } final_gemspec.files += vendor_files - final_gemspec.files += dirglob('**/.cargo/**/*').reject { |f| File.directory?(f) } + final_gemspec.files += dirglob("**/.cargo/**/*").reject { |f| File.directory?(f) } puts "Building gem to #{unpacked_dir}.gem..." Gem::Package.build(final_gemspec, true, false, "#{slug}.gem") @@ -93,7 +94,7 @@ namespace :pkg do sh "gem unpack #{staging_gem_path} --target #{File.dirname(unpacked_dir)} --quiet" mv File.join(base_dir, slug), unpacked_dir - puts 'Verifying cargo dependencies are vendored...' + puts "Verifying cargo dependencies are vendored..." sh "cargo verify-project --manifest-path #{File.join(unpacked_dir, 'Cargo.toml')}" cp staging_gem_path, output_gempath @@ -108,12 +109,12 @@ namespace :pkg do STATS end - desc 'Test source gem installation' - task 'ruby:test' => 'pkg:ruby' do + desc "Test source gem installation" + task "ruby:test" => "pkg:ruby" do gem_install_test("pkg/#{GEMSPEC.name}-#{GEMSPEC.version}.gem") end - %w[x86_64-darwin arm64-darwin x86_64-linux].each do |platform| + %w(x86_64-darwin arm64-darwin x86_64-linux).each do |platform| desc "Test #{platform} gem installation" task "#{platform}:test" do gem_install_test("pkg/#{GEMSPEC.name}-#{GEMSPEC.version}-#{platform}.gem") diff --git a/rakelib/spec.rake b/rakelib/spec.rake index 737e97b1..5ddbbdb3 100644 --- a/rakelib/spec.rake +++ b/rakelib/spec.rake @@ -1,9 +1,10 @@ +# typed: false # frozen_string_literal: true -CLEAN.include('.rspec_status') +CLEAN.include(".rspec_status") begin - require 'rspec/core/rake_task' + require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) rescue LoadError diff --git a/spec/lib/code_ownership/cli_spec.rb b/spec/lib/code_ownership/cli_spec.rb index 3fc6afde..ca77f4e4 100644 --- a/spec/lib/code_ownership/cli_spec.rb +++ b/spec/lib/code_ownership/cli_spec.rb @@ -1,20 +1,21 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership::Cli do subject { CodeOwnership::Cli.run!(argv) } - describe 'validate' do - let(:argv) { ['validate'] } + describe "validate" do + let(:argv) { ["validate"] } let(:owned_globs) { nil } before do write_configuration(owned_globs: owned_globs) - write_file('app/services/my_file.rb') - write_file('frontend/javascripts/my_file.jsx') + write_file("app/services/my_file.rb") + write_file("frontend/javascripts/my_file.jsx") end - context 'when run without arguments' do - it 'runs validations with the right defaults' do + context "when run without arguments" do + it "runs validations with the right defaults" do expect(CodeOwnership).to receive(:validate!) do |args| expect(args[:autocorrect]).to eq true expect(args[:stage_changes]).to eq true @@ -23,15 +24,15 @@ subject end - context 'with errors' do - it 'with errors' do + context "with errors" do + it "with errors" do expect { subject }.to raise_error(StandardError, /Some files are missing ownership/) end end - context 'without errors' do + context "without errors" do before do - write_file('config/teams/my_team.yml', <<~YML) + write_file("config/teams/my_team.yml", <<~YML) name: My Team github: team: '@my-team' @@ -40,31 +41,32 @@ - frontend/**/*.jsx YML end - it 'has empty output' do + + it "has empty output" do expect(CodeOwnership::Cli).to_not receive(:puts) subject end end end - context 'with explicit file arguments' do - let(:argv) { ['validate', 'app/services/my_file.rb', 'frontend/javascripts/my_file.jsx'] } + context "with explicit file arguments" do + let(:argv) { ["validate", "app/services/my_file.rb", "frontend/javascripts/my_file.jsx"] } - it 'validates only the specified files' do + it "validates only the specified files" do expect(CodeOwnership).to receive(:validate!) do |args| - expect(args[:files]).to match_array(['app/services/my_file.rb', 'frontend/javascripts/my_file.jsx']) + expect(args[:files]).to match_array(["app/services/my_file.rb", "frontend/javascripts/my_file.jsx"]) expect(args[:autocorrect]).to eq true expect(args[:stage_changes]).to eq true end subject end - context 'with options' do - let(:argv) { ['validate', '--skip-autocorrect', '--skip-stage', 'app/services/my_file.rb'] } + context "with options" do + let(:argv) { ["validate", "--skip-autocorrect", "--skip-stage", "app/services/my_file.rb"] } - it 'passes the options correctly' do + it "passes the options correctly" do expect(CodeOwnership).to receive(:validate!) do |args| - expect(args[:files]).to eq(['app/services/my_file.rb']) + expect(args[:files]).to eq(["app/services/my_file.rb"]) expect(args[:autocorrect]).to eq false expect(args[:stage_changes]).to eq false end @@ -72,44 +74,44 @@ end end - context 'when combined with --diff flag' do - let(:argv) { ['validate', '--diff', 'app/services/my_file.rb'] } + context "when combined with --diff flag" do + let(:argv) { ["validate", "--diff", "app/services/my_file.rb"] } before do allow(ENV).to receive(:fetch).and_call_original - allow(ENV).to receive(:fetch).with('CODEOWNERS_GIT_STAGED_FILES').and_return('other_file.rb') + allow(ENV).to receive(:fetch).with("CODEOWNERS_GIT_STAGED_FILES").and_return("other_file.rb") end - it 'prioritizes explicit files over git diff' do + it "prioritizes explicit files over git diff" do expect(CodeOwnership).to receive(:validate!) do |args| - expect(args[:files]).to eq(['app/services/my_file.rb']) + expect(args[:files]).to eq(["app/services/my_file.rb"]) end subject end end end - context 'with --diff argument' do - let(:argv) { ['validate', '--diff'] } + context "with --diff argument" do + let(:argv) { ["validate", "--diff"] } before do allow(ENV).to receive(:fetch).and_call_original - allow(ENV).to receive(:fetch).with('CODEOWNERS_GIT_STAGED_FILES').and_return('app/services/my_file.rb') + allow(ENV).to receive(:fetch).with("CODEOWNERS_GIT_STAGED_FILES").and_return("app/services/my_file.rb") end - context 'when there are multiple owned_globs' do - let(:owned_globs) { ['app/*/**', 'lib/*/**'] } + context "when there are multiple owned_globs" do + let(:owned_globs) { ["app/*/**", "lib/*/**"] } - it 'validates the tracked file' do + it "validates the tracked file" do expect { subject }.to raise_error StandardError end end end - context 'with --skip-autocorrect' do - let(:argv) { ['validate', '--skip-autocorrect'] } + context "with --skip-autocorrect" do + let(:argv) { ["validate", "--skip-autocorrect"] } - it 'passes autocorrect: false' do + it "passes autocorrect: false" do expect(CodeOwnership).to receive(:validate!) do |args| expect(args[:autocorrect]).to eq false expect(args[:stage_changes]).to eq true @@ -118,10 +120,10 @@ end end - context 'with --skip-stage' do - let(:argv) { ['validate', '--skip-stage'] } + context "with --skip-stage" do + let(:argv) { ["validate", "--skip-stage"] } - it 'passes stage_changes: false' do + it "passes stage_changes: false" do expect(CodeOwnership).to receive(:validate!) do |args| expect(args[:autocorrect]).to eq true expect(args[:stage_changes]).to eq false @@ -130,10 +132,10 @@ end end - context 'with --help' do - let(:argv) { ['validate', '--help'] } + context "with --help" do + let(:argv) { ["validate", "--help"] } - it 'shows help and exits' do + it "shows help and exits" do expect(CodeOwnership).not_to receive(:validate!) expect(CodeOwnership::Cli).to receive(:puts).at_least(:once) expect { subject }.to raise_error(SystemExit) @@ -141,11 +143,11 @@ end end - context 'for_team' do + context "for_team" do before do write_configuration(owned_globs: nil) - write_file('app/services/my_file.rb') - write_file('config/teams/my_team.yml', <<~YML) + write_file("app/services/my_file.rb") + write_file("config/teams/my_team.yml", <<~YML) name: My Team github: team: '@my-team' @@ -154,51 +156,52 @@ - frontend/**/*.jsx YML end - let(:argv) { ['for_team', 'My Team'] } - it 'outputs the team info in human readable format' do - expect(CodeOwnership::Cli).to receive(:puts).with('# Code Ownership Report for `My Team` Team') + let(:argv) { ["for_team", "My Team"] } + + it "outputs the team info in human readable format" do + expect(CodeOwnership::Cli).to receive(:puts).with("# Code Ownership Report for `My Team` Team") subject end - context 'with no team provided' do - let(:argv) { ['for_team'] } + context "with no team provided" do + let(:argv) { ["for_team"] } - it 'raises argument error' do + it "raises argument error" do expect { subject }.to raise_error("Please pass in one team. Use `#{described_class::EXECUTABLE} for_team --help` for more info") end end - context 'with multiple teams provided' do - let(:argv) { %w[for_team A B] } + context "with multiple teams provided" do + let(:argv) { %w(for_team A B) } - it 'raises argument error' do + it "raises argument error" do expect { subject }.to raise_error("Please pass in one team. Use `#{described_class::EXECUTABLE} for_team --help` for more info") end end - context 'with --help' do - let(:argv) { ['for_team', '--help'] } + context "with --help" do + let(:argv) { ["for_team", "--help"] } - it 'shows help and exits' do + it "shows help and exits" do expect(CodeOwnership::Cli).to receive(:puts).at_least(:once) expect { subject }.to raise_error(SystemExit) end end end - describe 'for_file' do + describe "for_file" do before do write_configuration - write_file('app/services/my_file.rb', <<~RB) + write_file("app/services/my_file.rb", <<~RB) class MyFile def initialize @team = 'My Team' end end RB - write_file('config/teams/my_team.yml', <<~YML) + write_file("config/teams/my_team.yml", <<~YML) name: My Team github: team: '@my-team' @@ -207,11 +210,11 @@ def initialize YML end - context 'when run with no flags' do - context 'when run with one file' do - let(:argv) { ['for_file', 'app/services/my_file.rb'] } + context "when run with no flags" do + context "when run with one file" do + let(:argv) { ["for_file", "app/services/my_file.rb"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect(CodeOwnership::Cli).to receive(:puts).with(<<~MSG) Team: My Team Team YML: config/teams/my_team.yml @@ -220,10 +223,10 @@ def initialize end end - context 'when run with --verbose' do - let(:argv) { ['for_file', 'app/services/my_file.rb', '--verbose'] } + context "when run with --verbose" do + let(:argv) { ["for_file", "app/services/my_file.rb", "--verbose"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect(CodeOwnership::Cli).to receive(:puts).with(<<~MSG) Team: My Team Team YML: config/teams/my_team.yml @@ -234,43 +237,44 @@ def initialize end end - context 'when run with no files' do - let(:argv) { ['for_file'] } + context "when run with no files" do + let(:argv) { ["for_file"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect { subject }.to raise_error "Please pass in one file. Use `#{described_class::EXECUTABLE} for_file --help` for more info" end end - context 'when run with multiple files' do - let(:argv) { ['for_file', 'app/services/my_file.rb', 'app/services/my_file2.rb'] } + context "when run with multiple files" do + let(:argv) { ["for_file", "app/services/my_file.rb", "app/services/my_file2.rb"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect { subject }.to raise_error "Please pass in one file. Use `#{described_class::EXECUTABLE} for_file --help` for more info" end end end - context 'when run with --json' do - let(:argv) { ['for_file', '--json', 'app/services/my_file.rb'] } + context "when run with --json" do + let(:argv) { ["for_file", "--json", "app/services/my_file.rb"] } - context 'when run with one file' do - it 'outputs JSONified information to the console' do + context "when run with one file" do + it "outputs JSONified information to the console" do json = { - team_name: 'My Team', - team_yml: 'config/teams/my_team.yml' + team_name: "My Team", + team_yml: "config/teams/my_team.yml", } expect(CodeOwnership::Cli).to receive(:puts).with(json.to_json) subject end - context 'when run with --verbose' do - let(:argv) { ['for_file', '--json', '--verbose', 'app/services/my_file.rb'] } - it 'outputs JSONified information to the console' do + context "when run with --verbose" do + let(:argv) { ["for_file", "--json", "--verbose", "app/services/my_file.rb"] } + + it "outputs JSONified information to the console" do json = { - team_name: 'My Team', - team_yml: 'config/teams/my_team.yml', - description: ['Owner specified in Team YML as an owned_glob `app/**/*.rb`'] + team_name: "My Team", + team_yml: "config/teams/my_team.yml", + description: ["Owner specified in Team YML as an owned_glob `app/**/*.rb`"], } expect(CodeOwnership::Cli).to receive(:puts).with(json.to_json) subject @@ -278,27 +282,27 @@ def initialize end end - context 'when run with no files' do - let(:argv) { ['for_file', '--json'] } + context "when run with no files" do + let(:argv) { ["for_file", "--json"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect { subject }.to raise_error "Please pass in one file. Use `#{described_class::EXECUTABLE} for_file --help` for more info" end end - context 'when run with multiple files' do - let(:argv) { ['for_file', 'app/services/my_file.rb', 'app/services/my_file2.rb'] } + context "when run with multiple files" do + let(:argv) { ["for_file", "app/services/my_file.rb", "app/services/my_file2.rb"] } - it 'outputs the team info in human readable format' do + it "outputs the team info in human readable format" do expect { subject }.to raise_error "Please pass in one file. Use `#{described_class::EXECUTABLE} for_file --help` for more info" end end end - context 'when file is unowned' do - let(:argv) { ['for_file', 'app/services/unowned.rb'] } + context "when file is unowned" do + let(:argv) { ["for_file", "app/services/unowned.rb"] } - it 'prints Unowned' do + it "prints Unowned" do allow(CodeOwnership).to receive(:for_file).and_return(nil) expect(CodeOwnership::Cli).to receive(:puts).with(<<~MSG) Team: Unowned @@ -307,10 +311,10 @@ def initialize subject end - context 'when run with --verbose' do - let(:argv) { ['for_file', 'app/services/unowned.rb', '--verbose'] } + context "when run with --verbose" do + let(:argv) { ["for_file", "app/services/unowned.rb", "--verbose"] } - it 'prints Unowned' do + it "prints Unowned" do allow(CodeOwnership).to receive(:for_file_verbose).and_return(nil) expect(CodeOwnership::Cli).to receive(:puts).with(<<~MSG) Team: Unowned @@ -321,38 +325,38 @@ def initialize end end - context 'with --help' do - let(:argv) { ['for_file', '--help'] } + context "with --help" do + let(:argv) { ["for_file", "--help"] } - it 'shows help and exits' do + it "shows help and exits" do expect(CodeOwnership::Cli).to receive(:puts).at_least(:once) expect { subject }.to raise_error(SystemExit) end end end - describe 'version' do - let(:argv) { ['version'] } + describe "version" do + let(:argv) { ["version"] } - it 'outputs the version' do + it "outputs the version" do expect(CodeOwnership::Cli).to receive(:puts).with(CodeOwnership.version.join("\n")) subject end end - describe 'using unknown command' do - let(:argv) { ['some_command'] } + describe "using unknown command" do + let(:argv) { ["some_command"] } - it 'outputs help text' do + it "outputs help text" do expect(CodeOwnership::Cli).to receive(:puts).with("'some_command' is not a code_ownership command. See `#{described_class::EXECUTABLE} help`.") subject end end - describe 'passing in no command' do + describe "passing in no command" do let(:argv) { [] } - it 'outputs help text' do + it "outputs help text" do expected = <<~EXPECTED Usage: #{described_class::EXECUTABLE} diff --git a/spec/lib/code_ownership/private/file_path_finder_spec.rb b/spec/lib/code_ownership/private/file_path_finder_spec.rb index bbfa020a..cd45a835 100644 --- a/spec/lib/code_ownership/private/file_path_finder_spec.rb +++ b/spec/lib/code_ownership/private/file_path_finder_spec.rb @@ -1,9 +1,10 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership::Private::FilePathFinder do class TestClass; end # rubocop:disable Lint/ConstantDefinitionInBlock, Lint/EmptyClass - describe '.path_from_klass' do + describe ".path_from_klass" do subject do described_class.path_from_klass(klass) end @@ -12,74 +13,74 @@ class TestClass; end # rubocop:disable Lint/ConstantDefinitionInBlock, Lint/Empt TestClass end - context 'when the klass is a class' do - it 'returns the path to the class' do - expect(subject).to include('spec/lib/code_ownership/private/file_path_finder_spec.rb') + context "when the klass is a class" do + it "returns the path to the class" do + expect(subject).to include("spec/lib/code_ownership/private/file_path_finder_spec.rb") end end - context 'when NameError is raised' do + context "when NameError is raised" do before do allow(Object).to receive(:const_source_location).and_raise(NameError) end - it 'returns nil' do + it "returns nil" do expect(subject).to be_nil end end - context 'when the klass is nil' do + context "when the klass is nil" do let(:klass) { nil } - it 'raises an ArgumentError' do + it "raises an ArgumentError" do expect(subject).to be_nil end end end - describe '.from_backtrace' do + describe ".from_backtrace" do subject(:files) { described_class.from_backtrace(backtrace).to_a } - context 'when backtrace is nil' do + context "when backtrace is nil" do let(:backtrace) { nil } - it 'returns an empty array' do + it "returns an empty array" do expect(files).to eq([]) end end - context 'when backtrace is empty' do + context "when backtrace is empty" do let(:backtrace) { [] } - it 'returns an empty array' do + it "returns an empty array" do expect(files).to eq([]) end end - context 'on Ruby < 3.4 backtrace format (backticks)' do + context "on Ruby < 3.4 backtrace format (backticks)" do let(:backtrace) do ["./app/models/user.rb:12:in `save'", "app/controllers/some_controller.rb:43:in `block (2 levels) in create'"] end - it 'extracts file paths' do - if RUBY_VERSION < '3.4.0' - expect(files).to include('app/models/user.rb', 'app/controllers/some_controller.rb') + it "extracts file paths" do + if RUBY_VERSION < "3.4.0" + expect(files).to include("app/models/user.rb", "app/controllers/some_controller.rb") else - skip 'Ruby version >= 3.4 uses single quote backtrace format' + skip "Ruby version >= 3.4 uses single quote backtrace format" end end end - context 'on Ruby >= 3.4 backtrace format (single quotes)' do + context "on Ruby >= 3.4 backtrace format (single quotes)" do let(:backtrace) do ["./app/models/user.rb:12:in 'save'", "app/controllers/some_controller.rb:43:in 'block (2 levels) in create'"] end - it 'extracts file paths' do - if RUBY_VERSION >= '3.4.0' - expect(files).to include('app/models/user.rb', 'app/controllers/some_controller.rb') + it "extracts file paths" do + if RUBY_VERSION >= "3.4.0" + expect(files).to include("app/models/user.rb", "app/controllers/some_controller.rb") else - skip 'Ruby version < 3.4 does not use single quote backtrace format' + skip "Ruby version < 3.4 does not use single quote backtrace format" end end end diff --git a/spec/lib/code_ownership/private/file_path_team_cache_spec.rb b/spec/lib/code_ownership/private/file_path_team_cache_spec.rb index 8775dda0..dd5d9622 100644 --- a/spec/lib/code_ownership/private/file_path_team_cache_spec.rb +++ b/spec/lib/code_ownership/private/file_path_team_cache_spec.rb @@ -1,58 +1,59 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership::Private::FilePathTeamCache do - let(:file_path) { 'app/javascript/[test]/test.js' } + let(:file_path) { "app/javascript/[test]/test.js" } let(:codes_team) { instance_double(CodeTeams::Team) } before do allow(codes_team).to receive(:is_a?).with(CodeTeams::Team).and_return(true) end - describe '.get' do + describe ".get" do subject { described_class.get(file_path) } - context 'when the file path is not in the cache' do - it 'returns nil' do + context "when the file path is not in the cache" do + it "returns nil" do expect(subject).to be_nil end end - context 'when the file path is in the cache' do + context "when the file path is in the cache" do before do described_class.set(file_path, codes_team) end - it 'returns the correct team' do + it "returns the correct team" do expect(subject).to eq codes_team end - context 'when cache is busted' do + context "when cache is busted" do before do described_class.bust_cache! end - it 'returns nil' do + it "returns nil" do expect(subject).to be_nil end end end end - describe '.cached?' do + describe ".cached?" do subject { described_class.cached?(file_path) } - context 'when the file path is not in the cache' do - it 'returns false' do + context "when the file path is not in the cache" do + it "returns false" do expect(subject).to be_falsey end end - context 'when the file path is in the cache' do + context "when the file path is in the cache" do before do described_class.set(file_path, codes_team) end - it 'returns true' do + it "returns true" do expect(subject).to be_truthy end end diff --git a/spec/lib/code_ownership/private/permit_pack_owner_top_level_key_spec.rb b/spec/lib/code_ownership/private/permit_pack_owner_top_level_key_spec.rb index f7b26cbf..e2209ef9 100644 --- a/spec/lib/code_ownership/private/permit_pack_owner_top_level_key_spec.rb +++ b/spec/lib/code_ownership/private/permit_pack_owner_top_level_key_spec.rb @@ -1,7 +1,8 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership::Private::PackOwnershipValidator do - it 'permits the owner top-level key' do - expect(described_class.new.permitted_keys).to include('owner') + it "permits the owner top-level key" do + expect(described_class.new.permitted_keys).to include("owner") end end diff --git a/spec/lib/code_ownership/private/team_finder_spec.rb b/spec/lib/code_ownership/private/team_finder_spec.rb index d3252971..349206b2 100644 --- a/spec/lib/code_ownership/private/team_finder_spec.rb +++ b/spec/lib/code_ownership/private/team_finder_spec.rb @@ -1,30 +1,31 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership::Private::TeamFinder do - describe '.for_file' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } + describe ".for_file" do + let(:file_path) { "packs/my_pack/owned_file.rb" } let(:rust_result) do - { team_name: 'Bar', team_config_yml: 'config/teams/bar.yml', reasons: [] } + { team_name: "Bar", team_config_yml: "config/teams/bar.yml", reasons: [] } end before do create_non_empty_application end - it 'caches positive results' do + it "caches positive results" do allow(RustCodeOwners).to receive(:for_file).with(file_path) .and_return(rust_result, nil) first = described_class.for_file(file_path) second = described_class.for_file(file_path) - expect(first).to eq(CodeTeams.find('Bar')) - expect(second).to eq(CodeTeams.find('Bar')) + expect(first).to eq(CodeTeams.find("Bar")) + expect(second).to eq(CodeTeams.find("Bar")) expect(CodeOwnership::Private::FilePathTeamCache.cached?(file_path)).to be true end - it 'caches nil when rust returns nil' do + it "caches nil when rust returns nil" do allow(RustCodeOwners).to receive(:for_file).with(file_path) .and_return(nil, rust_result) @@ -37,14 +38,14 @@ end end - describe '.for_backtrace' do - it 'returns nil for nil backtrace' do + describe ".for_backtrace" do + it "returns nil for nil backtrace" do expect(described_class.for_backtrace(nil)).to be_nil end end - describe '.first_owned_file_for_backtrace' do - it 'returns nil for nil backtrace' do + describe ".first_owned_file_for_backtrace" do + it "returns nil for nil backtrace" do expect(described_class.first_owned_file_for_backtrace(nil)).to be_nil end end diff --git a/spec/lib/code_ownership_spec.rb b/spec/lib/code_ownership_spec.rb index ed2b5e4f..cbab37b7 100644 --- a/spec/lib/code_ownership_spec.rb +++ b/spec/lib/code_ownership_spec.rb @@ -1,421 +1,442 @@ +# typed: false # frozen_string_literal: true RSpec.describe CodeOwnership do - it 'has a version number' do - expect(CodeOwnership::VERSION).not_to be nil + it "has a version number" do + expect(CodeOwnership::VERSION).not_to be_nil end - context 'teams_for_files_from_codeowners' do + context "teams_for_files_from_codeowners" do subject { CodeOwnership.teams_for_files_from_codeowners(files) } - let(:files) { ['app/services/my_file.rb'] } - context 'when config is not found' do - let(:files) { ['app/javascript/[test]/test.js'] } - it 'raises an error' do + let(:files) { ["app/services/my_file.rb"] } + + context "when config is not found" do + let(:files) { ["app/javascript/[test]/test.js"] } + + it "raises an error" do expect { subject }.to raise_error(RuntimeError, /Can't open config file:/) end end - context 'with non-empty application' do + context "with non-empty application" do before do create_non_empty_application # codeowners-rs is matching files against the codeowners file RustCodeOwners.generate_and_validate(nil, false) end - context 'when no ownership is found' do - let(:files) { ['app/madeup/file.rb'] } - it 'properly assigns ownership' do - expect(subject).to eq({ 'app/madeup/file.rb' => nil }) + context "when no ownership is found" do + let(:files) { ["app/madeup/file.rb"] } + + it "properly assigns ownership" do + expect(subject).to eq({ "app/madeup/file.rb" => nil }) end end - context 'when file path starts with ./' do - let(:files) { ['./app/javascript/[test]/test.js'] } - it 'properly assigns ownership' do - expect(subject).to eq({ './app/javascript/[test]/test.js' => nil }) + context "when file path starts with ./" do + let(:files) { ["./app/javascript/[test]/test.js"] } + + it "properly assigns ownership" do + expect(subject).to eq({ "./app/javascript/[test]/test.js" => nil }) end end - context 'when ownership is found' do - let(:files) { ['packs/my_pack/owned_file.rb'] } - it 'returns the correct team' do - expect(subject).to eq({ 'packs/my_pack/owned_file.rb' => CodeTeams.find('Bar') }) + context "when ownership is found" do + let(:files) { ["packs/my_pack/owned_file.rb"] } + + it "returns the correct team" do + expect(subject).to eq({ "packs/my_pack/owned_file.rb" => CodeTeams.find("Bar") }) end - context 'subsequent for_file utilizes cached team' do - let(:files) { ['packs/my_pack/owned_file.rb', 'packs/my_pack/owned_file2.rb'] } - it 'returns the correct team' do + context "subsequent for_file utilizes cached team" do + let(:files) { ["packs/my_pack/owned_file.rb", "packs/my_pack/owned_file2.rb"] } + + it "returns the correct team" do subject # caches paths -> teams allow(RustCodeOwners).to receive(:for_file) - expect(described_class.for_file('packs/my_pack/owned_file.rb')).to eq(CodeTeams.find('Bar')) + expect(described_class.for_file("packs/my_pack/owned_file.rb")).to eq(CodeTeams.find("Bar")) expect(RustCodeOwners).to_not have_received(:for_file) end end end - context 'when ownership is found but team is not found' do - let(:file_path) { ['packs/my_pack/owned_file.rb'] } + context "when ownership is found but team is not found" do + let(:file_path) { ["packs/my_pack/owned_file.rb"] } + before do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path.first => { team_name: 'Made Up Team' } }) + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path.first => { team_name: "Made Up Team" } }) end - it 'returns nil' do - expect(subject).to eq({ 'packs/my_pack/owned_file.rb' => nil }) + it "returns nil" do + expect(subject).to eq({ "packs/my_pack/owned_file.rb" => nil }) end end - context 'when ownership is found but team is not found and allow_raise is true' do - let(:files) { ['packs/my_pack/owned_file.rb'] } + context "when ownership is found but team is not found and allow_raise is true" do + let(:files) { ["packs/my_pack/owned_file.rb"] } + before do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ files.first => { team_name: 'Made Up Team' } }) + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ files.first => { team_name: "Made Up Team" } }) end - it 'raises an error' do + it "raises an error" do expect { CodeOwnership.teams_for_files_from_codeowners(files, allow_raise: true) }.to raise_error(StandardError, /Could not find team with name:/) end end end end - describe '.for_file_from_codeowners' do + describe ".for_file_from_codeowners" do subject { CodeOwnership.for_file(file_path, from_codeowners: true) } - context 'when config is not found' do - let(:file_path) { 'app/javascript/[test]/test.js' } - it 'raises an error' do + context "when config is not found" do + let(:file_path) { "app/javascript/[test]/test.js" } + + it "raises an error" do expect { subject }.to raise_error(RuntimeError, /Can't open config file:/) end end - context 'with non-empty application' do + context "with non-empty application" do before do create_non_empty_application # codeowners-rs is matching files against the codeowners file RustCodeOwners.generate_and_validate(nil, false) end - context 'when no ownership is found' do - let(:file_path) { 'app/madeup/file.rb' } - it 'properly assigns ownership' do + context "when no ownership is found" do + let(:file_path) { "app/madeup/file.rb" } + + it "properly assigns ownership" do expect(subject).to be_nil end end - context 'when file path starts with ./' do - let(:file_path) { './app/javascript/[test]/test.js' } - it 'properly assigns ownership' do + context "when file path starts with ./" do + let(:file_path) { "./app/javascript/[test]/test.js" } + + it "properly assigns ownership" do expect(subject).to be_nil end end - context 'when ownership is found' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + context "when ownership is found" do + let(:file_path) { "packs/my_pack/owned_file.rb" } + + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") end - context 'subsequent for_file utilizes cached team' do - it 'returns the correct team' do + context "subsequent for_file utilizes cached team" do + it "returns the correct team" do subject # caches path -> team allow(RustCodeOwners).to receive(:for_file) - expect(described_class.for_file(file_path)).to eq(CodeTeams.find('Bar')) + expect(described_class.for_file(file_path)).to eq(CodeTeams.find("Bar")) expect(RustCodeOwners).to_not have_received(:for_file) end end end - context 'when ownership is found but team is not found' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } + context "when ownership is found but team is not found" do + let(:file_path) { "packs/my_pack/owned_file.rb" } + before do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: 'Made Up Team' } }) + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: "Made Up Team" } }) end - it 'returns nil' do + it "returns nil" do expect(subject).to be_nil end end - context 'when ownership is found but team is not found and allow_raise is true' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } + context "when ownership is found but team is not found and allow_raise is true" do + let(:file_path) { "packs/my_pack/owned_file.rb" } + before do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: 'Made Up Team' } }) + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: "Made Up Team" } }) end - it 'raises an error' do + it "raises an error" do expect { CodeOwnership.for_file(file_path, from_codeowners: true, allow_raise: true) }.to raise_error(StandardError, /Could not find team with name:/) end end end end - describe '.for_file' do + describe ".for_file" do subject { CodeOwnership.for_file(file_path) } - context 'when config is not found' do - let(:file_path) { 'app/javascript/[test]/test.js' } - it 'raises an error' do + + context "when config is not found" do + let(:file_path) { "app/javascript/[test]/test.js" } + + it "raises an error" do expect { subject }.to raise_error(RuntimeError, /Can't open config file:/) end end - context 'with non-empty application' do + context "with non-empty application" do before do create_non_empty_application # codeowners-rs is matching files against the codeowners file for default path RustCodeOwners.generate_and_validate(nil, false) end - context 'when no ownership is found' do - let(:file_path) { 'app/madeup/file.rb' } - it 'properly assigns ownership' do + context "when no ownership is found" do + let(:file_path) { "app/madeup/file.rb" } + + it "properly assigns ownership" do expect(subject).to be_nil end end - context 'when file path starts with ./' do - let(:file_path) { './app/javascript/[test]/test.js' } - it 'properly assigns ownership' do + context "when file path starts with ./" do + let(:file_path) { "./app/javascript/[test]/test.js" } + + it "properly assigns ownership" do expect(subject).to be_nil end end - context 'when ownership is found' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + context "when ownership is found" do + let(:file_path) { "packs/my_pack/owned_file.rb" } + + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") end - context 'when ownership is cached' do - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + context "when ownership is cached" do + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") allow(RustCodeOwners).to receive(:teams_for_files) - expect(CodeOwnership.for_file(file_path)).to eq CodeTeams.find('Bar') + expect(CodeOwnership.for_file(file_path)).to eq CodeTeams.find("Bar") expect(RustCodeOwners).not_to have_received(:teams_for_files) end end end - context 'when ownership is found but team is not found' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } + context "when ownership is found but team is not found" do + let(:file_path) { "packs/my_pack/owned_file.rb" } + before do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: 'Made Up Team' } }) + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: "Made Up Team" } }) end - it 'returns nil by default' do + it "returns nil by default" do expect(subject).to be_nil end end - context 'when ownership is found but team is not found and allow_raise is true' do - let(:file_path) { 'packs/my_pack/owned_file.rb' } + context "when ownership is found but team is not found and allow_raise is true" do + let(:file_path) { "packs/my_pack/owned_file.rb" } - it 'raises an error when using from_codeowners path' do - allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: 'Made Up Team' } }) + it "raises an error when using from_codeowners path" do + allow(RustCodeOwners).to receive(:teams_for_files).and_return({ file_path => { team_name: "Made Up Team" } }) expect { CodeOwnership.for_file(file_path, allow_raise: true) }.to raise_error(StandardError, /Could not find team with name:/) end - it 'raises an error when using single-file path' do + it "raises an error when using single-file path" do allow(RustCodeOwners).to receive(:for_file) - .and_return({ team_name: 'Made Up Team', team_config_yml: 'config/teams/made_up_team.yml', reasons: [] }) + .and_return({ team_name: "Made Up Team", team_config_yml: "config/teams/made_up_team.yml", reasons: [] }) expect { CodeOwnership.for_file(file_path, from_codeowners: false, allow_raise: true) }.to raise_error(StandardError, /Could not find team with name:/) end end end end - describe '.for_file with from_codeowners: false and package ownership' do + describe ".for_file with from_codeowners: false and package ownership" do subject { CodeOwnership.for_file(file_path, from_codeowners: false) } - let(:file_path) { 'packs/outer/inner/file.rb' } + let(:file_path) { "packs/outer/inner/file.rb" } before do create_non_empty_application - write_file('packs/outer/package.yml', "owner: Foo\n") + write_file("packs/outer/package.yml", "owner: Foo\n") write_file(file_path) end - context 'when the package sets metadata.owner' do - before { write_file('packs/outer/inner/package.yml', { 'metadata' => { 'owner' => 'Bar' } }.to_yaml) } + context "when the package sets metadata.owner" do + before { write_file("packs/outer/inner/package.yml", { "metadata" => { "owner" => "Bar" } }.to_yaml) } - it 'returns the metadata owner' do - expect(subject).to eq CodeTeams.find('Bar') + it "returns the metadata owner" do + expect(subject).to eq CodeTeams.find("Bar") end end - context 'when the package sets conflicting owners' do - before { write_file('packs/outer/inner/package.yml', { 'owner' => 'Foo', 'metadata' => { 'owner' => 'Bar' } }.to_yaml) } + context "when the package sets conflicting owners" do + before { write_file("packs/outer/inner/package.yml", { "owner" => "Foo", "metadata" => { "owner" => "Bar" } }.to_yaml) } - it 'does not fall through to the enclosing package' do + it "does not fall through to the enclosing package" do expect(subject).to be_nil end end end - describe '.for_class' do + describe ".for_class" do subject { described_class.for_class(klass) } let(:klass) do described_class end - let(:file_path) { 'packs/my_pack/owned_file.rb' } + let(:file_path) { "packs/my_pack/owned_file.rb" } before do allow(CodeOwnership::Private::FilePathFinder).to receive(:path_from_klass).and_return(file_path) end - context 'when the klass path is found' do + context "when the klass path is found" do before do create_non_empty_application end - it 'calls for_file with the correct file path' do + it "calls for_file with the correct file path" do subject expect(CodeOwnership::Private::FilePathFinder).to have_received(:path_from_klass).with(klass) end - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") end end - context 'when the klass path is not found' do + context "when the klass path is not found" do let(:file_path) { nil } - it 'returns nil' do + + it "returns nil" do expect(subject).to be_nil end end end - describe '.for_package' do + describe ".for_package" do subject { described_class.for_package(package) } - let(:package_yml_path) { 'packs/my_pack/package.yml' } + let(:package_yml_path) { "packs/my_pack/package.yml" } + let(:package) do + Packs::Pack.from(Pathname.new(package_yml_path).realpath) + end before do create_non_empty_application write_file(package_yml_path, raw_hash.to_yaml) end - let(:package) do - Packs::Pack.from(Pathname.new(package_yml_path).realpath) - end - - context 'with owner set' do - let(:raw_hash) { { 'owner' => 'Bar' } } + context "with owner set" do + let(:raw_hash) { { "owner" => "Bar" } } - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") end end - context 'with metadata owner set' do - let(:raw_hash) { { 'metadata' => { 'owner' => 'Bar' } } } + context "with metadata owner set" do + let(:raw_hash) { { "metadata" => { "owner" => "Bar" } } } - it 'returns the correct team' do - expect(subject).to eq CodeTeams.find('Bar') + it "returns the correct team" do + expect(subject).to eq CodeTeams.find("Bar") end end - context 'with no owner set' do + context "with no owner set" do let(:raw_hash) { {} } - it 'returns nil' do + it "returns nil" do expect(subject).to be_nil end end - context 'with unknown owner' do - let(:raw_hash) { { 'owner' => 'Does Not Exist' } } + context "with unknown owner" do + let(:raw_hash) { { "owner" => "Does Not Exist" } } - it 'raises helpful error' do + it "raises helpful error" do expect { subject }.to raise_error(StandardError, /Could not find team with name:/) end end - context 'with empty owner string' do - let(:raw_hash) { { 'owner' => '' } } + context "with empty owner string" do + let(:raw_hash) { { "owner" => "" } } - it 'raises helpful error' do + it "raises helpful error" do expect { subject }.to raise_error(StandardError, /Could not find team with name:/) end end end - describe '.for_backtrace' do + describe ".for_backtrace" do before do create_files_with_defined_classes write_configuration end - context 'excluded_teams is not passed in as an input parameter' do - it 'finds the right team' do + context "excluded_teams is not passed in as an input parameter" do + it "finds the right team" do expect { MyFile.raise_error }.to raise_error do |ex| - expect(described_class.for_backtrace(ex.backtrace)).to eq CodeTeams.find('Bar') + expect(described_class.for_backtrace(ex.backtrace)).to eq CodeTeams.find("Bar") end end end - context 'excluded_teams is passed in as an input parameter' do - it 'ignores the first part of the stack trace and finds the next viable owner' do + context "excluded_teams is passed in as an input parameter" do + it "ignores the first part of the stack trace and finds the next viable owner" do expect { MyFile.raise_error }.to raise_error do |ex| - team_to_exclude = CodeTeams.find('Bar') - expect(described_class.for_backtrace(ex.backtrace, excluded_teams: [team_to_exclude])).to eq CodeTeams.find('Foo') + team_to_exclude = CodeTeams.find("Bar") + expect(described_class.for_backtrace(ex.backtrace, excluded_teams: [team_to_exclude])).to eq CodeTeams.find("Foo") end end end - context 'with nil backtrace' do - it 'returns nil' do + context "with nil backtrace" do + it "returns nil" do expect(described_class.for_backtrace(nil)).to be_nil end end end - describe '.first_owned_file_for_backtrace' do + describe ".first_owned_file_for_backtrace" do before do write_configuration create_files_with_defined_classes end - context 'excluded_teams is not passed in as an input parameter' do - it 'finds the right team' do + context "excluded_teams is not passed in as an input parameter" do + it "finds the right team" do expect { MyFile.raise_error }.to raise_error do |ex| - expect(described_class.first_owned_file_for_backtrace(ex.backtrace)).to eq [CodeTeams.find('Bar'), 'app/my_error.rb'] + expect(described_class.first_owned_file_for_backtrace(ex.backtrace)).to eq [CodeTeams.find("Bar"), "app/my_error.rb"] end end end - context 'excluded_teams is not passed in as an input parameter' do - it 'finds the right team' do + context "excluded_teams is not passed in as an input parameter" do + it "finds the right team" do expect { MyFile.raise_error }.to raise_error do |ex| - team_to_exclude = CodeTeams.find('Bar') - expect(described_class.first_owned_file_for_backtrace(ex.backtrace, excluded_teams: [team_to_exclude])).to eq [CodeTeams.find('Foo'), 'app/my_file.rb'] + team_to_exclude = CodeTeams.find("Bar") + expect(described_class.first_owned_file_for_backtrace(ex.backtrace, excluded_teams: [team_to_exclude])).to eq [CodeTeams.find("Foo"), "app/my_file.rb"] end end end - context 'when nothing is owned' do - it 'returns nil' do - expect { raise 'bang!' }.to raise_error do |ex| + context "when nothing is owned" do + it "returns nil" do + expect { raise "bang!" }.to raise_error do |ex| expect(described_class.first_owned_file_for_backtrace(ex.backtrace)).to be_nil end end end - context 'with nil backtrace' do - it 'returns nil' do + context "with nil backtrace" do + it "returns nil" do expect(described_class.first_owned_file_for_backtrace(nil)).to be_nil end end end - describe '.version' do - it 'returns the version' do + describe ".version" do + it "returns the version" do expect(described_class.version).to eq ["code_ownership version: #{CodeOwnership::VERSION}", "codeowners-rs version: #{RustCodeOwners.version}"] end end - describe '.remove_file_annotation!' do + describe ".remove_file_annotation!" do subject(:remove_file_annotation) do CodeOwnership.remove_file_annotation!(filename) # Getting the owner gets stored in the cache, so after we remove the file annotation we want to bust the cache @@ -423,7 +444,7 @@ end before do - write_file('config/teams/foo.yml', <<~CONTENTS) + write_file("config/teams/foo.yml", <<~CONTENTS) name: Foo github: team: '@MyOrg/foo-team' @@ -431,8 +452,8 @@ write_configuration end - context 'ruby file has no annotation' do - let(:filename) { 'app/my_file.rb' } + context "ruby file has no annotation" do + let(:filename) { "app/my_file.rb" } before do write_file(filename, <<~CONTENTS) @@ -440,7 +461,7 @@ CONTENTS end - it 'has no effect' do + it "has no effect" do expect(File.read(filename)).to eq "# Empty file\n" remove_file_annotation @@ -449,8 +470,8 @@ end end - context 'ruby file has annotation' do - let(:filename) { 'app/my_file.rb' } + context "ruby file has annotation" do + let(:filename) { "app/my_file.rb" } before do write_file(filename, <<~CONTENTS) @@ -462,9 +483,9 @@ RustCodeOwners.generate_and_validate(nil, false) end - it 'removes the annotation' do + it "removes the annotation" do current_ownership = CodeOwnership.for_file(filename, from_codeowners: false) - expect(current_ownership&.name).to eq 'Foo' + expect(current_ownership&.name).to eq "Foo" expect(File.read(filename)).to eq <<~RUBY # @team Foo @@ -483,8 +504,8 @@ end end - context 'javascript file has annotation' do - let(:filename) { 'app/my_file.jsx' } + context "javascript file has annotation" do + let(:filename) { "app/my_file.jsx" } before do write_file(filename, <<~CONTENTS) @@ -496,9 +517,9 @@ RustCodeOwners.generate_and_validate(nil, false) end - it 'removes the annotation' do + it "removes the annotation" do current_ownership = CodeOwnership.for_file(filename, from_codeowners: false) - expect(current_ownership&.name).to eq 'Foo' + expect(current_ownership&.name).to eq "Foo" expect(File.read(filename)).to eq <<~JAVASCRIPT // @team Foo @@ -518,7 +539,7 @@ end context "haml has annotation (only verifies file is changed, the current implementation doesn't verify haml files)" do - let(:filename) { 'app/views/my_file.html.haml' } + let(:filename) { "app/views/my_file.html.haml" } before do write_file(filename, <<~CONTENTS) @@ -528,7 +549,7 @@ CONTENTS end - it 'removes the annotation' do + it "removes the annotation" do expect(File.read(filename)).to eq <<~HAML -# @team Foo @@ -545,8 +566,8 @@ end end - context 'file has new lines after the annotation' do - let(:filename) { 'app/my_file.rb' } + context "file has new lines after the annotation" do + let(:filename) { "app/my_file.rb" } before do write_file(filename, <<~CONTENTS) @@ -560,7 +581,7 @@ CONTENTS end - it 'removes the annotation and the leading new lines' do + it "removes the annotation and the leading new lines" do expect(File.read(filename)).to eq <<~RUBY # @team Foo @@ -585,113 +606,113 @@ end end - describe '.validate!' do - context 'when the CODEOWNERS file is out of date' do + describe ".validate!" do + context "when the CODEOWNERS file is out of date" do before do create_non_empty_application RustCodeOwners.generate_and_validate(nil, false) # Add a new annotated file to make the CODEOWNERS file out of date - write_file('packs/my_pack/new_file.rb', "# @team Bar\nclass NewFile; end\n") + write_file("packs/my_pack/new_file.rb", "# @team Bar\nclass NewFile; end\n") end - it 'raises an error referencing bin/codeownership validate' do + it "raises an error referencing bin/codeownership validate" do expect { CodeOwnership.validate!(autocorrect: false) }.to raise_error( RuntimeError, /Run `bin\/codeownership validate/ ) end - it 'does not reference the standalone codeowners CLI' do + it "does not reference the standalone codeowners CLI" do expect { CodeOwnership.validate!(autocorrect: false) }.to raise_error(RuntimeError) do |error| - expect(error.message).not_to include('`codeowners generate`') + expect(error.message).not_to include("`codeowners generate`") end end - it 'includes the required CODEOWNERS changes after the headline' do + it "includes the required CODEOWNERS changes after the headline" do expect { CodeOwnership.validate!(autocorrect: false) }.to raise_error(RuntimeError) do |error| expect(error.message).to match(/CODEOWNERS out of date.*The following changes are required \(- current, \+ expected\):/m) expect(error.message).to include("\n+/packs/my_pack/new_file.rb @MyOrg/bar-team") end end - it 'regenerates the CODEOWNERS file when autocorrecting' do + it "regenerates the CODEOWNERS file when autocorrecting" do expect { CodeOwnership.validate!(stage_changes: false) }.not_to raise_error - expect(codeowners_path.read).to include('/packs/my_pack/new_file.rb @MyOrg/bar-team') + expect(codeowners_path.read).to include("/packs/my_pack/new_file.rb @MyOrg/bar-team") expect { CodeOwnership.validate!(autocorrect: false) }.not_to raise_error end end - context 'when the project is a git repository' do - let(:staged_files) { `git diff --cached --name-only`.lines(chomp: true) } + context "when the project is a git repository" do + let(:staged_files) { %x(git diff --cached --name-only).lines(chomp: true) } before do create_non_empty_application - system('git', 'init', '--quiet', exception: true) + system("git", "init", "--quiet", exception: true) end - it 'stages the CODEOWNERS file by default' do + it "stages the CODEOWNERS file by default" do CodeOwnership.validate! - expect(staged_files).to eq ['.github/CODEOWNERS'] + expect(staged_files).to eq [".github/CODEOWNERS"] end - it 'does not stage the CODEOWNERS file when stage_changes is false' do + it "does not stage the CODEOWNERS file when stage_changes is false" do CodeOwnership.validate!(stage_changes: false) expect(codeowners_path).to exist expect(staged_files).to be_empty end end - ['', "# no keys yet\n", "---\n"].each do |contents| + ["", "# no keys yet\n", "---\n"].each do |contents| context "when a package.yml is #{contents.inspect}" do before do - write_configuration(owned_globs: ['packs/**/*.rb']) - write_file('config/teams/bar.yml', <<~CONTENTS) + write_configuration(owned_globs: ["packs/**/*.rb"]) + write_file("config/teams/bar.yml", <<~CONTENTS) name: Bar github: team: '@MyOrg/bar-team' CONTENTS - write_file('packs/empty_pack/package.yml', contents) - write_file('packs/empty_pack/owned_file.rb', "# @team Bar\nclass OwnedFile; end\n") + write_file("packs/empty_pack/package.yml", contents) + write_file("packs/empty_pack/owned_file.rb", "# @team Bar\nclass OwnedFile; end\n") end - it 'passes validation' do + it "passes validation" do expect { CodeOwnership.validate!(stage_changes: false) }.not_to raise_error end - it 'leaves ownership to the annotation without printing a parse error' do + it "leaves ownership to the annotation without printing a parse error" do owner = nil # for_file falls back to the annotation when package.yml fails to parse, and only prints the error. - expect { owner = CodeOwnership.for_file('packs/empty_pack/owned_file.rb', from_codeowners: false) } + expect { owner = CodeOwnership.for_file("packs/empty_pack/owned_file.rb", from_codeowners: false) } .not_to output.to_stderr_from_any_process - expect(owner).to eq CodeTeams.find('Bar') + expect(owner).to eq CodeTeams.find("Bar") end end end end - describe '.bust_caches!' do - let(:file_path) { 'app/services/thing.rb' } + describe ".bust_caches!" do + let(:file_path) { "app/services/thing.rb" } def write_team(name, owned_globs: []) - config = { 'name' => name, 'github' => { 'team' => "@MyOrg/#{name.downcase}-team" }, 'owned_globs' => owned_globs } + config = { "name" => name, "github" => { "team" => "@MyOrg/#{name.downcase}-team" }, "owned_globs" => owned_globs } write_file("config/teams/#{name.downcase}.yml", config.to_yaml) end before do write_configuration write_file(file_path) - write_team('Foo', owned_globs: ['app/services/**']) - write_team('Bar') + write_team("Foo", owned_globs: ["app/services/**"]) + write_team("Bar") end - it 'makes a team file change visible to for_file within one process' do - expect(CodeOwnership.for_file(file_path, from_codeowners: false)).to eq CodeTeams.find('Foo') + it "makes a team file change visible to for_file within one process" do + expect(CodeOwnership.for_file(file_path, from_codeowners: false)).to eq CodeTeams.find("Foo") - write_team('Foo') - write_team('Bar', owned_globs: ['app/services/**']) + write_team("Foo") + write_team("Bar", owned_globs: ["app/services/**"]) CodeOwnership.bust_caches! - expect(CodeOwnership.for_file(file_path, from_codeowners: false)).to eq CodeTeams.find('Bar') + expect(CodeOwnership.for_file(file_path, from_codeowners: false)).to eq CodeTeams.find("Bar") end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 52ae89b4..f4d9eecb 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,16 +1,17 @@ +# typed: false # frozen_string_literal: true -require 'bundler/setup' -require 'debug' -require 'packwerk' -require 'code_ownership' -require 'code_teams' -require 'packs/rspec/support' -require_relative 'support/application_fixtures' +require "bundler/setup" +require "debug" +require "packwerk" +require "code_ownership" +require "code_teams" +require "packs/rspec/support" +require_relative "support/application_fixtures" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure - config.example_status_persistence_file_path = '.rspec_status' + config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! @@ -19,12 +20,12 @@ c.syntax = :expect end - config.include_context 'application fixtures' + config.include_context "application fixtures" # Hooks and linked worktrees export variables such as GIT_DIR and GIT_INDEX_FILE, which would aim git, including # the extension's git add in validate!, at the repository running the suite instead of each example's temp project. config.before(:suite) do - `git rev-parse --local-env-vars`.split.each { |key| ENV.delete(key) } + %x(git rev-parse --local-env-vars).split.each { |key| ENV.delete(key) } end config.before do |c| @@ -40,7 +41,7 @@ example.run else begin - prefix = [File.basename($0), Process.pid].join('-') # rubocop:disable Style/SpecialGlobalVars + prefix = [File.basename($0), Process.pid].join("-") # rubocop:disable Style/SpecialGlobalVars tmpdir = Dir.mktmpdir(prefix) Dir.chdir(tmpdir) do example.run diff --git a/spec/support/application_fixtures.rb b/spec/support/application_fixtures.rb index 89fabdab..d989c94b 100644 --- a/spec/support/application_fixtures.rb +++ b/spec/support/application_fixtures.rb @@ -1,18 +1,19 @@ +# typed: false # frozen_string_literal: true -RSpec.shared_context 'application fixtures' do - let(:codeowners_path) { Pathname.pwd.join('.github/CODEOWNERS') } +RSpec.shared_context "application fixtures" do + let(:codeowners_path) { Pathname.pwd.join(".github/CODEOWNERS") } def write_configuration(owned_globs: nil, **kwargs) - owned_globs ||= ['{app,components,config,frontend,lib,packs,spec}/**/*.{rb,rake,js,jsx,ts,tsx,json,yml}'] + owned_globs ||= ["{app,components,config,frontend,lib,packs,spec}/**/*.{rb,rake,js,jsx,ts,tsx,json,yml}"] config = { - 'owned_globs' => owned_globs, - 'unowned_globs' => ['config/code_ownership.yml'] + "owned_globs" => owned_globs, + "unowned_globs" => ["config/code_ownership.yml"], }.merge(kwargs) - write_file('config/code_ownership.yml', config.to_yaml) + write_file("config/code_ownership.yml", config.to_yaml) end - def write_file(path, content = '') + def write_file(path, content = "") pathname = Pathname.pwd.join(path) FileUtils.mkdir_p(pathname.dirname) pathname.write(content) @@ -22,25 +23,25 @@ def write_file(path, content = '') let(:create_non_empty_application) do write_configuration - write_file('frontend/javascripts/packages/my_package/owned_file.jsx', <<~CONTENTS) + write_file("frontend/javascripts/packages/my_package/owned_file.jsx", <<~CONTENTS) // @team Bar CONTENTS - write_file('packs/my_pack/owned_file.rb', <<~CONTENTS) + write_file("packs/my_pack/owned_file.rb", <<~CONTENTS) # @team Bar class OwnedFile; end CONTENTS - write_file('directory/owner/.codeowner', <<~CONTENTS) + write_file("directory/owner/.codeowner", <<~CONTENTS) Bar CONTENTS - write_file('directory/owner/some_directory_file.ts') - write_file('directory/owner/(my_folder)/.codeowner', <<~CONTENTS) + write_file("directory/owner/some_directory_file.ts") + write_file("directory/owner/(my_folder)/.codeowner", <<~CONTENTS) Foo CONTENTS - write_file('directory/owner/(my_folder)/some_other_file.ts') + write_file("directory/owner/(my_folder)/some_other_file.ts") - write_file('frontend/javascripts/packages/my_other_package/package.json', <<~CONTENTS) + write_file("frontend/javascripts/packages/my_other_package/package.json", <<~CONTENTS) { "name": "@gusto/my_package", "metadata": { @@ -48,15 +49,15 @@ class OwnedFile; end } } CONTENTS - write_file('frontend/javascripts/packages/my_other_package/my_file.jsx') + write_file("frontend/javascripts/packages/my_other_package/my_file.jsx") - write_file('config/teams/foo.yml', <<~CONTENTS) + write_file("config/teams/foo.yml", <<~CONTENTS) name: Foo github: team: '@MyOrg/foo-team' CONTENTS - write_file('config/teams/bar.yml', <<~CONTENTS) + write_file("config/teams/bar.yml", <<~CONTENTS) name: Bar github: team: '@MyOrg/bar-team' @@ -65,25 +66,25 @@ class OwnedFile; end - frontend/javascripts/bar_stuff/** CONTENTS - write_file('app/services/bar_stuff/thing.rb') - write_file('frontend/javascripts/bar_stuff/thing.jsx') + write_file("app/services/bar_stuff/thing.rb") + write_file("frontend/javascripts/bar_stuff/thing.jsx") - write_file('packs/my_other_package/package.yml', <<~CONTENTS) + write_file("packs/my_other_package/package.yml", <<~CONTENTS) enforce_dependency: true enforce_privacy: true owner: Bar CONTENTS - write_file('package.yml', <<~CONTENTS) + write_file("package.yml", <<~CONTENTS) enforce_dependency: true enforce_privacy: true CONTENTS - write_file('packs/my_other_package/my_file.rb') + write_file("packs/my_other_package/my_file.rb") end let(:create_files_with_defined_classes) do - write_file('app/my_file.rb', <<~CONTENTS) + write_file("app/my_file.rb", <<~CONTENTS) # @team Foo require_relative 'my_error' @@ -95,7 +96,7 @@ def self.raise_error end CONTENTS - write_file('app/my_error.rb', <<~CONTENTS) + write_file("app/my_error.rb", <<~CONTENTS) # @team Bar class MyError @@ -105,13 +106,13 @@ def self.raise_error end CONTENTS - write_file('config/teams/foo.yml', <<~CONTENTS) + write_file("config/teams/foo.yml", <<~CONTENTS) name: Foo github: team: '@MyOrg/foo-team' CONTENTS - write_file('config/teams/bar.yml', <<~CONTENTS) + write_file("config/teams/bar.yml", <<~CONTENTS) name: Bar github: team: '@MyOrg/bar-team' @@ -122,6 +123,6 @@ def self.raise_error # we re-require the constant each time, since `RSpecTempfiles` changes where the file lives with each test Object.send(:remove_const, :MyFile) if defined? MyFile # : Object.send(:remove_const, :MyError) if defined? MyError # : - require Pathname.pwd.join('app/my_file') + require Pathname.pwd.join("app/my_file") end end From 5f66aeb30ea04d7b85132a1b2d9f79607d9c53c5 Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Mon, 30 Nov 2026 13:27:18 -0800 Subject: [PATCH 2/2] Enable RSpec/NotToNot and sort cop configurations - Enable RSpec/NotToNot, which rubocop-gusto leaves off by default - Autocorrect the `to_not` calls it flags (2 spec files) - Sort the cop configurations in .rubocop.yml alphabetically; a comment that introduced a group of cops is repeated on each cop in the group --- .rubocop.yml | 104 +++++++++++++++------------- spec/lib/code_ownership/cli_spec.rb | 2 +- spec/lib/code_ownership_spec.rb | 4 +- 3 files changed, 58 insertions(+), 52 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index fec12d19..fbba3e21 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -31,62 +31,79 @@ AllCops: - target/**/** TargetRubyVersion: 3.3 -Metrics/ParameterLists: +Gemspec/DevelopmentDependencies: + Enabled: true + EnforcedStyle: gemspec + +Gemspec/RequireMFA: Enabled: false -# This cop is annoying with typed configuration -Style/TrivialAccessors: +# This leads to code that is not very readable at times (very long lines) +Layout/ArgumentAlignment: Enabled: false -# This rubocop is annoying when we use interfaces a lot -Lint/UnusedMethodArgument: +# This leads to code that is not very readable at times (very long lines) +Layout/FirstArgumentIndentation: Enabled: false -Gemspec/RequireMFA: +# Leaving length metrics to human judgment for now +Layout/LineLength: + Enabled: false + +# This leads to code that is not very readable at times (very long lines) +Layout/MultilineMethodCallIndentation: Enabled: false Lint/DuplicateBranch: Enabled: false -# If is sometimes easier to think about than unless sometimes -Style/NegatedIf: +# This rubocop is annoying when we use interfaces a lot +Lint/UnusedMethodArgument: Enabled: false -# It's nice to be able to read the condition first before reading the code within the condition -Style/GuardClause: +# Leaving length metrics to human judgment for now +Metrics/AbcSize: Enabled: false -# # Leaving length metrics to human judgment for now -# -Metrics/ModuleLength: +Metrics/BlockLength: Enabled: false -Layout/LineLength: +# Leaving length metrics to human judgment for now +Metrics/ClassLength: Enabled: false -Metrics/BlockLength: +# This doesn't feel useful +Metrics/CyclomaticComplexity: Enabled: false +# Leaving length metrics to human judgment for now Metrics/MethodLength: Enabled: false -Metrics/AbcSize: +# Leaving length metrics to human judgment for now +Metrics/ModuleLength: Enabled: false -Metrics/ClassLength: +Metrics/ParameterLists: Enabled: false # This doesn't feel useful -Metrics/CyclomaticComplexity: +Metrics/PerceivedComplexity: Enabled: false -# This doesn't feel useful -Metrics/PerceivedComplexity: +# Sometimes we like methods like `get_packages` +Naming/AccessorMethodName: Enabled: false -# It's nice to be able to read the condition first before reading the code within the condition -Style/IfUnlessModifier: +RSpec/NotToNot: + Enabled: true + +Style/AccessorGrouping: + Enabled: false + +# Blocks across lines are okay sometimes +Style/BlockDelimiters: Enabled: false # This leads to code that is not very readable at times (very long lines) @@ -101,44 +118,33 @@ Style/Documentation: Style/EmptyElse: Enabled: false -# This interacts poorly with typed code -Style/ModuleFunction: - EnforcedStyle: forbidden - -# Sometimes we want to more explicitly list out a condition -Style/RedundantCondition: - Enabled: false - -# This leads to code that is not very readable at times (very long lines) -Layout/MultilineMethodCallIndentation: - Enabled: false - -# Blocks across lines are okay sometimes -Style/BlockDelimiters: +# It's nice to be able to read the condition first before reading the code within the condition +Style/GuardClause: Enabled: false -# Sometimes we like methods like `get_packages` -Naming/AccessorMethodName: +Style/HashSyntax: Enabled: false -# This leads to code that is not very readable at times (very long lines) -Layout/FirstArgumentIndentation: +# It's nice to be able to read the condition first before reading the code within the condition +Style/IfUnlessModifier: Enabled: false -# This leads to code that is not very readable at times (very long lines) -Layout/ArgumentAlignment: - Enabled: false +# This interacts poorly with typed code +Style/ModuleFunction: + EnforcedStyle: forbidden -Style/AccessorGrouping: +# If is sometimes easier to think about than unless sometimes +Style/NegatedIf: Enabled: false -Style/HashSyntax: +# Sometimes we want to more explicitly list out a condition +Style/RedundantCondition: Enabled: false -Gemspec/DevelopmentDependencies: - Enabled: true - EnforcedStyle: gemspec - Style/StringLiterals: Enabled: true EnforcedStyle: double_quotes + +# This cop is annoying with typed configuration +Style/TrivialAccessors: + Enabled: false diff --git a/spec/lib/code_ownership/cli_spec.rb b/spec/lib/code_ownership/cli_spec.rb index ca77f4e4..47559e24 100644 --- a/spec/lib/code_ownership/cli_spec.rb +++ b/spec/lib/code_ownership/cli_spec.rb @@ -43,7 +43,7 @@ end it "has empty output" do - expect(CodeOwnership::Cli).to_not receive(:puts) + expect(CodeOwnership::Cli).not_to receive(:puts) subject end end diff --git a/spec/lib/code_ownership_spec.rb b/spec/lib/code_ownership_spec.rb index cbab37b7..515d9b76 100644 --- a/spec/lib/code_ownership_spec.rb +++ b/spec/lib/code_ownership_spec.rb @@ -56,7 +56,7 @@ subject # caches paths -> teams allow(RustCodeOwners).to receive(:for_file) expect(described_class.for_file("packs/my_pack/owned_file.rb")).to eq(CodeTeams.find("Bar")) - expect(RustCodeOwners).to_not have_received(:for_file) + expect(RustCodeOwners).not_to have_received(:for_file) end end end @@ -133,7 +133,7 @@ subject # caches path -> team allow(RustCodeOwners).to receive(:for_file) expect(described_class.for_file(file_path)).to eq(CodeTeams.find("Bar")) - expect(RustCodeOwners).to_not have_received(:for_file) + expect(RustCodeOwners).not_to have_received(:for_file) end end end