diff --git a/mpbackup b/mpbackup index b3369f3..e6ac7a4 100644 --- a/mpbackup +++ b/mpbackup @@ -18,6 +18,11 @@ def unset_restic_vars ENV.delete('RESTIC_PASSWORD') end +def error(exit_status, message) + STDERR.puts("Error: #{message}") + exit exit_status +end + unset_restic_vars options = {} @@ -50,8 +55,7 @@ else end if !Pathname.new(config_file).exist? then - STDERR.puts "Config file #{config_file} has not been found!" - exit 1 + error(1, "Config file #{config_file} has not been found!") end def do_backup(config) @@ -74,8 +78,7 @@ def do_backup(config) puts("Command: #{backup_command.join(' ')}") system(*backup_command) if $?.exitstatus > 0 - STDERR.puts 'Failed to do backup.' - exit 1 + error(1, 'Failed to do backup.') end puts 'Checking restic repo …' @@ -83,8 +86,7 @@ def do_backup(config) puts("Command: #{check_command.join(' ')}") system(*check_command) if $?.exitstatus > 0 - STDERR.puts "Checking restic repository #{ENV['RESTIC_REPOSITORY']} failed." - exit 1 + error(1, "Checking restic repository #{ENV['RESTIC_REPOSITORY']} failed.") end if config.dig('forget', 'enable') @@ -97,8 +99,7 @@ def do_backup(config) # Data will only be deleted when `restic prune` is executed or when # `restic forget` is called with `--prune`. if $?.exitstatus > 0 - STDERR.puts "Forgetting snapshots failed." - exit 1 + error(1, "Forgetting snapshots failed.") end end @@ -113,11 +114,13 @@ if config_names.empty? "configuration from the file (‘#{configs.dig(0, 'name')}’)." do_backup(configs[0]) else - config_names.each do |config_name| - configs.each do |config| - if config_name == config['name'] - do_backup(config) - end + config_hash = configs.map {|c| [c['name'], c]}.to_h + config_names.each do |name| + if !config_hash.key? name + error(1, "Cannot find configuration ‘#{name}’.") end end + config_names.each do |config_name| + do_backup(config_hash[config_name]) + end end