1#' Info on current GitHub user and token
2#'
3#' Reports wallet name, GitHub login, and GitHub URL for the current
4#' authenticated user, the first bit of the token, and the associated scopes.
5#'
6#' Get a personal access token for the GitHub API from
7#' <https://github.com/settings/tokens> and select the scopes necessary for your
8#' planned tasks. The `repo` scope, for example, is one many are likely to need.
9#'
10#' On macOS and Windows it is best to store the token in the git credential
11#' store, where most GitHub clients, including gh, can access it. You can
12#' use the gitcreds package to add your token to the credential store:
13#'
14#' ```r
15#' gitcreds::gitcreds_set()
16#' ```
17#'
18#' See <https://gh.r-lib.org/articles/managing-personal-access-tokens.html>
19#' and <https://usethis.r-lib.org/articles/articles/git-credentials.html>
20#' for more about managing GitHub (and generic git) credentials.
21#'
22#' On other systems, including Linux, the git credential store is
23#' typically not as convenient, and you might want to store your token in
24#' the `GITHUB_PAT` environment variable, which you can set in your
25#' `.Renviron` file.
26#'
27#' @inheritParams gh
28#'
29#' @return A `gh_response` object, which is also a `list`.
30#' @export
31#'
32#' @examplesIf identical(Sys.getenv("IN_PKGDOWN"), "true")
33#' gh_whoami()
34#'
35#' @examplesIf FALSE
36#' ## explicit token + use with GitHub Enterprise
37#' gh_whoami(.token = "8c70fd8419398999c9ac5bacf3192882193cadf2",
38#'           .api_url = "https://github.foobar.edu/api/v3")
39
40gh_whoami <- function(.token = NULL, .api_url = NULL, .send_headers = NULL) {
41  .token <- .token %||% gh_token(.api_url)
42  if (isTRUE(.token == "")) {
43    message("No personal access token (PAT) available.\n",
44            "Obtain a PAT from here:\n",
45            "https://github.com/settings/tokens\n",
46            "For more on what to do with the PAT, see ?gh_whoami.")
47    return(invisible(NULL))
48  }
49  res <- gh(endpoint = "/user", .token = .token,
50            .api_url = .api_url, .send_headers = .send_headers)
51  scopes <- attr(res, "response")[["x-oauth-scopes"]]
52  res <- res[c("name", "login", "html_url")]
53  res$scopes <- scopes
54  res$token <- format(gh_pat(.token))
55  ## 'gh_response' class has to be restored
56  class(res) <- c("gh_response", "list")
57  res
58}
59