Sha256: 2588bdb36b41bce817f4ec218dc0fbacca5b5a83c7e74a4e08f669f75fc2d4dc

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

require "yaml"
require "fileutils"
require "gemsmith/authenticators/ruby_gems"
require "gemsmith/authenticators/basic"

module Gemsmith
  # Generates gem credentials for RubyGems and/or alternative servers.
  class Credentials
    attr_reader :key, :url

    def self.default_key
      :rubygems_api_key
    end

    def self.default_url
      "https://rubygems.org"
    end

    def self.file_path
      File.join ENV.fetch("HOME"), ".gem", "credentials"
    end

    def self.authenticators
      [Authenticators::RubyGems, Authenticators::Basic]
    end

    def initialize key: self.class.default_key, url: self.class.default_url, shell: Bundler::UI::Shell.new
      @key = key
      @url = url
      @shell = shell
      @credentials = load_credentials
    end

    def authenticator
      selected = self.class.authenticators.detect { |auth| auth.url.include? url }
      selected ? selected : Authenticators::Basic
    end

    def value
      String credentials[key]
    end

    def valid?
      credentials? && !String(credentials[key]).empty?
    end

    def create
      return if valid?

      login = shell.ask %(What is your "#{url}" login?)
      password = shell.ask %(What is your "#{url}" password?)
      new_credentials = credentials.merge key => authenticator.new(login, password).authorization

      FileUtils.mkdir_p File.dirname self.class.file_path
      File.open(self.class.file_path, "w") { |file| file << YAML.dump(new_credentials) }
      FileUtils.chmod(0o600, self.class.file_path)
    end

    private

    attr_reader :credentials, :shell

    def credentials?
      File.exist? self.class.file_path
    end

    def load_credentials
      Hash YAML.load_file(self.class.file_path)
    rescue
      {}
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gemsmith-8.0.0 lib/gemsmith/credentials.rb