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.



34
35
36
# File 'lib/github-pr/token.rb', line 34

def initialize(token_file_path)
  @token_file_path = token_file_path
end

Instance Method Details

#create_dir_if_neededObject



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

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: regenerate = false) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/github-pr/token.rb', line 85

def get(regenerate: regenerate = false)
      create_dir_if_needed()

      if regenerate
FileUtils.rm(@token_file_path)
      end

      token = token_from_file()
      if token
return token
      end

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

#get_username_and_passObject



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

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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/github-pr/token.rb', line 42

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



38
39
40
# File 'lib/github-pr/token.rb', line 38

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

#token_from_githubObject



61
62
63
64
65
66
67
68
# File 'lib/github-pr/token.rb', line 61

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