|
| 1 | +package bitbucket |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/url" |
| 7 | + |
| 8 | + "github.com/ktrysmt/go-bitbucket" |
| 9 | + v1 "k8s.io/api/core/v1" |
| 10 | + |
| 11 | + "github.com/argoproj-labs/gitops-promoter/api/v1alpha1" |
| 12 | + "github.com/argoproj-labs/gitops-promoter/internal/scms" |
| 13 | +) |
| 14 | + |
| 15 | +// GitAuthenticationProvider implements the scms.GitOperationsProvider interface for Bitbucket. |
| 16 | +type GitAuthenticationProvider struct { |
| 17 | + scmProvider v1alpha1.GenericScmProvider |
| 18 | + secret *v1.Secret |
| 19 | + client *bitbucket.Client |
| 20 | +} |
| 21 | + |
| 22 | +var _ scms.GitOperationsProvider = &GitAuthenticationProvider{} |
| 23 | + |
| 24 | +// NewBitbucketGitAuthenticationProvider creates a new instance of GitAuthenticationProvider for Bitbucket. |
| 25 | +func NewBitbucketGitAuthenticationProvider(scmProvider v1alpha1.GenericScmProvider, secret *v1.Secret) (*GitAuthenticationProvider, error) { |
| 26 | + client, err := GetClient(*secret) |
| 27 | + if err != nil { |
| 28 | + return nil, fmt.Errorf("failed to create Bitbucket Client: %w", err) |
| 29 | + } |
| 30 | + |
| 31 | + return &GitAuthenticationProvider{ |
| 32 | + scmProvider: scmProvider, |
| 33 | + secret: secret, |
| 34 | + client: client, |
| 35 | + }, nil |
| 36 | +} |
| 37 | + |
| 38 | +// GetGitHttpsRepoUrl constructs the HTTPS URL for a Bitbucket repository based on the provided GitRepository object. |
| 39 | +func (_ GitAuthenticationProvider) GetGitHttpsRepoUrl(repo v1alpha1.GitRepository) string { |
| 40 | + var repoUrl string |
| 41 | + repoUrl = fmt.Sprintf("https://bitbucket.com/%s/%s.git", repo.Spec.Bitbucket.Workspace, repo.Spec.Bitbucket.Repository) |
| 42 | + if _, err := url.Parse(repoUrl); err != nil { |
| 43 | + return "" |
| 44 | + } |
| 45 | + return repoUrl |
| 46 | +} |
| 47 | + |
| 48 | +// GetToken retrieves the Bitbucket access token from the secret. |
| 49 | +func (bb GitAuthenticationProvider) GetToken(ctx context.Context) (string, error) { |
| 50 | + return string(bb.secret.Data["token"]), nil |
| 51 | +} |
| 52 | + |
| 53 | +// GetUser returns a placeholder user for Bitbucket authentication. |
| 54 | +func (_ GitAuthenticationProvider) GetUser(ctx context.Context) (string, error) { |
| 55 | + return "x-token-auth", nil |
| 56 | +} |
| 57 | + |
| 58 | +// GetClient creates a new Bitbucket client using the provided secret and domain. |
| 59 | +func GetClient(secret v1.Secret) (*bitbucket.Client, error) { |
| 60 | + token := string(secret.Data["token"]) |
| 61 | + if token == "" { |
| 62 | + return nil, fmt.Errorf("secret %q is missing required data key 'token'", secret.Name) |
| 63 | + } |
| 64 | + |
| 65 | + client := bitbucket.NewOAuthbearerToken(token) |
| 66 | + |
| 67 | + return client, nil |
| 68 | +} |
0 commit comments