Skip to content

Instantly share code, notes, and snippets.

@manveru
Created September 1, 2021 16:25
Show Gist options
  • Save manveru/f8cc711b3b5d235745ab36de0eff45fe to your computer and use it in GitHub Desktop.
Save manveru/f8cc711b3b5d235745ab36de0eff45fe to your computer and use it in GitHub Desktop.
Parse ~/.netrc in Crystal
require "string_scanner"
# A partial parser of the netrc format
# No support for default, account, or macdef)
class Netrc
def self.parse
file = File.read(File.expand_path("~/.netrc", home: true))
s = StringScanner.new(file)
machines = {} of String => Hash(String, String)
machine = ""
until s.eos?
if s.scan(/(default|macdef)\s*/)
raise "Unsupported token '#{s[1]}' in .netrc"
end
if s.scan(/machine\s+(\S+)/)
machine = s[1]
machines[machine] = {} of String => String
end
if s.scan(/(\S+)\s+(\S+)/)
raise "Unexpected token '#{s[1]}' in .netrc, expected machine" if machine == ""
machines[machine][s[1]] = s[2]
end
s.scan(/\s*/)
end
machines
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment