<commit_before>#!/usr/bin/env ruby

require 'keychain'

keychain = ENV['DOCK0_KEYCHAIN'] || Keychain.default.path

api_key = Keychain.open keychain
api_key = api_key.generic_passwords.where(service: 'linode-api')
fail('Failed to load keychain') unless api_key.first
puts api_key.first.password<commit_msg>update getkey to handle initial loading, fixes #29<commit_after>#!/usr/bin/env ruby

require 'keychain'
require 'highline/import'
require 'linodeapi'

keychain_path = ENV['DOCK0_KEYCHAIN'] || Keychain.default.path
KEYCHAIN = Keychain.open keychain_path
SERVICE = 'linode-api'

def load_from_keychain
  entry = KEYCHAIN.generic_passwords.where(service: SERVICE).first
  fail(KeyError, 'Keychain item not found') unless entry
  entry.password
end

def save_to_keychain(key)
  KEYCHAIN.generic_passwords.create(service: SERVICE, password: key)
end

def load_from_prompt
  prompt = HighLine.new(STDIN, STDERR)
  username = prompt.ask('Linode Manager Username: ')
  password = prompt.ask('Linode Manager Password: ') { |q| q.echo = '*' }
  twofactor = prompt.ask('Linode Manager 2FA token: ')
  api = LinodeAPI::Raw.new(
    username: username,
    password: password,
    token: twofactor)
  api.apikey
end

begin
  key = load_from_keychain
rescue KeyError
  key = load_from_prompt
  save_to_keychain(key)
end

fail('Failed to load credentials') unless key
puts key
{'fraction_non_alphanumeric': 0.10688140556368961, 'fraction_numerical': 0.0036603221083455345, 'mean_word_length': 5.358139534883721, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6094107', 'n_tokens_mistral': 479, 'n_tokens_neox': 467, 'n_words': 111}