Skip to content

Commit

Permalink
include PAT information in URL
Browse files Browse the repository at this point in the history
Signed-off-by: sZma5a <sZma5a@geekers.io>
  • Loading branch information
sZma5a authored and sZma5a committed Jul 30, 2023
1 parent 8a8f812 commit 634ff91
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
33 changes: 32 additions & 1 deletion pkg/git/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package git
import (
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -48,6 +49,10 @@ type client struct {
cacheDir string
mu sync.Mutex
repoLocks map[string]*sync.Mutex
pat struct {
userName string
userToken string
}

gitEnvs []string
gitEnvsByRepo map[string][]string
Expand Down Expand Up @@ -90,6 +95,15 @@ func WithEmail(e string) Option {
}
}

func WithPAT(userName, userToken string) Option {
return func(c *client) {
if userName != "" && userToken != "" {
c.pat.userName = userName
c.pat.userToken = userToken
}
}
}

// NewClient creates a new CLient instance for cloning git repositories.
// After using Clean should be called to delete cache data.
func NewClient(opts ...Option) (Client, error) {
Expand Down Expand Up @@ -131,10 +145,15 @@ func (c *client) Clone(ctx context.Context, repoID, remote, branch, destination
)
)

remote, err := includePatRemote(ctx, remote, c.pat.userName, c.pat.userToken)
if err != nil {
return nil, err
}

c.lockRepo(repoID)
defer c.unlockRepo(repoID)

_, err := os.Stat(repoCachePath)
_, err = os.Stat(repoCachePath)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
Expand Down Expand Up @@ -260,6 +279,18 @@ func (c *client) envsForRepo(remote string) []string {
return append(envs, c.gitEnvs...)
}

func includePatRemote(ctx context.Context, remote, userName, userToken string) (string, error) {
if userName == "" || userToken == "" {
return remote, nil
}
u, err := parseGitURL(remote)
if err != nil {
return "", fmt.Errorf("failed to include pat: %v", err)
}
u.User = url.UserPassword(userName, userToken)
return u.String(), nil
}

func runGitCommand(ctx context.Context, execPath, dir string, envs []string, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, execPath, args...)
cmd.Dir = dir
Expand Down
7 changes: 7 additions & 0 deletions pkg/git/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,13 @@ func (g gitCommander) addCommit(filename string, content string) error {
})
}

func TestCloneUsingPAT(t *testing.T) {
ctx := context.Background()
url, err := includePatRemote(ctx, "https://example.com/org/repo", "test-user", "test-token")
require.NoError(t, err)
assert.Equal(t, "https://test-user:test-token@example.com/org/repo", url)
}

func TestRetryCommand(t *testing.T) {
var (
ranCount = 0
Expand Down

0 comments on commit 634ff91

Please sign in to comment.