Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rubolint all the things #2

Merged
merged 2 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require:
- rubocop-rake
- rubocop-rspec

AllCops:
NewCops: enable
Comment on lines +5 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Review Required: RuboCop version not pinned in Gemfile.

Enabling NewCops is beneficial for staying updated with the latest style recommendations. However, since RuboCop is not version-pinned in the Gemfile, automatic updates may introduce unexpected changes in your CI pipelines.

  • File: Gemfile
    • Line: gem 'rubocop'

Recommendation: Pin the RuboCop version in your Gemfile to ensure consistent behavior across environments. For example:

gem 'rubocop', '1.66.1'
Analysis chain

LGTM: NewCops enabled, consider version pinning.

Enabling NewCops is a good practice as it keeps the project up-to-date with the latest style recommendations. However, it's worth noting that this may introduce unexpected changes in CI pipelines when RuboCop is updated.

To ensure consistent behavior across different environments, consider pinning the RuboCop version in your Gemfile. You can verify the current RuboCop version with:

If the version isn't pinned, you might want to update your Gemfile to include a specific version of RuboCop.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check RuboCop version in Gemfile.lock
grep -A 2 "rubocop " Gemfile.lock

Length of output: 260


Script:

#!/bin/bash
# Description: Check if RuboCop version is pinned in Gemfile
grep -E '^\s*gem ["'\''"]rubocop["'\''"]' Gemfile

Length of output: 67


Exclude:
- 'lib/hawksi.rb'

Style/HashSyntax:
Enabled: false

Layout/HeredocIndentation:
Exclude:
- 'lib/hawksi.rb'

Metrics/BlockLength:
Exclude:
- 'spec/**/*'
- '*.gemspec'
10 changes: 8 additions & 2 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@

source 'https://rubygems.org'

gem 'json'
gem 'httpx', '~> 1.3'
gem "puma", ">= 6.4.3"
gem 'json'
gem 'puma', '>= 6.4.3'
gem 'rack'
gem 'thor'

group :development, :test do
gem 'bundler'
gem 'rake'
gem 'rspec', '~> 3.13'
gem 'rubocop', '1.66.1'
gem 'rubocop-rake'
gem 'rubocop-rspec'
gem 'ruby-lsp'
end

group :test do
Expand Down
44 changes: 44 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
GEM
remote: https://rubygems.org/
specs:
ast (2.4.2)
diff-lcs (1.5.1)
http-2 (1.0.1)
httpx (1.3.0)
http-2 (>= 1.0.0)
json (2.7.1)
language_server-protocol (3.17.0.3)
logger (1.6.1)
nio4r (2.7.3)
parallel (1.26.3)
parser (3.3.5.0)
ast (~> 2.4.1)
racc
prism (1.0.0)
puma (6.4.3)
nio4r (~> 2.0)
racc (1.8.1)
rack (2.2.9)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rainbow (3.1.1)
rake (13.2.1)
rbs (3.5.3)
logger
regexp_parser (2.9.2)
rspec (3.13.0)
rspec-core (~> 3.13.0)
rspec-expectations (~> 3.13.0)
Expand All @@ -25,19 +39,49 @@ GEM
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-support (3.13.1)
rubocop (1.66.1)
json (~> 2.3)
language_server-protocol (>= 3.17.0)
parallel (~> 1.10)
parser (>= 3.3.0.2)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 2.4, < 3.0)
rubocop-ast (>= 1.32.2, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 3.0)
rubocop-ast (1.32.3)
parser (>= 3.3.1.0)
rubocop-rake (0.6.0)
rubocop (~> 1.0)
rubocop-rspec (3.0.5)
rubocop (~> 1.61)
ruby-lsp (0.18.2)
language_server-protocol (~> 3.17.0)
prism (~> 1.0)
rbs (>= 3, < 4)
sorbet-runtime (>= 0.5.10782)
ruby-progressbar (1.13.0)
sorbet-runtime (0.5.11577)
thor (1.3.1)
unicode-display_width (2.5.0)

PLATFORMS
arm64-darwin-23
ruby

DEPENDENCIES
bundler
httpx (~> 1.3)
json
puma (>= 6.4.3)
rack
rack-test (~> 1.1)
rake
rspec (~> 3.13)
rubocop (= 1.66.1)
rubocop-rake
rubocop-rspec
ruby-lsp
thor

BUNDLED WITH
Expand Down
6 changes: 4 additions & 2 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

require 'bundler/gem_tasks'
require 'rspec/core/rake_task'

Expand All @@ -11,11 +13,11 @@ task :build do
end

desc 'Install the Hawksi gem locally'
task :install => :build do
task install: :build do
system "gem install ./hawksi-#{Hawksi::VERSION}.gem"
end

