Sha256: 4466b60eb6aee93cad74bf32875249b4ec8d86db8bc1aec1421b1aff2d2273fd

Contents?: true

Size: 1.85 KB

Versions: 2

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true

require "yaml"

require "date"

module Bup
  class Config
    @@timeformat = "%Y-%m-%dT%H:%M:%S %z"

    attr_accessor :config, :runtime

    def initialize
      @runtime = {
        "profile" => "default",
        "type" => "full"
      }

      @config = {
        "profiles" => {
          "default" => {
          }
        }
      }
    end

    def load(file)
      c = File.open(file) do |io|
        YAML.safe_load(io)
      end

      Config.merge(@config, c)
    end

    def save(file)
      File.open(file, "w") do |io|
        io.write(YAML.dump(@config))
      end
    end

    def update_lastrun(name)
      date = DateTime.now.new_offset(0)
      set_lastrun(name, date)
    end

    # Return the last run time of the backup or nil if there is none.
    def lastrun(name)
      DateTime.strptime(profile(name)["lastrun"] || "", @@timeformat)
    rescue Date::Error
      nil
    end

    # Return the last run time of the backup or nil if there is none.
    def set_lastrun(name, date)
      profile(name)["lastrun"] = date.strftime(@@timeformat)
    end

    def profile(name)
      @config["profiles"][name] || (raise RuntimeError("No such profile #{name}."))
    end

    def self.merge(c1, c2)
      (c1.keys + c2.keys)
        .each_with_object({}) do |r, l|
          l[r] = 1
        end.each_key do |key|
          v1 = c1[key]
          v2 = c2[key]
          if v1.nil?
            if v2.nil?
              # nop
            else
              c1[key] = v2
            end
          elsif v2.nil?
            # Nop - c1[key] already equals v1.
          elsif v1.instance_of?(Array) && v2.instance_of?(Array)
            c1[key] = v1 + v2
          elsif v1.instance_of?(Hash) && v2.instance_of?(Hash)
            c1[key] = merge(v1, v2)
          elsif !v2.nil?
            c1[key] = v2
          end
        end
      c1
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bup-0.2.0 lib/bup/config.rb
bup-0.1.0 lib/bup/config.rb