forked from edgarjs/alfred-github-repos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github
executable file
·215 lines (183 loc) · 5.28 KB
/
github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env ruby
require './xml_builder'
require 'json'
require 'net/http'
require 'cgi'
class InvalidToken < StandardError; end
class Github
def initialize
@base_uri = "https://api.github.com"
@cache_file = ".repositoriescache"
@token_file = ".auth_token"
end
def store_token(token)
if token && token.length > 0
File.open(@token_file, 'w') do |f|
f.write(token)
end
rebuild_user_repos_cache
end
end
def search_repo(query)
repos = load_and_cache_user_repos
results = repos.select do |repo|
repo['name'] =~ Regexp.new(query, 'i')
end
results += search_all_repos(query) if query =~ /\//
results.uniq
end
def rebuild_user_repos_cache
File.delete(@cache_file) if File.exists?(@cache_file)
cache_all_repos_for_user
end
def test_authentication
load_token
return false if !@token || @token.length == 0
res = get "/"
!res.has_key?('error')
end
private
def load_token
@token = File.read(@token_file).strip if File.exists?(@token_file)
end
def load_and_cache_user_repos
if File.exists?(@cache_file)
JSON.parse(File.read(@cache_file))
else
cache_all_repos_for_user
end
end
# TODO: probably will do a search request instead of fetching all at once
def cache_all_repos_for_user
raise InvalidToken unless test_authentication
repos = []
repos += get_user_repos
get_user_orgs.each do |org|
repos += get_org_repos( org['login'] )
end
File.open(@cache_file, 'w') do |f|
f.write repos.to_json
end
repos
end
def get_user_repos
res = get "/user/repos"
if res.is_a?(Array)
res.map do |repo|
{ 'name' => repo['full_name'], 'url' => repo['html_url'] }
end
else # TODO: handle error
[]
end
end
def get_user_orgs
res = get "/user/orgs"
if res.is_a?(Array)
res.map do |org|
{ 'login' => org['login'] }
end
else # TODO: handle error
[]
end
end
def get_org_repos(org)
res = get "/orgs/#{org}/repos"
if res.is_a?(Array)
res.map do |repo|
{ 'name' => repo['full_name'], 'url' => repo['html_url'] }
end
else # TODO: handle error
[]
end
end
def search_all_repos(query)
return [] if !query || query.length == 0
raise InvalidToken unless test_authentication
parts = query.split('/', 2)
if parts.length == 1 and parts[0].length > 0
res = get "/search/repositories", { "q" => query }
if res.is_a?(Hash) and res.has_key?('items')
res['items'].map do |repo|
{ 'name' => repo['full_name'], 'url' => repo['html_url'] }
end
else # TODO: handle error
[]
end
elsif parts.length == 2 and parts[0].length > 0
user = parts[0]
userQuery = parts[1]
res = get "/users/#{user}/repos"
if res.is_a?(Array)
repos = res.select do |repo|
repo['name'] =~ Regexp.new(userQuery, 'i')
end
repos.map do |repo|
{ 'name' => repo['full_name'], 'url' => repo['html_url'] }
end
else # TODO: handle error
[]
end
else
[]
end
end
def get(path, params = {})
params['per_page'] = 100 # Note: 100 is the max. - see https://developer.github.com/v3/#pagination
qs = params.map {|k, v| "#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join("&")
uri = URI("#{@base_uri}#{path}?#{qs}")
json_all = []
begin
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Get.new(uri)
req['Accept'] = "application/vnd.github.v3+json"
req['Authorization'] = "token #{@token}"
http.request(req)
end
json = JSON.parse(res.body)
if not res.kind_of? Net::HTTPSuccess
return { 'error' => json['message'] }
end
if json.is_a?(Array) # result is paged
json_all.concat json
# See if more pages must be retrieved by testing for and extracting the link header's "next" URL.
# See https://developer.github.com/guides/traversing-with-pagination/
uri = URI((res['link'].match /<([^>]+)>;\s*rel="next"/)[1]) rescue nil
break if uri.nil?
else # result is not an array and therefore not paged
json_all = json
break
end
end while true
json_all
end
end
query = ARGV[0]
github = Github.new
begin
if query == '--update'
github.rebuild_user_repos_cache
elsif query == '--auth'
github.store_token(ARGV[1])
else
results = github.search_repo(query || '')
output = XmlBuilder.build do |xml|
xml.items do
if results.length > 0
results.each do |repo|
xml.item Item.new(repo['url'], repo['url'], repo['name'], repo['url'], 'yes')
end
else
xml.item Item.new(nil, query, 'Update the repository cache and try again.', 'Rebuilds your local cache from GitHub, then searches again; gh-update to rebuild anytime.', 'yes', 'FE3390F7-206C-45C4-94BB-5DD14DE23A1B.png')
end
end
end
puts output
end
rescue InvalidToken
output = XmlBuilder.build do |xml|
xml.items do
xml.item Item.new('gh-error', 'gh-auth ', "Missing or invalid token!", "Please set your token with gh-auth. ↩ to go there now.", 'yes')
end
end
puts output
end