module ActiveScripts module Packages class Base < ActiveScripts::Base # INFO: ActiveScripts::Packages::Base contains code that is # shared between all package files. COMMANDS = [:install, :upgrade, :uninstall] OPTIONS = [:dry_run, :verbose] attr_accessor :command, :options def initialize(command, options={}) @command = command @options = options end def self.execute(command, options={}) new(command, options).execute end def execute assert_valid_command! assert_valid_options! assert_valid_user! send(@command) end private def assert_valid_command! unless COMMANDS.include?(@command) raise ArgumentError, "Unknown package command: #{@command.inspect}. Valid package commands are: #{COMMANDS.map(&:inspect).join(', ')}" end end def assert_valid_options! @options.each_key do |option| unless OPTIONS.include?(option) raise ArgumentError, "Unknown package option: #{option.inspect}. Valid package options are: #{OPTIONS.map(&:inspect).join(', ')}" end end end def option_dry_run? @options.fetch(:dry_run, false) end def option_verbose? @options.fetch(:verbose, false) end def addendum_path!(file) output = File.dirname(__FILE__) output = output.shift("/packages") "#{output}/addendums/#{file}" end def execute_command!(command) say(" Executing: '#{command}'") if option_dry_run? || option_verbose? option_dry_run? ? (output = error = "") : (output, error, status = Open3.capture3("#{command}")) return(error.blank? ? output : error) end def package_installed?(command: "brew list", excludes: nil, includes: nil) begin output, error, status = Open3.capture3("#{command}") output = output.squish if includes.nil? && excludes.nil? output.present? else includes.nil? ? [excludes].flatten.any? { |str| output.exclude?(str) } : [includes].flatten.any? { |str| output.include?(str) } end rescue return(false) end end def package_output?(output, excludes: nil, includes: nil) output = output.squish if includes.nil? && excludes.nil? output.blank? else includes.nil? ? [excludes].flatten.any? { |str| output.exclude?(str) } : [includes].flatten.any? { |str| output.include?(str) } end end def notify_package_exists! say_warning(" [!] PackageError") say_warning(" - The package is already installed.") end def notify_package_missing! say_error(" [!] PackageError") say_error(" - The package is not installed.") end def notify_package_unavailable! say_warning(" [!] PackageError") say_warning(" - The package is not available for your operating system.") end end end end