Sha256: 42fb82d82be1a27878f5669f1d5bbec739f5dc106d13535c16f3e9a0f33b34ea

Contents?: true

Size: 1.88 KB

Versions: 6

Compression:

Stored size: 1.88 KB

Contents

# frozen_string_literal: true

require "yaml"

require "date"

module Bup
  # Configuration management.
  class Config

    attr_accessor :config, :runtime

    def initialize
      @timeformat = "%Y-%m-%dT%H:%M:%S %z"
      @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

6 entries across 6 versions & 1 rubygems

Version Path
bup-0.8.0 lib/bup/config.rb
bup-0.7.0 lib/bup/config.rb
bup-0.6.0 lib/bup/config.rb
bup-0.5.0 lib/bup/config.rb
bup-0.4.0 lib/bup/config.rb
bup-0.3.0 lib/bup/config.rb