@@ -32,22 +32,29 @@ gist_auth <- function(app = gistr_app, reauth = FALSE) {
3232 if (exists(" auth_config" , envir = cache ) && ! reauth ) {
3333 return (auth_header(cache $ auth_config $ auth_token ))
3434 }
35- # if nothing cached, use gitcreds. gitcreds will retrieve PAT stored as an
36- # GITHUB_PAT environment variable or one set with gitcreds::gitcreds_set()
37- # TODO use tryCatch here to customize error message to be more helpful
38- # cli::cli_alert_warning("Please set {.field GITHUB_PAT} in your {.file .Renviron} or use the {.pkg gitcreds}
39- creds <- try(gitcreds :: gitcreds_get())
40- if (! inherits(creds , " try-error" )) {
41- token <- creds $ password
42- } else if (interactive()) { # if no gitcreds, try interactive authentication
43- # try oauth direct
44- endpt <- httr :: oauth_endpoints(" github" )
45- auth <- httr :: oauth2.0_token(endpt , app , scope = " gist" , cache = ! reauth )
46- token <- auth $ credentials $ access_token
47- } else {
48- stop(" In non-interactive environments, please set GITHUB_PAT env to a GitHub" ,
49- " access token (https://help.github.com/articles/creating-an-access-token-for-command-line-use)" ,
50- call. = FALSE )
35+ # if nothing cached, use gitcreds to retrieve PAT stored as an GITHUB_PAT
36+ # environment variable or set with gitcreds::gitcreds_set(). gitcreds_get()
37+ # errors when no PAT is found, but we want to try one more method, so silence
38+ # this error and return NULL.
39+ creds <- tryCatch(
40+ error = function (cnd ) {
41+ return (NULL )
42+ },
43+ gitcreds :: gitcreds_get()
44+ )
45+ token <- creds $ password
46+ # TODO would be great to check here that token has "gist" scope
47+ # if no token, or invalid token and interactive, try direct oauth
48+ if ((is.null(token ) | ! valid_gh_pat(token ))) {
49+ if (interactive()) {
50+ endpt <- httr :: oauth_endpoints(" github" )
51+ auth <- httr :: oauth2.0_token(endpt , app , scope = " gist" , cache = ! reauth )
52+ token <- auth $ credentials $ access_token
53+ } else {
54+ stop(" In non-interactive environments, please set GITHUB_PAT env to a GitHub" ,
55+ " access token (https://help.github.com/articles/creating-an-access-token-for-command-line-use)" ,
56+ call. = FALSE )
57+ }
5158 }
5259
5360 # cache auth config
@@ -65,3 +72,11 @@ gistr_app <- httr::oauth_app(
6572 " 89ecf04527f70e0f9730" ,
6673 " 77b5970cdeda925513b2cdec40c309ea384b74b7"
6774)
75+
76+ # inspired by https://github.com/r-lib/gh/blob/main/R/gh_token.R
77+ valid_gh_pat <- function (x ) {
78+ ! is.null(x ) & (
79+ grepl(" ^(gh[pousr]_[A-Za-z0-9_]{36,251}|github_pat_[A-Za-z0-9_]{36,244})$" , x ) ||
80+ grepl(" ^[[:xdigit:]]{40}$" , x )
81+ )
82+ }
0 commit comments