adding support for an environment variable

This commit is contained in:
Samantha Marshall 2017-03-11 14:51:54 -05:00
commit 32ed21695b
No known key found for this signature in database
GPG key ID: DF782CB74434EFA2

View file

@ -16,6 +16,7 @@ type
const const
ApiKeyFile = "github_api_token" ApiKeyFile = "github_api_token"
ApiTokenEnvironmentVariable = "NIMBLE_GITHUB_API_TOKEN"
proc userAborted() = proc userAborted() =
raise newException(NimbleError, "User aborted the process.") raise newException(NimbleError, "User aborted the process.")
@ -25,11 +26,7 @@ proc createHeaders(a: Auth): string =
"Content-Type: application/x-www-form-urlencoded\c\L" & "Content-Type: application/x-www-form-urlencoded\c\L" &
"Accept: */*\c\L") "Accept: */*\c\L")
proc getGithubAuth(cfg: Config): Auth = proc requestNewToken(cfg: Config): string =
try:
result.token = readFile(cfg.nimbleDir / ApiKeyFile)
except IOError:
display("Info:", "Please create a new personal access token on Github in" & display("Info:", "Please create a new personal access token on Github in" &
" order to allow Nimble to fork the packages repository.", " order to allow Nimble to fork the packages repository.",
priority = HighPriority) priority = HighPriority)
@ -40,8 +37,25 @@ proc getGithubAuth(cfg: Config): Auth =
"https://github.com/settings/tokens/new", priority = HighPriority) "https://github.com/settings/tokens/new", priority = HighPriority)
sleep(3000) sleep(3000)
openDefaultBrowser("https://github.com/settings/tokens/new") openDefaultBrowser("https://github.com/settings/tokens/new")
result.token = promptCustom("Personal access token?", "").strip() let token = promptCustom("Personal access token?", "").strip()
writeFile(cfg.nimbleDir / ApiKeyFile, result.token) # inform the user that their token will be written to disk
let token_write_path = cfg.nimbleDir / ApiKeyFile
display("Info:", "Writing access token to file:" & token_write_path,
priority = HighPriority)
writeFile(token_write_path, token)
return token
proc getGithubAuth(cfg: Config): Auth =
# always prefer the environment variable to asking for a new one
if existsEnv(ApiTokenEnvironmentVariable):
result.token = getEnv(ApiTokenEnvironmentVariable)
else:
# try to read from disk, if it cannot be found write a new one
try:
result.token = readFile(cfg.nimbleDir / ApiKeyFile)
except IOError:
result.token = requestNewToken(cfg)
let resp = getContent("https://api.github.com/user", let resp = getContent("https://api.github.com/user",
extraHeaders=createHeaders(result)).parseJson() extraHeaders=createHeaders(result)).parseJson()