Skip to content

Instantly share code, notes, and snippets.

@plambert
Created August 5, 2021 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plambert/470dd2ddb979e214afd3c25343a28e72 to your computer and use it in GitHub Desktop.
Save plambert/470dd2ddb979e214afd3c25343a28e72 to your computer and use it in GitHub Desktop.
trying to handle missing or malformed json config files in crystal
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