diff --git a/lib/bundler/gem_bytes/actions.rb b/lib/bundler/gem_bytes/actions.rb index a1ce0d9..aca5c56 100644 --- a/lib/bundler/gem_bytes/actions.rb +++ b/lib/bundler/gem_bytes/actions.rb @@ -1,9 +1,37 @@ # frozen_string_literal: true +require 'bundler/gem_bytes' + module Bundler module GemBytes # The API for GemBytes templates # @api public - module Actions; end + module Actions + # Adds (or updates) a dependency in the project's gemspec file + # + # @example + # add_dependency(:development, 'rspec', '~> 3.13') + # add_dependency(:runtime, 'activesupport', '>= 6.0.0') + # + # @param dependency_type [Symbol] the type of dependency to add (either :development or :runtime) + # @param gem_name [String] the name of the gem to add + # @param version_constraint [String] the version constraint for the gem + # @param force [Boolean] whether to overwrite the existing dependency + # @param gemspec [String] the path to the gemspec file + # + # @return [void] + # + # @api public + # + def add_dependency(dependency_type, gem_name, version_constraint, force: false, gemspec: Dir['*.gemspec'].first) + puts 'Staring' + source = File.read(gemspec) + updated_source = Bundler::GemBytes::Gemspec::UpsertDependency.new( + dependency_type, gem_name, version_constraint, force: force + ).call(source) + File.write(gemspec, updated_source) + puts 'Ending' + end + end end end diff --git a/spec/lib/bundler/gem_bytes/actions_spec.rb b/spec/lib/bundler/gem_bytes/actions_spec.rb new file mode 100644 index 0000000..39c7ff8 --- /dev/null +++ b/spec/lib/bundler/gem_bytes/actions_spec.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +RSpec.describe Bundler::GemBytes::Actions do + let(:including_class) do + Class.new do + include Bundler::GemBytes::Actions + end + end + + let(:instance) { including_class.new } + + # More detailed tests of add_dependency are in the tests for UpsertDependency + # class. + # + # These tests just make sure that calls to add_dependency are correctly delegated + # to the UpsertDependency class. + # + describe '.add_dependency' do + subject { instance.add_dependency(dependency_type, gem_name, version_constraint, force:) } + + let(:dependency_type) { :development } + let(:gem_name) { 'rspec' } + let(:version_constraint) { '~> 3.13' } + let(:force) { false } + + it 'adds the dependency to the gemspec' do + # Make a temporary directory to work in + Dir.mktmpdir do |temp_dir| + Dir.chdir(temp_dir) do + # Create a new gemspec file + gemspec_file = 'my_gem.gemspec' + File.write(gemspec_file, <<~GEMSPEC) + Gem::Specification.new do |spec| + spec.name = 'my_gem' + spec.version = '0.1.0' + end + GEMSPEC + + # Add the dependency + instance.add_dependency(dependency_type, gem_name, version_constraint, force: force) + + # Read the gemspec file + gemspec_content = File.read(gemspec_file) + + # Check that the dependency was added + expect(gemspec_content).to include("spec.add_development_dependency 'rspec', '~> 3.13'") + end + end + end + end +end