Sha256: 9b1fc9c43dd0ee3ec1c0e8ecbfdb7bf9a11fe113dcbf1ee93eb30f7046e84d6a

Contents?: true

Size: 1.76 KB

Versions: 2

Compression:

Stored size: 1.76 KB

Contents

require "json"

module Imap::Backup
  module Configuration; end

  class Configuration::Store
    CONFIGURATION_DIRECTORY = File.expand_path("~/.imap-backup")

    attr_reader :pathname

    def self.default_pathname
      File.join(CONFIGURATION_DIRECTORY, "config.json")
    end

    def self.exist?(pathname = default_pathname)
      File.exist?(pathname)
    end

    def initialize(pathname = self.class.default_pathname)
      @pathname = pathname
    end

    def path
      File.dirname(pathname)
    end

    def save
      mkdir_private path
      remove_modified_flags
      remove_deleted_accounts
      File.open(pathname, "w") { |f| f.write(JSON.pretty_generate(data)) }
      FileUtils.chmod 0600, pathname
    end

    def accounts
      data[:accounts]
    end

    def modified?
      accounts.any? { |a| a[:modified] || a[:delete] }
    end

    def debug?
      data[:debug]
    end

    def debug=(value)
      data[:debug] = [true, false].include?(value) ? value : false
    end

    private

    def data
      return @data if @data
      if File.exist?(pathname)
        Utils.check_permissions pathname, 0600
        contents = File.read(pathname)
        @data = JSON.parse(contents, symbolize_names: true)
      else
        @data = {accounts: []}
      end
      @data[:debug] = false unless @data.include?(:debug)
      @data[:debug] = false unless [true, false].include?(@data[:debug])
      @data
    end

    def remove_modified_flags
      accounts.each { |a| a.delete(:modified) }
    end

    def remove_deleted_accounts
      accounts.reject! { |a| a[:delete] }
    end

    def mkdir_private(path)
      if !File.directory?(path)
        FileUtils.mkdir path
      end
      if Utils::stat(path) != 0700
        FileUtils.chmod 0700, path
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
imap-backup-1.3.0 lib/imap/backup/configuration/store.rb
imap-backup-1.2.3 lib/imap/backup/configuration/store.rb