Class: GitHubPr::FileToken

Inherits:
Token
  • Object
show all
Defined in:
lib/github-pr/token.rb

Instance Method Summary collapse

Methods inherited from Token

create

Constructor Details

#initialize(token_file_path) ⇒ FileToken

Returns a new instance of FileToken.



42
43
44
# File 'lib/github-pr/token.rb', line 42

def initialize(token_file_path)
	@token_file_path = token_file_path
end

Instance Method Details

#create_dir_if_neededObject



78
79
80
81
82
83
# File 'lib/github-pr/token.rb', line 78

def create_dir_if_needed
	token_dir = File.dirname(@token_file_path)
	unless File.directory?(token_dir)
		FileUtils.mkdir_p(token_dir)
	end
end

#get(regenerate: false) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/github-pr/token.rb', line 93

def get(regenerate: false)
			create_dir_if_needed()

			if regenerate
puts 'Token has been reveked'
FileUtils.rm(@token_file_path)
			end

			token = token_from_file()
			if token
return token
			end
			puts 'Token is nil regenerating'

			token = token_from_github()
  File.open(@token_file_path, 'w+') {|file| file.write token}
  return token
end

#get_username_and_passObject



85
86
87
88
89
90
91
# File 'lib/github-pr/token.rb', line 85

def get_username_and_pass
	cli = HighLine.new

	github_username = cli.ask("GitHub Username: ")
	github_password = cli.ask("GitHub Password(Only one time): ") { |q| q.echo = "*" }
	return {:login => github_username, :password => github_password}
end

#retry_logic(count, initial_note) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/github-pr/token.rb', line 50

def retry_logic(count, initial_note)
	note = initial_note
	count.times do |i|
    	begin
    		yield(note)
    		break
    	rescue Exception => e 
    		if i == 8
    			raise 'Please remove some personal tokens from your github account, you have too many tokens'
    		end
    		if e.errors[0][:code] != "already_exists" || e.errors[0][:field] != "description"
    			raise e 
    		else
    			note = initial_note + (i + 2).to_s
    		end
    	end
    end
end

#token_from_fileObject



46
47
48
# File 'lib/github-pr/token.rb', line 46

def token_from_file
	File.exist?(@token_file_path) ? IO.read(@token_file_path) : nil
end

#token_from_githubObject



69
70
71
72
73
74
75
76
# File 'lib/github-pr/token.rb', line 69

def token_from_github
	client = Octokit::Client.new(get_username_and_pass())
    # trying 9 different notes, if all is failed, 
    # then you have to remove some of them
    retry_logic(9, 'CLI uses') do |note|
    	return client.create_authorization(:scopes => ["repo", "user"], :note => note)[:token]
    end
end