diff --git a/.gitignore b/.gitignore index 31cafb5..b742e0d 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ tmp *.o *.a mkmf.log +log diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..25a0417 --- /dev/null +++ b/.rspec @@ -0,0 +1,4 @@ +--format +d +--colour +--order rand \ No newline at end of file diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..026c183 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,29 @@ +# This is the configuration used to check the rubocop source code. + +inherit_from: .rubocop_todo.yml + +AllCops: + Include: + - 'lib/**/*.rb' + - 'bin/*' + - 'Rakefile' + - 'Gemfile' + - '*.gemspec' + Exclude: + - '.**/*' + - 'spec/**/*' + - 'coverage/**/*' + - '.vendor/**/*' + - 'vendor/**/*' + - '.bundle/**/*' + +Metrics/LineLength: + Max: 120 + +Metrics/MethodLength: + Max: 15 + +Metrics/AbcSize: + Max: 20 +Style/ClassAndModuleChildren: + EnforcedStyle: compact \ No newline at end of file diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..e69de29 diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..e00d7e9 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +--- +language: ruby +sudo: false +bundler_args: --without development --jobs=3 --retry=3 --path=${BUNDLE_PATH:-vendor/bundle} +cache: bundler +script: + - bundle exec rake test +before_install: rm -f Gemfile.lock +rvm: + - '1.9' + - '2.0' + - '2.1' + - '2.2' +notifications: + email: false diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..2da0da6 --- /dev/null +++ b/Gemfile @@ -0,0 +1,30 @@ +source ENV['GEM_SOURCE'] || 'https://rubygems.org' + +gemspec + +group :test do + gem 'rake', '~> 10.4.0', require: false + gem 'rspec', '~> 3.3.0', require: false + gem 'rspec-its', '~> 1.2.0', require: false + gem 'simplecov', '~> 0.10.0', require: false + gem 'rubocop', '~> 0.34.0', require: false + gem 'inch', '~> 0.7.0', require: false + gem 'coveralls', '~> 0.8.9', require: false + gem 'codeclimate-test-reporter', '~> 0.4.8', require: false +end + +group :development do + gem 'guard', '~> 2.13.0', require: false + gem 'guard-bundler', '~> 2.1.0', require: false + gem 'guard-rake', '~> 1.0.0', require: false + gem 'guard-rubocop', '~> 1.2.0', require: false + gem 'pry-byebug', '~> 3.2.0', require: false if RUBY_VERSION > '2.0.0' +end + +local_gemfile = File.join(File.dirname(__FILE__), 'Gemfile.ruby19') +eval_gemfile local_gemfile if File.exist?(local_gemfile) + +local_gemfile = File.join(File.dirname(__FILE__), 'Gemfile.local') +eval_gemfile local_gemfile if File.exist?(local_gemfile) + +# vim:ft=ruby diff --git a/Gemfile.ruby19 b/Gemfile.ruby19 new file mode 100644 index 0000000..ff4330a --- /dev/null +++ b/Gemfile.ruby19 @@ -0,0 +1 @@ +gem 'tins', '~> 1.6.0', require: false if RUBY_VERSION < '2.0.0' \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..42e49b8 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2015 Centralny Ośrodek Informatyki + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..fcb3b1b --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# Revamp + +[![Build Status](https://travis-ci.org/coi-gov-pl/revamp.svg)](https://travis-ci.org/coi-gov-pl/revamp) [![Coverage Status](https://coveralls.io/repos/coi-gov-pl/revamp/badge.svg?branch=develop&service=github)](https://coveralls.io/github/coi-gov-pl/revamp?branch=develop) [![Code Climate](https://codeclimate.com/github/coi-gov-pl/revamp/badges/gpa.svg)](https://codeclimate.com/github/coi-gov-pl/revamp) [![Dependency Status](https://gemnasium.com/coi-gov-pl/revamp.svg)](https://gemnasium.com/coi-gov-pl/revamp) + +This module can convert standard puppet module file in form of tarball to valid RPM or DEB package with all dependencies as references to other system packages. The dependencies can be packaged inside the final system package or just referenced as dependencies. + +## Installation + +Install it yourself, globally as: + + $ sudo gem install revamp + +On Debian/Ubuntu systems to convert to RPM you will need also: + + $ sudo apt-get install librpm-dev + +## Usage + +The basic usage is really simple: + + $ revamp -f coi-jboss-1.0.0.tar.gz + INFO: Converting to RPM package puppetmodule_coi-jboss-1.0.0-0.noarch.rpm... + INFO: Files successfully converted: 1. + +Or with extra options: + + $ revamp --release 42 --outdir /tmp -f coi-jboss-1.0.0.tar.gz + INFO: Converting to RPM package /tmp/puppetmodule_coi-jboss-1.0.0-42.noarch.rpm... + INFO: Files successfully converted: 1. + +More on available options in help: + + $ revamp --help + +## Contributing + +1. Fork it ( https://github.com/coi-gov-pl/gem-revamp/fork ) +2. Create your feature branch (`git checkout -b feature/my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin feature/my-new-feature`) +5. Create a new Pull Request diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..284a7fd --- /dev/null +++ b/Rakefile @@ -0,0 +1,63 @@ +require 'bundler/gem_tasks' +require 'rspec/core/rake_task' +require 'rubocop/rake_task' +require 'rubocop' +require 'fileutils' +require 'rainbow' +require 'inch/rake' + +namespace :spec do + desc 'Run all spec tests at once.' + RSpec::Core::RakeTask.new(:all) + + desc 'Run unit spec tests.' + RSpec::Core::RakeTask.new(:unit) do |t| + t.pattern = [ + 'spec/unit' + ] + end + + desc 'Run integration spec tests.' + RSpec::Core::RakeTask.new(:integration) do |t| + t.pattern = [ + 'spec/integration' + ] + end +end + +Inch::Rake::Suggest.new :inch, '--pedantic' + +RuboCop::RakeTask.new(:rubocop) do |task| + # don't abort rake on failure + task.fail_on_error = true +end + +namespace :rubocop do + namespace :todo do + desc 'Cleans a rubocop TODO list' + task :clean do + File.write('.rubocop_todo.yml', '') + Rake::Task[:rubocop].execute + end + + desc 'Saves actual rubocop state into TODO list' + task :save do + rcli = RuboCop::CLI.new + rcli.run ['--auto-gen-config'] + end + end +end + +tests = [ + :'spec:all', + :rubocop, + :inch +] + +desc 'Run lint, and all spec tests.' +task test: tests + +desc 'test package' +task build: [:test] + +task default: :test diff --git a/bin/revamp b/bin/revamp new file mode 100755 index 0000000..38d417d --- /dev/null +++ b/bin/revamp @@ -0,0 +1,13 @@ +#!/usr/bin/env ruby + +$0 = 'revamp' + +begin + require 'revamp/cli' +rescue LoadError + require 'rubygems' + require 'revamp/cli' +end + +# Process command line options and run Revamp +Kernel.exit(Revamp::CLI.new.run!) diff --git a/lib/revamp.rb b/lib/revamp.rb new file mode 100644 index 0000000..773aa32 --- /dev/null +++ b/lib/revamp.rb @@ -0,0 +1,61 @@ +require 'logger' + +begin + require 'pry' +rescue LoadError # rubocop:disable Lint/HandleExceptions + # Do nothing here +end + +# Top level module for Revamp +module Revamp + @logger = Logger.new($stdout) + @logger.formatter = proc { |severity, _datetime, _progname, msg| "#{severity}: #{msg}\n" } + class << self + # Logger for CLI interface + # @return [Logger] logger for CLI + attr_reader :logger + + # Reports a bug in desired format + # + # @param ex [Exception] an exception that was thrown + # @return [Hash] a hash with info about bug to be displayed to user + def bug(ex) + file = Tempfile.new(['revamp-bug', '.log']) + filepath = file.path + file.close + file.unlink + message = "v#{Revamp::VERSION}-#{ex.class}: #{ex.message}" + contents = message + "\n\n" + ex.backtrace.join("\n") + "\n" + File.write(filepath, contents) + bugo = { + message: message, + homepage: Revamp::HOMEPAGE, + bugfile: filepath, + help: "Please report this bug to #{Revamp::HOMEPAGE} by passing contents of bug file: #{filepath}" + } + bugo + end + end +end + +# A module for modeles +module Revamp::Model +end + +# A module for mapper +module Revamp::Mapper +end + +# A module for persister +module Revamp::Persister +end + +# Parser module +module Revamp::Parser +end + +# A module for filters of persiters +module Revamp::Filter +end + +require 'revamp/version' diff --git a/lib/revamp/application.rb b/lib/revamp/application.rb new file mode 100644 index 0000000..6c6d79c --- /dev/null +++ b/lib/revamp/application.rb @@ -0,0 +1,33 @@ +require 'revamp' +require 'revamp/persister/rpm' +require 'revamp/parser/puppet-tarball' + +# A main application class +class Revamp::Application + def initialize(options) + @options = options + @filenames = options[:filenames] + @format = :rpm + end + + def run! + @filenames.each do |file| + parser = Revamp::Parser::PuppetTarball.new(file) + model = parser.parse + persister = build_persister + persister.persist(model) + end + Revamp.logger.info("Files successfully converted: #{@filenames.size}.") + end + + protected + + def build_persister + persister = case @format + when :rpm then Revamp::Persister::Rpm.new + else fail ArgumentError, "Unknown format: #{@format}" + end + persister.options = @options + persister + end +end diff --git a/lib/revamp/cli.rb b/lib/revamp/cli.rb new file mode 100644 index 0000000..1607b78 --- /dev/null +++ b/lib/revamp/cli.rb @@ -0,0 +1,98 @@ +require 'micro-optparse' +require 'revamp' + +# A command line interface class +class Revamp::CLI + # Executes an Revamp from CLI + # + # @param argv [Array] an argv from CLI + # @return [Integer] a status code for program + def run!(argv = ARGV) + exec = parse_execution(argv) + return -1 unless exec.success? + exec = run_execution(exec.value) + return 1 unless exec.success? + 0 + end + + protected + + # Parse an ARGV command line arguments + # @param argv [Array] an argv from CLI + # @return [Hash] options to use by application + def parse(argv) + options = parser.process!(argv) + validate_options(options) + Revamp.logger.level = Logger::INFO unless options[:verbose] + options + end + + private + + def validate_options(options) + filenames = options[:filenames] + fail ArgumentError, "You must pass filenames with `-f`. See: `#{$PROGRAM_NAME} --help`" if filenames.empty? + filenames.each do |file| + fail ArgumentError, "Can't read file given: #{file}" unless File.readable?(file) + end + + outdir = options[:outdir] + fail ArgumentError, "Can't write to output directory: #{@outdir}" unless File.writable?(outdir) + end + + def parse_execution(argv) + Execution.new(true, parse(argv)) + rescue ArgumentError => ex + Revamp.logger.fatal(ex) + Execution.new(false) + end + + def run_execution(options) + require 'revamp/application' + Execution.new(true, Revamp::Application.new(options).run!) + rescue StandardError => ex + bug = Revamp.bug(ex) + Revamp.logger.fatal("Unexpected error occured, mayby a bug?\n\n#{bug[:message]}\n\n#{bug[:help]}") + Execution.new(false) + end + + def banner + txt = <<-eos +#{Revamp::NAME} v#{Revamp::VERSION} - #{Revamp::SUMMARY} + +#{Revamp::DESCRIPTION} +Usage: #{$PROGRAM_NAME} [options] + eos + txt + end + + def parser + Parser.new do |p| + p.banner = banner + p.version = Revamp::VERSION + p.option :release, 'A RPM release number, by default it is equal to \'1\'', default: '1' + p.option :epoch, 'A RPM epoch number, by default it is equal to \'6\'', default: '6' + p.option( + :outdir, + 'A directory to output converted packages, by default this is current directory: ' + Dir.pwd, + default: Dir.pwd + ) + p.option :filenames, 'Files which will be processed', default: [] + p.option :verbose, 'Should print all information, by default: false', default: false + p.option :cleanup, 'Should temporary files be cleaned up, by default: true', default: true + end + end + + # An execution wrapper + class Execution + attr_reader :value + def initialize(success, value = nil) + @success = success + @value = value + end + + def success? + @success == true + end + end +end diff --git a/lib/revamp/filter/puppetver2rpmreq.rb b/lib/revamp/filter/puppetver2rpmreq.rb new file mode 100644 index 0000000..402f008 --- /dev/null +++ b/lib/revamp/filter/puppetver2rpmreq.rb @@ -0,0 +1,98 @@ +require 'revamp' +require 'revamp/mapper/puppet-name-slugger' + +# A filter that process Puppet dependency into RPM requirements lines +# More info: https://docs.puppetlabs.com/puppet/latest/reference/modules_publishing.html#dependencies-in-metadatajson +# Even more info: https://robots.thoughtbot.com/rubys-pessimistic-operator +class Revamp::Filter::PuppetVerToRpmReq + PUPPETMODULE = 'puppetmodule' + TWIDDLE_WAKKA = '~>' + + attr_accessor :slugger, :slug + + def initialize + @slugger = Revamp::Mapper::PuppetNameSlugger.new + end + + # Filters a Puppet version + # @param [puppetver] Revamp::Model::PuppetDependency + # @return String[] + def filter(puppetver) + @slug = slugger.map(puppetver.name) + reqs = [] + requirements = puppetver.version.requirements + if singular?(requirements) + reqs += filter_single(requirements.first) + else + reqs += filter_many(requirements) + end + reqs + end + + private + + def filter_single(requirement) + reqs = [] + type, version = requirement + if type == TWIDDLE_WAKKA + reqs += filter_twiddle_wakka(version) + elsif semver?(version) + reqs += filter_semver(version) + else + reqs += process(requirement) + end + reqs + end + + def filter_many(requirements) + reqs = [] + requirements.each do |tuple| + reqs += process(tuple) + end + reqs + end + + def modulename + "#{PUPPETMODULE}(#{slug})" + end + + def process(requirement) + type, version = requirement + ["#{modulename} #{type} #{version}"] + end + + def filter_twiddle_wakka(version) + upper_cap = make_upper_cap(version) + reqs = [] + reqs << "#{modulename} >= #{version}" + reqs << "#{modulename} < #{upper_cap}" + reqs + end + + def filter_semver(version) + digital = digitalize(version) + filter_twiddle_wakka(digital) + end + + def make_upper_cap(version) + # take second from back and add increment + upper_cap_digit = version.segments[-2] + 1 + segments = version.segments.dup + segments[-2] = upper_cap_digit + # zero last digit + segments[-1] = 0 + Gem::Version.new(segments.join('.')) + end + + def digitalize(version) + Gem::Version.new(version.to_s.tr('x', '0')) + end + + def semver?(version) + version.to_s.include? 'x' + end + + def singular?(list) + list.size == 1 + end +end diff --git a/lib/revamp/mapper/puppet-name-slugger.rb b/lib/revamp/mapper/puppet-name-slugger.rb new file mode 100644 index 0000000..2164b9d --- /dev/null +++ b/lib/revamp/mapper/puppet-name-slugger.rb @@ -0,0 +1,8 @@ +require 'revamp' + +# This class implements slugification of Puppet module name: 'puppetlabs/stdlib' <-> 'puppetlabs-stdlib' +class Revamp::Mapper::PuppetNameSlugger + def map(slash_name) + slash_name.tr('/', '-') + end +end diff --git a/lib/revamp/model/puppet-module.rb b/lib/revamp/model/puppet-module.rb new file mode 100644 index 0000000..cabe1ff --- /dev/null +++ b/lib/revamp/model/puppet-module.rb @@ -0,0 +1,79 @@ +require 'revamp' +require 'revamp/mapper/puppet-name-slugger' + +# This class describes a puppet dependency +class Revamp::Model::PuppetDependency + attr_accessor :name, :version + + def initialize(hash) + @name = hash['name'] + versions = normalize(hash['version_requirement']) + @version = Gem::Requirement.new(versions) + end + + private + + def normalize(versionreq) + re = /^(([><=~]+)?\s*([\dx]+(?:\.[\dx]+(?:\.[\dx]+)?)?))(.*)/ + m = re.match(versionreq.strip) + first = m[1].strip + second = m[4].strip + reqs = [first] + reqs << second unless second.empty? + reqs + end +end + +# This class describes a puppet module +class Revamp::Model::PuppetModule + def self.puppet_accessor(*vars) + @attributes ||= [] + @attributes.concat vars + attr_accessor(*vars) + end + + class << self + attr_reader :attributes + end + + attr_accessor :files + attr_accessor :metadata + attr_accessor :name + + puppet_accessor :dependencies + puppet_accessor :source + puppet_accessor :author + puppet_accessor :version + puppet_accessor :license + puppet_accessor :summary + puppet_accessor :project_page + + def initialize + @files = {} + @metadata = nil + @dependencies = [] + end + + def add_file(path, content) + @files[path] = content + end + + def attributes + self.class.attributes + end + + def dependencies=(deps) + @dependencies = [] + deps.each do |dep| + @dependencies << Revamp::Model::PuppetDependency.new(dep) + end + end + + def slugname + Revamp::Mapper::PuppetNameSlugger.new.map(name) + end + + def rawname + name.split('/')[-1] + end +end diff --git a/lib/revamp/parser/puppet-tarball.rb b/lib/revamp/parser/puppet-tarball.rb new file mode 100644 index 0000000..2667050 --- /dev/null +++ b/lib/revamp/parser/puppet-tarball.rb @@ -0,0 +1,78 @@ +require 'revamp' +require 'zlib' +require 'json' +require 'rubygems/package' +require 'revamp/model/puppet-module' + +# This class is a parser for Puppet's tarballs format +class Revamp::Parser::PuppetTarball + def initialize(tarball_file) + @tarball = tarball_file + end + + def parse + model = nil + File.open(@tarball, 'rb') do |file| + Zlib::GzipReader.wrap(file) do |gz| + Gem::Package::TarReader.new(gz) do |tar| + model = Revamp::Model::PuppetModule.new + tar.each do |tarfile| + entry = Entry.new(tarfile) + parse_metadata(model, entry) if entry.metadata? + model.add_file(entry.name, entry.content) if entry.file? + end + end + end + end + normalize(model) + end + + private + + def normalize(model) + strip = "#{model.slugname}-#{model.version}/" + model.files = Hash[model.files.map { |file, content| [file.gsub(strip, ''), content] }] + model + end + + def parse_metadata(model, entry) + data = JSON.parse(entry.content) + model.metadata = data + model.name = data['name'].tr('-', '/') if data['name'] + model.attributes.each do |attr| + value = data[attr.to_s] + fail ArgumentError, "No #{attr} module metadata provided for #{name}" unless value + parse_dependencies(attr, value) + model.send(attr.to_s + '=', value) + end + end + + def parse_dependencies(attr, value) + return unless attr == :dependencies + value.tap do |dependencies| + dependencies.each do |dep| + dep['version_requirement'] ||= dep['versionRequirement'] || '>= 0.0.0' + end + end + end + + # An entry from tarball + class Entry + attr_accessor :content + attr_accessor :name + def initialize(tarfile) + @tarfile = tarfile + @name = tarfile.full_name + @content = nil + @content = tarfile.read unless @tarfile.directory? + end + + def metadata? + !@tarfile.directory? && name.end_with?('metadata.json') + end + + def file? + !content.nil? + end + end +end diff --git a/lib/revamp/persister/rpm-spec.erb b/lib/revamp/persister/rpm-spec.erb new file mode 100644 index 0000000..4acea51 --- /dev/null +++ b/lib/revamp/persister/rpm-spec.erb @@ -0,0 +1,28 @@ +Name: <%= name %> +Version: <%= model.version %> +Release: <%= release %> +Summary: <%= model.summary %> +Source0: <%= rpm %>.tar.gz +License: <%= model.license %> +Group: Development +BuildArch: noarch +Provides: puppetmodule(<%= model.slugname %>) +<% if has_requirements %>Requires: <%= requirements %><% end %> +%description +<%= model.summary %> +%prep +%setup +%build +%install +rm -rf $RPM_BUILD_ROOT +mkdir -p ${RPM_BUILD_ROOT}/etc/puppet/modules +cp -r %{_builddir}/<%= rpm %> ${RPM_BUILD_ROOT}%{_sysconfdir}/puppet/modules +mv ${RPM_BUILD_ROOT}%{_sysconfdir}/puppet/modules/<%= rpm %> ${RPM_BUILD_ROOT}%{_sysconfdir}/puppet/modules/<%= model.rawname %> +%clean +%post +%files +%dir %{_sysconfdir}/puppet +%dir %{_sysconfdir}/puppet/modules +%dir %{_sysconfdir}/puppet/modules/<%= model.rawname %> +<% filenames.each do |file| %>%{_sysconfdir}/puppet/modules/<%= model.rawname %>/<%= file %> +<% end %> \ No newline at end of file diff --git a/lib/revamp/persister/rpm.rb b/lib/revamp/persister/rpm.rb new file mode 100644 index 0000000..a6d93b3 --- /dev/null +++ b/lib/revamp/persister/rpm.rb @@ -0,0 +1,156 @@ +require 'revamp' +require 'tmpdir' +require 'erb' +require 'ostruct' +require 'rbconfig' +require 'revamp/filter/puppetver2rpmreq' + +# A main RPM persister +class Revamp::Persister::Rpm + def initialize + @options = nil + end + + attr_accessor :options + + def persist(model) + dir = File.expand_path('~') + workdir = Pathname.new(dir).join('rpmbuild') + builder = Builder.new(model, workdir, options) + builder.make_structure + builder.write_spec + builder.write_sources + produced = builder.produce + builder.cleanup if options[:cleanup] + produced + end + + # A command line executor for command line + class CommandLine + class << self + def execute(command, directory, verbose) + Revamp.logger.debug("Executing: '#{command}' in directory: '#{directory}'") + out = '/dev/null' + out = $stdout if verbose + pid = Process.spawn(command, chdir: directory, out: out, err: out) + Process.wait pid + $? # rubocop:disable SpecialGlobalVars + end + end + end + + # A builder for RPM's packages + class Builder + SOURCES = 'SOURCES' + SPECS = 'SPECS' + RPMS = 'RPMS' + SELFDIR = Pathname.new(__FILE__).dirname + ATTRS = [ + :name, :version, :filename, :rpm, + :model, :tmpdir, :release, :filenames, + :specfile, :has_requirements, + :requirements, :options + ] + ATTRS.each { |attr| attr_accessor(attr) } + + def initialize(model, dir, options) + @options = options + @name = "puppetmodule_#{model.slugname}" + @release = options[:release] + @version = model.version + @filename = "#{name}-#{version}-#{release}.noarch.rpm" + @rpm = "#{name}-#{version}" + @specfile = rpm + '.spec' + @model = model + @tmpdir = dir + @filenames = model.files.keys + @has_requirements = model.dependencies.any? + @requirements = configure_rpm_requirements_line + end + + def configure_rpm_requirements_line + req = [] + model.dependencies.each do |dep| + req += Revamp::Filter::PuppetVerToRpmReq.new.filter(dep) + end + req.join(', ') + end + + def make_structure + FileUtils.mkdir_p(tmpdir.join(SOURCES)) + FileUtils.mkdir_p(tmpdir.join(SPECS)) + end + + def erbize(template, vars) + values = OpenStruct.new(vars).instance_eval { binding } + ERB.new(template).result(values) + end + + def write_spec + tpl = SELFDIR.join('rpm-spec.erb') + values = Hash[ATTRS.map { |key| [key, send(key)] }] + spec = erbize(tpl.read, values) + File.open(specfile_path, 'w') { |file| file.write(spec) } + end + + def write_sources + pathsufix = Pathname.new(rpm) + File.open(sources_tgz_path, 'wb') do |tgz| + Zlib::GzipWriter.wrap(tgz) do |gz| + Gem::Package::TarWriter.new(gz) do |tar| + model.files.each do |file, content| + full = pathsufix.join(file).to_s + tar.add_file_simple(full, 0644, content.length) { |io| io.write(content) } + end + end + end + end + end + + def sources_tgz_path + sources = tmpdir.join(SOURCES) + sources.join("#{rpm}.tar.gz") + end + + def specfile_path + tmpdir.join(SPECS).join(specfile) + end + + def target + outdir = options[:outdir] + Pathname.new(outdir).join(filename) + end + + def produce + Revamp.logger.info("Converting to RPM package #{target}...") + cmd = "rpmbuild -ba #{SPECS}/#{specfile}" + verbose = options[:verbose] + ret = Revamp::Persister::Rpm::CommandLine.execute(cmd, tmpdir, verbose) + fail "RPM Build failed with retcode = #{ret.exitstatus}" unless ret.success? + move_produced + target + end + + def move_produced + produced = tmpdir.join(RPMS).join('noarch').join(filename) + Revamp.logger.debug("Produced RPM in build dir: #{produced}") + FileUtils.mv(produced, target) + end + + def cleanup + arch = RbConfig::CONFIG['arch'].gsub('-linux', '') + cleanup_files [ + sources_tgz_path, specfile_path, tmpdir.join('BUILD').join(rpm), + tmpdir.join('BUILDROOT').join("#{rpm}-#{release}.#{arch}") + ] + end + + def cleanup_files(files) + Revamp.logger.debug("Files to be cleaned up: #{files}") + readable = files.reject { |path| !path.readable? } + readable.each do |path| + path.directory? ? FileUtils.rm_r(path) : path.unlink + end + end + end +end diff --git a/lib/revamp/version.rb b/lib/revamp/version.rb new file mode 100644 index 0000000..e7f6552 --- /dev/null +++ b/lib/revamp/version.rb @@ -0,0 +1,35 @@ +# Top level module for Revamp +module Revamp + # Prepare version + # + # @param desired [String] a desired version + # @return [String] a prepared version + def self.version_prep(desired) + version = desired + if desired.match(/[^0-9\.]+/) + git = `git describe --tags --dirty --always` + version += '.' + git.tr('-', '.') + end + version.strip + end + + # Version for Herald + VERSION = version_prep '1.0.0' + # Lincense for Herald + LICENSE = 'Apache-2.0' + # Project name + NAME = 'Revamp' + # Package (gem) for Herald + PACKAGE = 'revamp' + # A summary info + SUMMARY = 'Converts puppet module file to valid RPM or DEB package' + # A homepage for Herald + HOMEPAGE = 'https://github.com/coi-gov-pl/gem-revamp' + # A description info + DESCRIPTION = <<-eos + This module can convert standard puppet module file in form of tarball to + valid RPM or DEB package with all dependencies as references to other + system packages. The dependencies can be packaged inside the final system + package or just referenced as dependencies. + eos +end diff --git a/revamp.gemspec b/revamp.gemspec new file mode 100644 index 0000000..f47b8c6 --- /dev/null +++ b/revamp.gemspec @@ -0,0 +1,29 @@ +# coding: utf-8 +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) +require 'revamp/version' + +Gem::Specification.new do |spec| + spec.name = Revamp::PACKAGE + spec.version = Revamp::VERSION + spec.authors = [ + 'Centralny Ośrodek Informatyki', + 'Suszyński Krzysztof' + ] + spec.email = ['krzysztof.suszynski@coi.gov.pl'] + spec.summary = Revamp::SUMMARY + spec.description = Revamp::DESCRIPTION + spec.homepage = Revamp::HOMEPAGE + spec.license = Revamp::LICENSE + + spec.files = `git ls-files -z`.split("\x0") + spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } + spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) + spec.require_paths = ['lib'] + + spec.add_development_dependency 'bundler' + spec.add_development_dependency 'rake' + spec.add_runtime_dependency 'micro-optparse', '~> 1.2.0' + + spec.required_ruby_version = '>= 1.9' +end diff --git a/spec/file_matchers.rb b/spec/file_matchers.rb new file mode 100644 index 0000000..2fa5bf0 --- /dev/null +++ b/spec/file_matchers.rb @@ -0,0 +1,5 @@ +RSpec::Matchers.define :be_readable_file do + match do |actual| + File.readable?(actual) + end +end \ No newline at end of file diff --git a/spec/fixtures/coi-sample-0.1.1.tar.gz b/spec/fixtures/coi-sample-0.1.1.tar.gz new file mode 100644 index 0000000..ff64c26 Binary files /dev/null and b/spec/fixtures/coi-sample-0.1.1.tar.gz differ diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..55cb532 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,49 @@ +require 'rspec/its' + +begin +gem 'simplecov' + require 'simplecov' + formatters = [] + formatters << SimpleCov::Formatter::HTMLFormatter + + begin + gem 'coveralls' + require 'coveralls' + formatters << Coveralls::SimpleCov::Formatter if ENV['TRAVIS'] + rescue Gem::LoadError + # do nothing + end + + begin + gem 'codeclimate-test-reporter' + require 'codeclimate-test-reporter' + formatters << CodeClimate::TestReporter::Formatter if (ENV['TRAVIS'] and ENV['CODECLIMATE_REPO_TOKEN']) + rescue Gem::LoadError + # do nothing + end + SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[*formatters] + SimpleCov.start do + add_filter "/spec/" + add_filter "/.vendor/" + add_filter "/vendor/" + add_filter "/gems/" + minimum_coverage 95 + refuse_coverage_drop + end +rescue Gem::LoadError + # do nothing +end + +begin + gem 'pry' + require 'pry' +rescue Gem::LoadError + # do nothing +end + +RSpec.configure do |c| + c.tty = true unless ENV['JENKINS_URL'].nil? + c.mock_with :rspec do |mock| + mock.syntax = [:expect] + end +end diff --git a/spec/unit/revamp/cli_spec.rb b/spec/unit/revamp/cli_spec.rb new file mode 100644 index 0000000..efd588f --- /dev/null +++ b/spec/unit/revamp/cli_spec.rb @@ -0,0 +1,120 @@ +require 'spec_helper' +require 'revamp/cli' +require 'revamp/application' +require 'stringio' + +describe Revamp::CLI do + let(:instance) { described_class.new } + describe '.run!' do + before :each do + @level = Revamp.logger.level + Revamp.logger.level = 100 + end + after :each do + Revamp.logger.level = @level + end + context 'while ARGV is equal to' do + let (:argv) { self.class.description.split(/\s+/) } + subject { instance.run!(argv) } + describe '--invalid-option' do + it do + expect { subject }.to raise_error(SystemExit, 'exit') { |error| + expect(error).not_to be_success + } + end + end + context 'while catching STDOUT' do + before :each do + @stringio = StringIO.new + $stdout = @stringio + end + after :each do + $stdout = STDOUT + end + describe '--help' do + it do + begin + subject + rescue SystemExit + end + expect(@stringio.string).to include('Revamp v', 'Usage:', '-h, --help') + end + it do + expect { subject }.to raise_error(SystemExit, 'exit') { |error| + expect(error).to be_success + } + end + end + describe '--version' do + it do + begin + subject + rescue SystemExit + end + expect(@stringio.string).to match(/^\d+\.\d+\.\d+/) + end + it do + expect { subject }.to raise_error(SystemExit, 'exit') { |error| + expect(error).to be_success + } + end + end + end + + context 'mocking to return' do + before :each do + app = Revamp::Application.new({}) + expect(app).to receive(:run!).and_return(:mock_return) + expect(Revamp::Application).to receive(:new).and_return(app) + end + describe '-f spec/fixtures/coi-sample-0.1.1.tar.gz' do + it { expect(subject).to eq(0) } + end + end + context 'mocking to raise error' do + before :each do + app = Revamp::Application.new({}) + expect(app).to receive(:run!).and_raise(StandardError, 'mock-ex') + expect(Revamp::Application).to receive(:new).and_return(app) + end + describe '-f spec/fixtures/coi-sample-0.1.1.tar.gz' do + it { expect(subject).to eq(1) } + end + end + context 'performing real operation' do + before :each do + require 'revamp/persister/rpm' + ret = double(success?: true) + expect(Revamp::Persister::Rpm::CommandLine).to receive(:execute).and_return(ret) + expect(FileUtils).to receive(:mv) + end + describe '-f spec/fixtures/coi-sample-0.1.1.tar.gz -o /tmp' do + it { expect(subject).to eq(0) } + end + end + end + end + + describe '.parse' do + let (:argv) { eval(self.class.description) } + subject { instance.send(:parse, argv) } + describe([].inspect) do + it { expect { subject }.to raise_error(ArgumentError, /You must pass filenames with `-f`/) } + end + describe(['-f', 'abc-lib-1.0.0.tar.gz'].inspect) do + it { expect { subject }.to raise_error(ArgumentError, 'Can\'t read file given: abc-lib-1.0.0.tar.gz') } + end + describe(['-f', 'spec/fixtures/coi-sample-0.1.1.tar.gz', '-o', Dir.tmpdir].inspect) do + it do + expect(subject).to eq({ + release: "1", + epoch: "6", + outdir: "/tmp", + filenames: ["spec/fixtures/coi-sample-0.1.1.tar.gz"], + verbose: false, + cleanup: true + }) + end + end + end +end \ No newline at end of file diff --git a/spec/unit/revamp/filter/puppetver2rpmreq_spec.rb b/spec/unit/revamp/filter/puppetver2rpmreq_spec.rb new file mode 100644 index 0000000..28bf2f6 --- /dev/null +++ b/spec/unit/revamp/filter/puppetver2rpmreq_spec.rb @@ -0,0 +1,96 @@ +require 'spec_helper' +require 'revamp/model/puppet-module' +require 'revamp/filter/puppetver2rpmreq' + +describe Revamp::Filter::PuppetVerToRpmReq do + subject { described_class.new.filter(puppetver) } + let(:reqname) { 'puppetlabs/stdlib' } + let(:inputhash) do + { + 'name' => reqname, + 'version_requirement' => version_requirement + } + end + let(:puppetver) { Revamp::Model::PuppetDependency.new(inputhash) } + let (:version_requirement) { self.class.description } + + describe '.filter()' do + subject { described_class.new.filter(puppetver) } + + context 'for standard greater or equals cases, for ex.:' do + describe '>=3.0.0 <4.0.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0.0', + 'puppetmodule(puppetlabs-stdlib) < 4.0.0' + ]) + end + end + describe '>= 3.0.0 < 4.0.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0.0', + 'puppetmodule(puppetlabs-stdlib) < 4.0.0' + ]) + end + end + describe '>=3.0.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0.0' + ]) + end + end + describe '>3.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) > 3.0' + ]) + end + end + describe '>3' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) > 3' + ]) + end + end + end + context 'for twiddle-wakka cases, for ex.:' do + describe '~>3.0.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0.0', + 'puppetmodule(puppetlabs-stdlib) < 3.1.0' + ]) + end + end + describe '~>3.0' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0', + 'puppetmodule(puppetlabs-stdlib) < 4.0' + ]) + end + end + end + context 'for semantic versioning cases, for ex.:' do + describe '3.x' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0', + 'puppetmodule(puppetlabs-stdlib) < 4.0' + ]) + end + end + describe '3.0.x' do + it do + expect(subject).to eq([ + 'puppetmodule(puppetlabs-stdlib) >= 3.0.0', + 'puppetmodule(puppetlabs-stdlib) < 3.1.0' + ]) + end + end + end + end +end \ No newline at end of file diff --git a/spec/unit/revamp/parser/puppet-tarball_spec.rb b/spec/unit/revamp/parser/puppet-tarball_spec.rb new file mode 100644 index 0000000..e9bccd2 --- /dev/null +++ b/spec/unit/revamp/parser/puppet-tarball_spec.rb @@ -0,0 +1,53 @@ +require 'spec_helper' +require 'file_matchers' +require 'rspec/its' +require 'revamp/parser/puppet-tarball' + +describe Revamp::Parser::PuppetTarball do + let(:sample_file) { 'spec/fixtures/coi-sample-0.1.1.tar.gz' } + context 'for a sample puppet tarball file' do + it { expect(sample_file).to be_readable_file } + let(:parser) { described_class.new(sample_file) } + + describe '.new' do + it { expect(parser).not_to be_nil } + end + + describe '.parse' do + let(:model) { parser.parse } + it { expect(model).not_to be_nil } + + context 'files' do + subject { model.files } + context 'size' do + let (:size) { subject.size } + it { expect(size).to eq(3) } + end + it { expect(subject.keys).to include 'checksums.json' } + it { expect(subject.keys).to include 'metadata.json' } + it { expect(subject.keys).to include 'manifests/init.pp' } + end + + context 'model' do + subject { model } + it { is_expected.not_to be_nil } + its(:metadata) { is_expected.to be_a(Hash) } + its(:name) { is_expected.to eq('coi/sample') } + its(:summary) { is_expected.to eq 'An example Puppet module' } + its(:version) { is_expected.to eq '0.1.1' } + its(:license) { is_expected.to eq 'Apache-2.0' } + its(:author) { is_expected.to eq 'Krzysztof Suszynski' } + context 'dependencies' do + subject { model.dependencies } + its(:size) { is_expected.to eq(1) } + context 'pop' do + subject { model.dependencies.pop } + its(:name) { is_expected.to eq('puppetlabs/stdlib') } + its(:version) { is_expected.to eq(Gem::Requirement.new(["< 5.0.0", ">= 3.2.0"])) } + end + end + end + + end + end +end \ No newline at end of file diff --git a/spec/unit/revamp/persister/rpm_spec.rb b/spec/unit/revamp/persister/rpm_spec.rb new file mode 100644 index 0000000..160c7b9 --- /dev/null +++ b/spec/unit/revamp/persister/rpm_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' +require 'revamp/persister/rpm' +require 'rbconfig' + +describe Revamp::Persister::Rpm::CommandLine do + describe '#execute' do + before :each do + @level = Revamp.logger.level + Revamp.logger.level = 100 + end + after :each do + Revamp.logger.level = @level + end + let(:is_windows) { RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/ } + let(:command) do + is_windows ? 'dir > nul' : 'true' + end + let(:directory) { Dir.tmpdir } + let(:options) do + { + release: "1", + epoch: "6", + outdir: "/tmp", + filenames: ["spec/fixtures/coi-sample-0.1.1.tar.gz"], + verbose: false, + cleanup: true + } + end + subject { described_class.execute(command, directory, options) } + it { expect(subject).to be_success } + end +end \ No newline at end of file diff --git a/spec/unit/revamp/version_spec.rb b/spec/unit/revamp/version_spec.rb new file mode 100644 index 0000000..17373a6 --- /dev/null +++ b/spec/unit/revamp/version_spec.rb @@ -0,0 +1,13 @@ +require 'spec_helper' +require 'revamp' + +describe Revamp, '.version_prep' do + context 'on stable version v1.2.3' do + subject { Revamp::version_prep '1.2.3' } + it { expect(subject).to eq '1.2.3' } + end + context 'on unstable version v1.2.3.pre' do + subject { Revamp::version_prep '1.2.3.pre' } + it { expect(subject).to match /^1\.2\.3\.pre\.?(?:v\d+\.\d+\.\d+(?:\.\d+\.g)?)?(?:[0-9a-f]{7})?(?:\.dirty)?$/ } + end +end diff --git a/spec/unit/revamp_spec.rb b/spec/unit/revamp_spec.rb new file mode 100644 index 0000000..08479c4 --- /dev/null +++ b/spec/unit/revamp_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' +require 'revamp' + +describe Revamp do + describe '#bug' do + let(:ex) do + ex = nil + begin + raise ArgumentError, 'Sample error' + rescue => detail + ex = detail + end + ex + end + subject { described_class.bug(ex) } + after :each do + Dir.glob(Dir.tmpdir + '/revamp-bug*.log') { |file| Pathname.new(file).unlink } + end + it { is_expected.not_to be_nil } + end +end \ No newline at end of file