desc 'Release the Hawksi gem to RubyGems'
task :release => :build do
task release: :build do
system "gem push ./hawksi-#{Hawksi::VERSION}.gem"
end
2 changes: 2 additions & 0 deletions bin/hawksi
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative '../lib/hawksi'
CLI.start(ARGV)
20 changes: 10 additions & 10 deletions hawksi.gemspec
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

# hawksi.gemspec
require_relative 'lib/version'

Expand All @@ -8,7 +10,8 @@ Gem::Specification.new do |spec|
spec.email = ['[email protected]']

spec.summary = 'Hawksi: Rack middleware to the Mocksi API.'
spec.description = 'Hawksi sits between your application and the Mocksi API, allowing our agents to learn from your app to simulate whatever you can imagine.'
spec.description = 'Hawksi sits between your application and the Mocksi API,\n'
spec.description += 'allowing our agents to learn from your app to simulate whatever you can imagine.'
spec.homepage = 'https://github.com/Mocksi/hawksi'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 3.2.0')
Expand All @@ -20,22 +23,19 @@ Gem::Specification.new do |spec|
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject do |f|
%w[test spec features .gitignore hawksi.gemspec].include?(f) ||
f.match?(/(^\.|\/\.\.|\.\.\/|\.git|\.hg|CVS|\.svn|\.lock|~$)/) ||
f.end_with?('.gem') # Exclude gem files
f.match?(%r{(^\.|/\.\.|\.\./|\.git|\.hg|CVS|\.svn|\.lock|~$)}) ||
f.end_with?('.gem') # Exclude gem files
end
end
spec.bindir = 'bin'
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ['lib']

spec.add_dependency 'rack', '~> 2.2'
spec.add_dependency 'httpx', '~> 1.3'
spec.add_dependency 'json', '~> 2.5'
spec.add_dependency 'puma', '~> 5.0'
spec.add_dependency 'rack', '~> 2.2'
spec.add_dependency 'thor', '~> 1.1'
spec.add_dependency 'json', '~> 2.5'
spec.add_dependency 'httpx', '~> 1.3'


spec.add_development_dependency 'bundler', '~> 2.2'
spec.add_development_dependency 'rake', '~> 13.0'
spec.add_development_dependency 'rspec', '~> 3.10'
spec.metadata['rubygems_mfa_required'] = 'true'
end
12 changes: 8 additions & 4 deletions lib/captures_cli.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
# frozen_string_literal: true

require 'thor'
require_relative 'file_storage'

# CLI for listing captured requests and responses
class CapturesCLI < Thor
desc "list", "Lists recent captured requests and responses"
option :base_dir, type: :string, desc: 'Base directory for storing intercepted data. Defaults to ./tmp/intercepted_data'
def list(*args)
desc 'list', 'Lists recent captured requests and responses'
option :base_dir, type: :string,
desc: 'Base directory for storing intercepted data. Defaults to ./tmp/intercepted_data'
def list(*_args) # rubocop:disable Metrics/MethodLength
base_dir = FileStorage.base_dir
FileStorage.base_dir = options[:base_dir] if options[:base_dir]

Expand All @@ -14,7 +18,7 @@ def list(*args)
files = Dir.glob(glob_pattern)

if files.empty?
puts "No captured requests or responses found."
puts 'No captured requests or responses found.'
return
end

Expand Down
28 changes: 16 additions & 12 deletions lib/cli.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

require 'thor'
require 'puma'
require 'puma/cli'
Expand All @@ -6,33 +8,35 @@
require_relative 'captures_cli'
require_relative 'uploads_cli'

# CLI for starting and stopping the Hawksi Interceptor server
class CLI < Thor
desc "start", "Starts the Hawksi Interceptor server"
option :base_dir, type: :string, desc: 'Base directory for storing intercepted data. Defaults to ./tmp/intercepted_data'
desc 'start', 'Starts the Hawksi Interceptor server'
option :base_dir, type: :string,
desc: 'Base directory for storing intercepted data. Defaults to ./tmp/intercepted_data'
def start(*args)
FileStorage.base_dir = options[:base_dir] if options[:base_dir]
puts "Starting HawksiInterceptor server..."
puts 'Starting HawksiInterceptor server...'
Puma::CLI.new(args).run
end

map 'serve' => 'start'

desc "stop", "Stops the HawksiInterceptor server"
desc 'stop', 'Stops the HawksiInterceptor server'
def stop
puts "Stopping Hawksi Interceptor server..."
system("pkill -f puma")
puts 'Stopping Hawksi Interceptor server...'
system('pkill -f puma')
end

