-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
github_uploader.rb
86 lines (69 loc) · 2.51 KB
/
github_uploader.rb
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
require "rest-client"
require "github_api"
class GithubUploader
def initialize(login, username, repo, token=nil, root=Dir.pwd)
@login = login
@username = username
@repo = repo
@root = root
@token = token || check_token
end
def authorized?
!!@token
end
def token_path
File.expand_path(".github-upload-token", @root)
end
def check_token
File.exist?(token_path) ? File.open(token_path, "rb").read : nil
end
def authorize
return if authorized?
puts "There is no file named .github-upload-token in this folder. This file holds the OAuth token needed to communicate with GitHub."
puts "You will be asked to enter your GitHub password so a new OAuth token will be created."
print "GitHub Password: "
system "stty -echo" # disable echoing of entered chars so password is not shown on console
pw = STDIN.gets.chomp
system "stty echo" # enable echoing of entered chars
puts ""
# check if the user already granted access for Ember.js Uploader by checking the available authorizations
response = RestClient.get "https://#{@login}:#{pw}@api.github.com/authorizations"
JSON.parse(response.to_str).each do |auth|
if auth["note"] == "Ember.js Uploader"
# user already granted access, so we reuse the existing token
@token = auth["token"]
end
end
## we need to create a new token
unless @token
payload = {
:scopes => ["public_repo"],
:note => "Ember.js Uploader",
:note_url => "https://github.com/#{@username}/#{@repo}"
}
response = RestClient.post "https://#{@login}:#{pw}@api.github.com/authorizations", payload.to_json, :content_type => :json
@token = JSON.parse(response.to_str)["token"]
end
# finally save the token into .github-upload-token
File.open(".github-upload-token", 'w') {|f| f.write(@token)}
end
def upload_file(filename, description, file)
return false unless authorized?
gh = Github.new :user => @username, :repo => @repo, :oauth_token => @token
# remvove previous download with the same name
gh.repos.downloads.list @username, @repo do |download|
if filename == download.name
gh.repos.downloads.delete @username, @repo, download.id
break
end
end
# step 1
hash = gh.repos.downloads.create @username, @repo,
"name" => filename,
"size" => File.size(file),
"description" => description
# step 2
gh.repos.downloads.upload hash, file
return true
end
end