class Abt::GitConfig

Attributes

namespace[R]
scope[R]

Public Class Methods

new(scope = "local", namespace = "") click to toggle source
# File lib/abt/git_config.rb, line 9
def initialize(scope = "local", namespace = "")
  @namespace = namespace

  raise ArgumentError, 'scope must be "local" or "global"' unless %w[local global].include?(scope)

  @scope = scope
end

Public Instance Methods

[](key) click to toggle source
# File lib/abt/git_config.rb, line 31
def [](key)
  get(key)
end
[]=(key, value) click to toggle source
# File lib/abt/git_config.rb, line 35
def []=(key, value)
  set(key, value)
end
available?() click to toggle source
# File lib/abt/git_config.rb, line 17
def available?
  unless instance_variables.include?(:available)
    @available = begin
      success = false
      Open3.popen3(availability_check_call) do |_i, _o, _e, thread|
        success = thread.value.success?
      end
      success
    end
  end

  @available
end
clear(output: nil) click to toggle source
# File lib/abt/git_config.rb, line 50
def clear(output: nil)
  raise UnsafeNamespaceError, "Keys can only be cleared within a namespace" if namespace.empty?

  keys.each do |key|
    output&.puts "Clearing #{scope}: #{key_with_namespace(key)}"
    self[key] = nil
  end
end
full_keys() click to toggle source
# File lib/abt/git_config.rb, line 44
def full_keys
  ensure_scope_available!

  `git config --#{scope} --get-regexp --name-only ^#{namespace}`.lines.map(&:strip)
end
keys() click to toggle source
# File lib/abt/git_config.rb, line 39
def keys
  offset = namespace.length + 1
  full_keys.map { |key| key[offset..-1] }
end

Private Instance Methods

availability_check_call() click to toggle source
# File lib/abt/git_config.rb, line 61
def availability_check_call
  "git config --#{scope} -l"
end
ensure_scope_available!() click to toggle source
# File lib/abt/git_config.rb, line 65
def ensure_scope_available!
  return if available?

  raise StandardError, "Local configuration is not available outside a git repository"
end
get(key) click to toggle source
# File lib/abt/git_config.rb, line 75
def get(key)
  ensure_scope_available!

  git_value = `git config --#{scope} --get #{key_with_namespace(key).inspect}`.strip
  git_value.empty? ? nil : git_value
end
key_with_namespace(key) click to toggle source
# File lib/abt/git_config.rb, line 71
def key_with_namespace(key)
  namespace.empty? ? key : "#{namespace}.#{key}"
end
set(key, value) click to toggle source
# File lib/abt/git_config.rb, line 82
def set(key, value)
  ensure_scope_available!

  if value.nil? || value.empty?
    `git config --#{scope} --unset #{key_with_namespace(key).inspect}`
    nil
  else
    `git config --#{scope} --replace-all #{key_with_namespace(key).inspect} #{value.inspect}`
    value
  end
end