desc "captures", "Manage captures"
subcommand "captures", CapturesCLI
desc 'captures', 'Manage captures'
subcommand 'captures', CapturesCLI

desc "uploads", "Uploads captured requests and responses"
subcommand "uploads", UploadsCLI
desc 'uploads', 'Uploads captured requests and responses'
subcommand 'uploads', UploadsCLI

desc "clear", "Clears stored request/response data"
desc 'clear', 'Clears stored request/response data'
def clear
FileUtils.rm_rf('./intercepted_data/requests')
FileUtils.rm_rf('./intercepted_data/responses')
puts "Cleared stored data."
puts 'Cleared stored data.'
end
end
12 changes: 8 additions & 4 deletions lib/command_executor.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# frozen_string_literal: true

require 'httpx'
require 'json'
require 'logger'

# Generates and sends commands to the Reactor endpoint.
class CommandExecutor
attr_reader :logger, :client_uuid, :endpoint_url

Expand All @@ -11,12 +14,12 @@ def initialize(logger, client_uuid)
@endpoint_url = Hawksi.configuration.reactor_url
end

def execute_command(command, params)
def execute_command(command, params) # rubocop:disable Metrics/MethodLength
request_body = build_request_body(command, params)
response = send_request(request_body)

if response.nil?
logger.error "Failed to execute command due to a request error."
logger.error 'Failed to execute command due to a request error.'
elsif response.is_a?(HTTPX::ErrorResponse)
logger.error "HTTPX Error: #{response.error.message}"
elsif response.status == 200
Expand All @@ -39,8 +42,9 @@ def build_request_body(command, params)
def send_request(request_body)
logger.info "sending request to #{endpoint_url}"
logger.info "request body: #{request_body}"
HTTPX.post(endpoint_url, headers: { "Content-Type" => "application/json", "x-client-id" => client_uuid }, body: request_body)
rescue => e
HTTPX.post(endpoint_url, headers: { 'Content-Type' => 'application/json', 'x-client-id' => client_uuid },
body: request_body)
rescue StandardError => e
logger.error "Failed to send request: #{e.message}"
nil
end
Expand Down
6 changes: 4 additions & 2 deletions lib/file_handler.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# frozen_string_literal: true

require 'fileutils'
require 'securerandom'

# Handles file operations.
class FileHandler
def initialize(base_dir, logger)
@base_dir = base_dir
Expand All @@ -25,7 +28,7 @@ def generate_client_uuid
client_uuid
end

def create_tar_gz_files(files)
def create_tar_gz_files(files) # rubocop:disable Metrics/MethodLength
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider refactoring instead of disabling RuboCop.

While it's sometimes necessary to disable RuboCop cops, it's generally better to refactor the code to comply with the rules. The Metrics/MethodLength cop is designed to encourage methods that are focused and not too complex.

Consider breaking down the create_tar_gz_files method into smaller, more focused methods. This could improve readability and maintainability. For example:

def create_tar_gz_files(files)
  files.map { |file| create_tar_gz_file(file) }.compact
end

private

def create_tar_gz_file(file)
  tar_gz_file = "#{file}.tar.gz"
  return tar_gz_file if File.exist?(tar_gz_file)

  create_tarball(file)
  compress_tarball(file)
  tar_gz_file
end

def create_tarball(file)
  tar_file = "#{file}.tar"
  system("tar -C #{File.dirname(file)} -cf #{tar_file} #{File.basename(file)}")
end

def compress_tarball(file)
  tar_file = "#{file}.tar"
  system("gzip #{tar_file}")
end

This refactoring breaks down the logic into smaller, more focused methods, which should resolve the Metrics/MethodLength issue without needing to disable the cop.

tar_gz_files = []
files.each do |file|
tar_file = "#{file}.tar"
Expand All @@ -39,7 +42,6 @@ def create_tar_gz_files(files)
system("gzip #{tar_file}")
end


tar_gz_files << tar_gz_file
end
tar_gz_files
Expand Down
7 changes: 4 additions & 3 deletions lib/file_storage.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# frozen_string_literal: true

require 'json'
require 'fileutils'
require 'securerandom'

# Handles file storage..
class FileStorage
def self.base_dir
@base_dir ||= ENV['HAWKSI_BASE_DIR'] || './tmp/intercepted_data'
Expand All @@ -24,9 +27,7 @@ def self.store(type, data)
file_path = File.join(dir, filename)

puts("Storing data in: #{file_path}")
File.open(file_path, 'w') do |file|
file.write(data.to_json)
end
File.write(file_path, data.to_json)
puts("Data stored in: #{file_path}")
end
end
Expand Down
Loading
Loading