Created
August 5, 2021 20:19
-
-
Save plambert/470dd2ddb979e214afd3c25343a28e72 to your computer and use it in GitHub Desktop.
trying to handle missing or malformed json config files in crystal
This file contains 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
def self.create( | |
client_id : String = {{ read_file("#{__DIR__}/../client_id.secret").chomp }}, | |
client_secret : String = {{ read_file("#{__DIR__}/../client_secret.secret").chomp }}, | |
config_file : String | Path = Path["~/.config/dropbox-cli/dropbox-cli.json"].expand(home: true) | |
) | |
config_data = begin | |
self.read_config(config_file) | |
rescue e : File::NotFoundError | |
Dir.mkdir_p(config_file.parent) | |
self.write_config(config_file, DEFAULT_CONFIGURATION) | |
DEFAULT_CONFIGURATION | |
end | |
config : Hash(String, String) = begin | |
cfg = Hash(String, String).new | |
pull = JSON::PullParser.new(config_data) | |
pull.read_object do |key| | |
case key | |
when "token", "client_id", "client_secret" | |
cfg[key] = pull.read_string | |
else | |
STDERR.puts "#{config_file}: #{key}: unknown key, ignoring" | |
end | |
end | |
cfg | |
rescue e : JSON::ParseException | |
STDERR.puts "#{config_file}: #{e.message}" | |
Process.exit(1) | |
end | |
pp config | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment