From 8d97c9c5109cd8ba0c175b03c0ed26c5859e6cb6 Mon Sep 17 00:00:00 2001 From: Buildkite Date: Tue, 19 Nov 2019 05:32:27 -0600 Subject: [PATCH] Initial commit --- .gitignore | 13 ++ .rspec | 3 + .rubocop.yml | 12 ++ .travis.yml | 13 ++ Gemfile | 11 ++ LICENSE.txt | 21 +++ README.md | 61 +++++++- Rakefile | 36 +++++ bin/console | 15 ++ bin/setup | 8 ++ config/default.yml | 6 + lib/rubocop-flexport.rb | 11 ++ lib/rubocop/cop/flexport/new_global_model.rb | 131 ++++++++++++++++++ lib/rubocop/cop/flexport_cops.rb | 3 + lib/rubocop/flexport.rb | 15 ++ lib/rubocop/flexport/inject.rb | 20 +++ lib/rubocop/flexport/version.rb | 7 + rubocop-flexport.gemspec | 24 ++++ .../cop/flexport/new_global_model_spec.rb | 129 +++++++++++++++++ spec/rubocop/flexport_spec.rb | 7 + spec/spec_helper.rb | 16 +++ 21 files changed, 560 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 .rspec create mode 100644 .rubocop.yml create mode 100644 .travis.yml create mode 100644 Gemfile create mode 100644 LICENSE.txt create mode 100644 Rakefile create mode 100755 bin/console create mode 100755 bin/setup create mode 100644 config/default.yml create mode 100644 lib/rubocop-flexport.rb create mode 100644 lib/rubocop/cop/flexport/new_global_model.rb create mode 100644 lib/rubocop/cop/flexport_cops.rb create mode 100644 lib/rubocop/flexport.rb create mode 100644 lib/rubocop/flexport/inject.rb create mode 100644 lib/rubocop/flexport/version.rb create mode 100644 rubocop-flexport.gemspec create mode 100644 spec/rubocop/cop/flexport/new_global_model_spec.rb create mode 100644 spec/rubocop/flexport_spec.rb create mode 100644 spec/spec_helper.rb diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c249f1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ + +# rspec failure tracking +.rspec_status + +Gemfile.lock diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..28cb17b --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,12 @@ +Layout/ExtraSpacing: + Enabled: true + AllowForAlignment: false + +Metrics/BlockLength: + Enabled: true + Exclude: + - spec/**/*.rb + +Naming/FileName: + Exclude: + - lib/rubocop-flexport.rb diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..b5f9597 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,13 @@ +language: ruby +sudo: false +rvm: + - 2.3 + - 2.4 + - 2.5 + - 2.6 +install: + - gem install bundler + - bundle install +script: + - bundle exec rspec + - bundle exec rubocop diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..1558061 --- /dev/null +++ b/Gemfile @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } + +# Specify your gem's dependencies in rubocop-flexport.gemspec +gemspec +gem 'rake' +gem 'rspec' +gem 'rubocop', github: 'rubocop-hq/rubocop' diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..76a48ea --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Flexport Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index 90bef0e..ef8a0bc 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,59 @@ -# rubocop-flexport -Flexport Rubocop Config and Custom Cops +# Rubocop::Flexport + +This repo is for cops developed at Flexport that don't make sense to upstream +into any of the existing RuboCop repos. When possible, we prefer upstreaming. + +## Installation + +Add this line to your application's Gemfile: + +```ruby +gem 'rubocop-flexport' +``` + +And then execute: + + $ bundle + +Or install it yourself as: + + $ gem install rubocop-flexport + +## Usage + +Put this into your .rubocop.yml: + +``` +require: + - rubocop-flexport +``` + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run +`rake spec` to run the tests. You can also run `bin/console` for an interactive +prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. + +To test it locally against your main codebase, update your Gemfile to something +like below and then run `bundle install`: + +``` +gem "rubocop-flexport", path: "/Users//rubocop-flexport" +``` + +To release a new version, update the version number in `version.rb`, and then +run `bundle exec rake release`, which will create a git tag for the version, +push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/flexport/rubocop-flexport. +This project is intended to be a safe, welcoming space for collaboration, and +contributors are expected to adhere to the +[Contributor Covenant](http://contributor-covenant.org) code of conduct. + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..3f124fe --- /dev/null +++ b/Rakefile @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'bundler/gem_tasks' +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new(:spec) + +task default: :spec + +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new(:spec) do |spec| + spec.pattern = FileList['spec/**/*_spec.rb'] +end + +desc 'Generate a new cop with a template' +task :new_cop, [:cop] do |_task, args| + require 'rubocop' + + cop_name = args.fetch(:cop) do + warn 'usage: bundle exec rake new_cop[Department/Name]' + exit! + end + + github_user = `git config github.user`.chop + github_user = 'your_id' if github_user.empty? + + generator = RuboCop::Cop::Generator.new(cop_name, github_user) + + generator.write_source + generator.write_spec + generator.inject_require(root_file_path: 'lib/rubocop/cop/flexport_cops.rb') + generator.inject_config(config_file_path: 'config/default.yml') + + puts generator.todo +end diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..b959769 --- /dev/null +++ b/bin/console @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'bundler/setup' +require 'rubocop/flexport' + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +# (If you use this, don't forget to add pry to your Gemfile!) +# require "pry" +# Pry.start + +require 'irb' +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/config/default.yml b/config/default.yml new file mode 100644 index 0000000..58ab18e --- /dev/null +++ b/config/default.yml @@ -0,0 +1,6 @@ +Flexport/NewGlobalModel: + Description: 'Disallows addition of new global models to `app/models`. Prefer Rails Engines or namespaces.' + Enabled: true + VersionAdded: '0.1.0' + GlobalModelsPath: 'app/models/' + AllowNamespacedGlobalModels: true diff --git a/lib/rubocop-flexport.rb b/lib/rubocop-flexport.rb new file mode 100644 index 0000000..8f67652 --- /dev/null +++ b/lib/rubocop-flexport.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +require 'rubocop' + +require_relative 'rubocop/flexport' +require_relative 'rubocop/flexport/version' +require_relative 'rubocop/flexport/inject' + +RuboCop::Flexport::Inject.defaults! + +require_relative 'rubocop/cop/flexport_cops' diff --git a/lib/rubocop/cop/flexport/new_global_model.rb b/lib/rubocop/cop/flexport/new_global_model.rb new file mode 100644 index 0000000..ef192cf --- /dev/null +++ b/lib/rubocop/cop/flexport/new_global_model.rb @@ -0,0 +1,131 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Flexport + # This cop disallows adding new models to the `app/models` directory. + # + # The goal is to encourage developers to put new models inside Rails + # Engines (or at least namespaces), where they can be more modularly + # isolated and ownership is clear. + # + # Use RuboCop's standard `Exclude` file list parameter to exclude + # existing global model files from counting as violations for this cop. + # + # @example AllowNamespacedGlobalModels: true (default) + # # When `AllowNamespacedGlobalModels` is true, the cop only forbids + # # additions at the top-level directory. + # + # # bad + # # path: app/models/my_new_global_model.rb + # class MyNewGlobalModel < ApplicationRecord + # # ... + # end + # + # # good + # # path: app/models/my_namespace/my_new_global_model.rb + # class MyNamespace::MyNewGlobalModel < ApplicationRecord + # # ... + # end + # + # # good + # # path: engines/my_engine/app/models/my_engine/my_new_engine_model.rb + # class MyEngine::MyNewEngineModel < ApplicationRecord + # # ... + # end + # + # @example AllowNamespacedGlobalModels: false + # # When `AllowNamespacedGlobalModels` is false, the cop forbids all + # # new models in this directory and its descendants. + # + # # bad + # # path: app/models/my_new_global_model.rb + # class MyNewGlobalModel < ApplicationRecord + # # ... + # end + # + # # bad + # # path: app/models/my_namespace/my_new_global_model.rb + # class MyNamespace::MyNewGlobalModel < ApplicationRecord + # # ... + # end + # + # # good + # # path: engines/my_engine/app/models/my_engine/my_new_engine_model.rb + # class MyEngine::MyNewEngineModel < ApplicationRecord + # # ... + # end + class NewGlobalModel < Cop + ALLOW_NAMESPACES_MSG = + 'Do not add new top-level global models in `app/models`. ' \ + 'Prefer namespaced models like `app/models/foo/bar.rb` or ' \ + 'or models inside Rails Engines.' + + DISALLOW_NAMESPACES_MSG = + 'Do not add new global models in `app/models`. ' \ + 'Instead add new models to Rails Engines.' + + def investigate(processed_source) + return if processed_source.blank? + + path = processed_source.file_path + return unless global_rails_model?(path) + + add_offense(processed_source.ast) + end + + private + + def message(_node) + return ALLOW_NAMESPACES_MSG if allow_namespaced_global_models + + DISALLOW_NAMESPACES_MSG + end + + def global_rails_model?(path) + return false unless path.include?(global_models_path) + return false if path.include?('/concerns/') + return false if in_engine?(path) + return false if allowed_namespace?(path) + + true + end + + def allowed_namespace?(path) + return false unless allow_namespaced_global_models + + parts = path.split(global_models_path) + parts.last.split('/').length > 1 + end + + def in_engine?(path) + return true if path.include?('/engines/') + + # Engines model dirs are structured like: + # my_engine/app/models/my_engine/my_model.rb. + # We detect models whose directory structure matches + # this pattern even if they aren't children of an + # "/engines/" directory. + parts = path.split(global_models_path) + potential_engine_name = parts.last.split('/').first + engine_models_path = File.join( + potential_engine_name, + global_models_path, + potential_engine_name + ) + path.include?(engine_models_path) + end + + def global_models_path + path = cop_config['GlobalModelsPath'] + path += '/' unless path.end_with?('/') + path + end + + def allow_namespaced_global_models + cop_config['AllowNamespacedGlobalModels'] + end + end + end + end +end diff --git a/lib/rubocop/cop/flexport_cops.rb b/lib/rubocop/cop/flexport_cops.rb new file mode 100644 index 0000000..e01a9da --- /dev/null +++ b/lib/rubocop/cop/flexport_cops.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require_relative 'flexport/new_global_model' diff --git a/lib/rubocop/flexport.rb b/lib/rubocop/flexport.rb new file mode 100644 index 0000000..4d54263 --- /dev/null +++ b/lib/rubocop/flexport.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require 'rubocop/flexport/version' + +module RuboCop + # Namespace for Flexport-specific RuboCop cops. + module Flexport + class Error < StandardError; end + PROJECT_ROOT = Pathname.new(__dir__).parent.parent.expand_path.freeze + CONFIG_DEFAULT = PROJECT_ROOT.join('config', 'default.yml').freeze + CONFIG = YAML.safe_load(CONFIG_DEFAULT.read).freeze + + private_constant(:CONFIG_DEFAULT, :PROJECT_ROOT) + end +end diff --git a/lib/rubocop/flexport/inject.rb b/lib/rubocop/flexport/inject.rb new file mode 100644 index 0000000..b6ef4cd --- /dev/null +++ b/lib/rubocop/flexport/inject.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +# The original code is from https://github.com/rubocop-hq/rubocop-rspec/blob/master/lib/rubocop/rspec/inject.rb +# See https://github.com/rubocop-hq/rubocop-rspec/blob/master/MIT-LICENSE.md +module RuboCop + module Flexport + # Because RuboCop doesn't yet support plugins, we have to monkey patch in a + # bit of our configuration. + module Inject + def self.defaults! + path = CONFIG_DEFAULT.to_s + hash = ConfigLoader.send(:load_yaml_configuration, path) + config = Config.new(hash, path) + puts "configuration from #{path}" if ConfigLoader.debug? + config = ConfigLoader.merge_with_default(config, path) + ConfigLoader.instance_variable_set(:@default_configuration, config) + end + end + end +end diff --git a/lib/rubocop/flexport/version.rb b/lib/rubocop/flexport/version.rb new file mode 100644 index 0000000..bd03859 --- /dev/null +++ b/lib/rubocop/flexport/version.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module RuboCop + module Flexport + VERSION = '0.1.0' + end +end diff --git a/rubocop-flexport.gemspec b/rubocop-flexport.gemspec new file mode 100644 index 0000000..94dfa9a --- /dev/null +++ b/rubocop-flexport.gemspec @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path('lib', __dir__) +require_relative 'lib/rubocop/flexport/version' + +Gem::Specification.new do |spec| + spec.name = 'rubocop-flexport' + spec.version = RuboCop::Flexport::VERSION + spec.authors = ['Flexport Engineering'] + spec.email = ['dev@flexport.com'] + + spec.summary = 'RuboCop cops used at Flexport.' + spec.description = '' + spec.homepage = 'https://github.com/flexport/rubocop-flexport' + spec.license = 'MIT' + + spec.files = `git ls-files bin config lib LICENSE.txt README.md` + .split($RS) + spec.bindir = 'exe' + spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } + spec.require_paths = ['lib'] + + spec.add_runtime_dependency 'rubocop', '>= 0.70.0' +end diff --git a/spec/rubocop/cop/flexport/new_global_model_spec.rb b/spec/rubocop/cop/flexport/new_global_model_spec.rb new file mode 100644 index 0000000..78a1cdc --- /dev/null +++ b/spec/rubocop/cop/flexport/new_global_model_spec.rb @@ -0,0 +1,129 @@ +# frozen_string_literal: true + +RSpec.describe RuboCop::Cop::Flexport::NewGlobalModel do + subject(:cop) { described_class.new(config) } + + let(:config) do + RuboCop::Config.new( + 'Flexport/NewGlobalModel' => { + 'GlobalModelsPath' => 'app/models/', + 'AllowNamespacedGlobalModels' => true + } + ) + end + + context 'when non-model file' do + let(:random_file) { '/root/bar/random.rb' } + + let(:source) do + <<~RUBY + module RandomFile + FOO = 1 + end + RUBY + end + + it 'does not add any offenses' do + expect_no_offenses(source, random_file) + end + end + + context 'engine models' do + context 'when model in engine' do + let(:engine_model_file) do + '/root/engines/my_engine/app/models/my_engine/model_in_engine.rb' + end + + let(:source) do + <<~RUBY + class GlobalModelInEngine + FOO = 1 + end + RUBY + end + + it 'does not add any offenses' do + expect_no_offenses(source, engine_model_file) + end + end + + context 'when model in engine without /engines/ in path' do + let(:atypical_engine_model_file) do + '/root/radiators/my_engine/app/models/my_engine/model_in_engine.rb' + end + + let(:source) do + <<~RUBY + class GlobalModelInEngine + FOO = 1 + end + RUBY + end + + it 'does not add any offenses' do + expect_no_offenses(source, atypical_engine_model_file) + end + end + end + + context 'global models' do + context 'when new global model file' do + let(:global_model_file) { '/root/app/models/new_global_model.rb' } + + let(:source) do + <<~RUBY + class NewGlobalModel + ^^^^^^^^^^^^^^^^^^^^ Do not add new top-level global models in `app/models`. Prefer namespaced models like `app/models/foo/bar.rb` or or models inside Rails Engines. + FOO = 1 + end + RUBY + end + + it 'adds offenses' do + expect_offense(source, global_model_file) + end + end + + context 'when model in subdir' do + let(:global_model_file_in_sub_dir) { '/root/app/models/foo/bar.rb' } + + context 'AllowNamespacedGlobalModels is true' do + let(:source) do + <<~RUBY + class Foo::Bar + FOO = 1 + end + RUBY + end + + it 'does not add any offenses' do + expect_no_offenses(source, global_model_file_in_sub_dir) + end + end + + context 'AllowNamespacedGlobalModels is false' do + let(:config) do + RuboCop::Config.new( + 'Flexport/NewGlobalModel' => { + 'GlobalModelsPath' => 'app/models/', + 'AllowNamespacedGlobalModels' => false + } + ) + end + + let(:source) do + <<~RUBY + class Foo::Bar + ^^^^^^^^^^^^^^ Do not add new global models in `app/models`. Instead add new models to Rails Engines. + FOO = 1 + end + RUBY + end + + it 'adds offenses' do + expect_offense(source, global_model_file_in_sub_dir) + end + end + end + end +end diff --git a/spec/rubocop/flexport_spec.rb b/spec/rubocop/flexport_spec.rb new file mode 100644 index 0000000..f082d0b --- /dev/null +++ b/spec/rubocop/flexport_spec.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +RSpec.describe RuboCop::Flexport do + it 'has a version number' do + expect(RuboCop::Flexport::VERSION).not_to be nil + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..d4a3d8f --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require 'rubocop-flexport' +require 'rubocop/rspec/support' + +RSpec.configure do |config| + config.include RuboCop::RSpec::ExpectOffense + + config.disable_monkey_patching! + config.raise_errors_for_deprecations! + config.raise_on_warning = true + config.fail_if_no_examples = true + + config.order = :random + Kernel.srand config.seed +end