Created
September 1, 2021 16:25
-
-
Save manveru/f8cc711b3b5d235745ab36de0eff45fe to your computer and use it in GitHub Desktop.
Parse ~/.netrc in Crystal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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