Sha256: e5177d04c95cd796994597de081cb13a7de3e33af28fda9876e8cfb5db7ca1db

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

require "optparse"
require "json"
require "yaml"
require "fileutils"
require "securerandom"

require_relative "2pass/version"

module TwoPass
  VAULT_DIR = "#{Dir.home}/.2pass"

  class << self
    def create_symlink(vault_name, target_path)
      FileUtils.mkdir_p(VAULT_DIR)
      symlink_path = "#{VAULT_DIR}/#{vault_name}.yml"

      if File.exist?(symlink_path)
        puts "Symlink already exists: #{symlink_path}"
      else
        File.symlink(target_path, symlink_path)
        puts "Created symlink: #{symlink_path} -> #{target_path}"
      end
    end

    def load_vault(vault_name)
      file_path = "#{VAULT_DIR}/#{vault_name}.yml"
      return [] unless File.exist?(file_path)

      YAML.load_file(file_path, symbolize_names: true) || []
    rescue Psych::SyntaxError => e
      STDERR.puts "Error parsing YAML file: #{e.message}"
      []
    end

    def save_vault(vault_name, data)
      FileUtils.mkdir_p(VAULT_DIR)
      file_path = "#{VAULT_DIR}/#{vault_name}.yml"
      File.write(file_path, YAML.dump(data))
    end

    def list_content(vault_name)
      vault = load_vault(vault_name)
      JSON.pretty_generate(vault)
    end

    def add_secret(vault_name, id, value)
      new_secret = {
        id: id,
        value: value,
        uuid: SecureRandom.uuid
      }
      data = load_vault(vault_name)
      existing_entry_id = data.find_index { |hash| hash[:id] == new_secret[:id] }
      if existing_entry_id
        raise "The secret already exists"
      end
      data << new_secret
      save_vault(vault_name, data)
    end

    def get_secret(vault_name, id)
      vault = load_vault(vault_name)
      entry = vault.find { |hash| hash[:id] == id }
      if entry
        entry[:value]
      else
        raise "Entry not found"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
2pass-1.1.0 lib/2pass.rb