Sha256: 003b1be69aa8dbafc264a882140371156423e9499f83cba96ebfdac552a48ae2

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

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

require_relative "2pass/version"

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

  def self.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 self.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 self.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 self.list_content(vault_name)
    vault = load_vault(vault_name)
    JSON.pretty_generate(vault)
  end

  def self.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 self.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

Version data entries

1 entries across 1 versions & 1 rubygems

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