Skip to content

Instantly share code, notes, and snippets.

@alexpop
Last active November 28, 2017 23:57
Show Gist options
  • Save alexpop/ed416844a7e634116792 to your computer and use it in GitHub Desktop.
Save alexpop/ed416844a7e634116792 to your computer and use it in GitHub Desktop.
Read user's github gists
require 'net/http'
require 'json'
require 'set'
# Method to return the content of the local db as a set
def read_db(file_db)
unless File.exists?(file_db)
return nil
end
read_gists = Set.new
file = File.new(file_db, 'r')
while (line = file.gets)
read_gists.add(line.strip)
end
file.close
return read_gists
end
# Method to create or update the local db
def update_db(file_db, gists_set)
File.open(file_db, "w") do |f|
f.write(gists_set.to_a.join("\n"))
end
end
# Do a basic input validation
if ARGV[0] =~ /^[A-Za-z0-9-]+$/
user = ARGV[0]
else
puts "Usage: ruby #{$0} GITHUB_USERNAME"
puts "Where GITHUB_USENAME may only contain alphanumeric characters or single hyphens"
exit 2
end
GISTS_DB = "#{user}_gists.txt"
uri = URI("https://api.github.com/users/#{user}/gists")
# TO-DO error handling and retries
content = Net::HTTP.get(uri)
gists = JSON.parse(content)
current_gists = Set.new
gists.each do |gist|
current_gists.add(gist['id'])
end
previous_gists = read_db(GISTS_DB)
# Enter here only if the database is not yet created
unless previous_gists
update_db(GISTS_DB, current_gists)
# First execution, returning 'changes' exit code
exit 1
end
if current_gists == previous_gists
# No gist changes, returning 'no changes' without updating GISTS_DB
exit 0
else
update_db(GISTS_DB, current_gists)
# Found gist changes, returning 'changes' exit code
exit 1
end
@alexpop
Copy link
Author

alexpop commented Nov 28, 2017

test commend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment