#!/usr/bin/env ruby # Copyright (c) 2020 Jerome Arbez-Gindre # frozen_string_literal: true require('csv') require('defmastership') require('gli') module DefMastership # The start of everything ! class App extend GLI::App program_desc 'Tool to handle Asciidoctor definition extension' version DefMastership::VERSION subcommand_option_handling :normal arguments :strict # desc 'Describe some switch here' # switch [:s,:switch] # desc 'Describe some flag here' # default_value 'the default' # arg_name 'The name of the argument' # flag [:f,:flagname] pre do |_global, _command, _options, _args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end post do |_global, _command, _options, _args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |_exception| # Error logic here # return false to skip default error handling true end desc 'Export the definition database in CSV' arg_name 'asciidoctor_files' command :export, :exp, :e do |c| c.flag(%i[separator sep s], default_value: ',', desc: 'CSV separator') c.switch(%i[no-fail], desc: 'Exit succes even in case of wrong explicit checksum') c.action do |_global_options, options, args| my_doc = DefMastership::Document.new my_doc.parse_file_with_preprocessor(args[0]) output_file = args[0].sub(/\.adoc$/, '.csv') DefMastership::CSVFormatter.new(my_doc, options['separator']).export_to(output_file) if my_doc.wrong_explicit_checksum? my_doc.definitions.each do |definition| next if definition.wrong_explicit_checksum.nil? warn("warning: #{definition.reference} has a wrong explicit checksum (should be #{definition.sha256})") end exit 1 unless options[:"no-fail"] end end end desc 'Apply one or more modifications' arg_name 'asciidoctor_files' command :modify, :mod, :m do |c| c.flag( %i[modifications mod m], must_match: /(?:[\w-]+)(?:,[\w-]+)*/, default_value: 'all', desc: 'comma separated list of modifications to apply' ) c.flag(%i[modifications-file mf], default_value: 'modifications.yml', desc: 'modifications description file') c.flag(%i[changes-summary s], default_value: 'changes.csv', desc: 'generates a change summary in a CSV file') c.action do |_global_options, options, args| changer = BatchModifier.new( YAML.load_file(options[:'modifications-file']), args.map { |afile| [afile, File.open(afile).read] }.to_h ) changer.apply(options[:modifications]) changer.adoc_texts.each do |adoc_file, adoc_text| File.open(adoc_file, 'w') { |f| f.write(adoc_text) } end File.open(options[:'modifications-file'], 'w') { |f| f.write(changer.config.to_yaml) } unless options['changes-summary'].nil? CSV.open(options['changes-summary'], 'wb') do |csv| csv << %w[Modifier Was Becomes] changer.changes.each { |row| csv << row } end end end end end end exit(DefMastership::App.run(ARGV))