From cb26fd867021c48bcb0f1a98f1aa93e09a11ec62 Mon Sep 17 00:00:00 2001 From: ChristopherHX Date: Sun, 9 Feb 2025 04:24:32 +0100 Subject: [PATCH] Use gh auth token for default GITHUB_TOKEN secret (#2651) * initial version --- cmd/root.go | 10 ++++++++++ pkg/gh/gh.go | 40 ++++++++++++++++++++++++++++++++++++++++ pkg/gh/gh_test.go | 11 +++++++++++ 3 files changed, 61 insertions(+) create mode 100644 pkg/gh/gh.go create mode 100644 pkg/gh/gh_test.go diff --git a/cmd/root.go b/cmd/root.go index f2bf329..140e11b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -29,6 +29,7 @@ import ( "github.com/nektos/act/pkg/artifacts" "github.com/nektos/act/pkg/common" "github.com/nektos/act/pkg/container" + "github.com/nektos/act/pkg/gh" "github.com/nektos/act/pkg/model" "github.com/nektos/act/pkg/runner" ) @@ -412,6 +413,15 @@ func newRunCommand(ctx context.Context, input *Input) func(*cobra.Command, []str log.Debugf("Loading secrets from %s", input.Secretfile()) secrets := newSecrets(input.secrets) _ = readEnvs(input.Secretfile(), secrets) + hasGitHubToken := false + for k := range secrets { + if strings.EqualFold(k, "GITHUB_TOKEN") { + hasGitHubToken = true + } + } + if !hasGitHubToken { + secrets["GITHUB_TOKEN"], _ = gh.GetToken(ctx, "") + } log.Debugf("Loading vars from %s", input.Varfile()) vars := newSecrets(input.vars) diff --git a/pkg/gh/gh.go b/pkg/gh/gh.go new file mode 100644 index 0000000..9ba23eb --- /dev/null +++ b/pkg/gh/gh.go @@ -0,0 +1,40 @@ +package gh + +import ( + "bufio" + "bytes" + "context" + "os/exec" +) + +func GetToken(ctx context.Context, workingDirectory string) (string, error) { + var token string + + // Locate the 'gh' executable + path, err := exec.LookPath("gh") + if err != nil { + return "", err + } + + // Command setup + cmd := exec.CommandContext(ctx, path, "auth", "token") + cmd.Dir = workingDirectory + + // Capture the output + var out bytes.Buffer + cmd.Stdout = &out + + // Run the command + err = cmd.Run() + if err != nil { + return "", err + } + + // Read the first line of the output + scanner := bufio.NewScanner(&out) + if scanner.Scan() { + token = scanner.Text() + } + + return token, nil +} diff --git a/pkg/gh/gh_test.go b/pkg/gh/gh_test.go new file mode 100644 index 0000000..578f0d3 --- /dev/null +++ b/pkg/gh/gh_test.go @@ -0,0 +1,11 @@ +package gh + +import ( + "context" + "testing" +) + +func TestGetToken(t *testing.T) { + token, _ := GetToken(context.TODO(), "") + t.Log(token) +}