Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ brew install brows
```

## Configuration:

* (Required) Set the `GITHUB_OAUTH_TOKEN` environment variable to a [GitHub PAT](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) for access to the GitHub API.
* (Required) A GitHub auth token is required. It can be set by the `GITHUB_OAUTH_TOKEN` environment variable to a [GitHub PAT](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) or, if the environment variable is not set, Brows will attempt to use the token from the [GitHub CLI](https://cli.github.com/) (`gh auth token`) if available (CLI installed and logged in).
* (Optional) Create a config file at `$HOME/.config/brows.yml` and set a `default_org` key, like:

```
Expand Down
7 changes: 3 additions & 4 deletions brows.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package main

import "github.com/rubysolo/brows/util"

import (
"context"
"fmt"
Expand Down Expand Up @@ -464,10 +466,7 @@ func main() {
repo = parts[1]
}

token := os.Getenv("GITHUB_OAUTH_TOKEN")
if token == "" {
log.Fatal("no GITHUB_OAUTH_TOKEN provided.")
}
token := util.GetGHToken()

ctx := context.Background()
ts := oauth2.StaticTokenSource(
Expand Down
34 changes: 34 additions & 0 deletions util/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package util

import (
"log"
"os"
"os/exec"
"strings"
)

const GITHUB_TOKEN_ENV = "GITHUB_OAUTH_TOKEN"
const GH_CLI_COMMAND = "gh auth token"

// GetToken retrieves a GitHub access token from the environment variable `GITHUB_OAUTH_TOKEN`.
// If the environment variable is not set, it attempts to obtain the token by executing
// the GitHub CLI `gh auth token` command. If both methods fail, the function terminates
// the program with a fatal error, providing guidance for the user.
func GetGHToken() string {
token := os.Getenv(GITHUB_TOKEN_ENV)
if token != "" {
return token
}


command_arr := strings.Split(GH_CLI_COMMAND, " ")
out, err := exec.Command(command_arr[0], command_arr[1:]...).Output()
if err != nil {
log.Fatal("GITHUB_OAUTH_TOKEN not set and failed to retrieve token from gh CLI: ", err, "\nPlease set GITHUB_OAUTH_TOKEN or run 'gh auth login'")
}
trimmed := strings.TrimSpace(string(out))
if trimmed == "" {
log.Fatal("GITHUB_OAUTH_TOKEN not set and gh CLI did not return a token.\nPlease set GITHUB_OAUTH_TOKEN or run 'gh auth login'")
}
return trimmed
}
Loading