Skip to content

Commit

Permalink
fix: fixes from testing
Browse files Browse the repository at this point in the history
  • Loading branch information
didroe committed Nov 21, 2023
1 parent 0bd5589 commit b3adf8d
Show file tree
Hide file tree
Showing 16 changed files with 145 additions and 894 deletions.
4 changes: 4 additions & 0 deletions internal/commands/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,10 @@ func Run(ctx context.Context, opts flag.Options) (err error) {
return fmt.Errorf("failed to get git context: %w", err)
}

if opts.Diff && gitContext == nil {
return errors.New("--diff option requires a git repository")
}

if !opts.Quiet {
outputhandler.StdErrLog("Loading rules")
}
Expand Down
27 changes: 21 additions & 6 deletions internal/commands/process/gitrepository/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/google/go-github/github"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
"gopkg.in/yaml.v3"

"github.com/bearer/bearer/internal/flag"
"github.com/bearer/bearer/internal/git"
Expand All @@ -33,11 +34,15 @@ type Context struct {
}

func NewContext(options *flag.Options) (*Context, error) {
rootDir := git.GetRoot(options.Target)
if rootDir == "" {
if options.IgnoreGit {
return nil, nil
}

rootDir, err := git.GetRoot(options.Target)
if rootDir == "" || err != nil {
return nil, err
}

currentBranch, err := getCurrentBranch(options, rootDir)
if err != nil {
return nil, fmt.Errorf("error getting current branch name: %w", err)
Expand All @@ -48,7 +53,7 @@ func NewContext(options *flag.Options) (*Context, error) {
return nil, fmt.Errorf("error getting default branch name: %w", err)
}

baseBranch, err := getBaseBranch(options)
baseBranch, err := getBaseBranch(options, defaultBranch)
if err != nil {
return nil, fmt.Errorf("error getting base branch name: %w", err)
}
Expand Down Expand Up @@ -87,7 +92,7 @@ func NewContext(options *flag.Options) (*Context, error) {
fullName = urlInfo.FullName
}

return &Context{
context := &Context{
RootDir: rootDir,
CurrentBranch: currentBranch,
DefaultBranch: defaultBranch,
Expand All @@ -101,7 +106,12 @@ func NewContext(options *flag.Options) (*Context, error) {
Name: name,
FullName: fullName,
HasUncommittedChanges: hasUncommittedChanges,
}, nil
}

contextYAML, _ := yaml.Marshal(context)
log.Debug().Msgf("git context:\n%s", contextYAML)

return context, nil
}

func getCurrentBranch(options *flag.Options, rootDir string) (string, error) {
Expand All @@ -125,7 +135,7 @@ func getDefaultBranch(options *flag.Options, rootDir string) (string, error) {
return git.GetDefaultBranch(rootDir)
}

func getBaseBranch(options *flag.Options) (string, error) {
func getBaseBranch(options *flag.Options, defaultBranch string) (string, error) {
if !options.Diff {
return "", nil
}
Expand All @@ -134,6 +144,11 @@ func getBaseBranch(options *flag.Options) (string, error) {
return options.DiffBaseBranch, nil
}

if defaultBranch != "" {
log.Debug().Msgf("using default branch %s for diff base branch", defaultBranch)
return defaultBranch, nil
}

return "", errors.New(
"couldn't determine base branch for diff scanning. " +
"please set the 'BEARER_DIFF_BASE_BRANCH' environment variable",
Expand Down
28 changes: 18 additions & 10 deletions internal/commands/process/gitrepository/gitrepository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gitrepository

import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
Expand All @@ -21,7 +22,6 @@ import (
type Repository struct {
ctx context.Context
config settings.Config
rootPath,
targetPath,
gitTargetPath string
context *Context
Expand All @@ -38,7 +38,7 @@ func New(ctx context.Context, config settings.Config, targetPath string, context
return nil, fmt.Errorf("failed to get relative target: %w", err)
}

log.Debug().Msgf("git target: [%s/]%s", context.RootDir, gitTargetPath)
log.Debug().Msgf("git target: [%s]/%s", context.RootDir, gitTargetPath)

repository := &Repository{
ctx: ctx,
Expand Down Expand Up @@ -78,13 +78,13 @@ func (repository *Repository) fetchMergeBaseCommit() error {

log.Debug().Msgf("merge base commit: %s", hash)

if git.CommitPresent(repository.rootPath, hash) {
return nil
if isPresent, err := git.CommitPresent(repository.context.RootDir, hash); isPresent || err != nil {
return err
}

log.Debug().Msgf("merge base commit not present, fetching")

if err := git.FetchRef(repository.ctx, repository.rootPath, hash); err != nil {
if err := git.FetchRef(repository.ctx, repository.context.RootDir, hash); err != nil {
return err
}

Expand All @@ -97,9 +97,13 @@ func (repository *Repository) getCurrentFiles(
ignore *ignore.FileIgnore,
goclocResult *gocloc.Result,
) (*files.List, error) {
if repository.context.CurrentCommitHash == "" {
return &files.List{}, nil
}

var headFiles []files.File

gitFiles, err := git.ListTree(repository.rootPath, repository.context.CurrentCommitHash)
gitFiles, err := git.ListTree(repository.context.RootDir, repository.context.CurrentCommitHash)
if err != nil {
return nil, err
}
Expand All @@ -125,7 +129,7 @@ func (repository *Repository) getDiffFiles(
renames := make(map[string]string)
chunks := make(map[string]git.Chunks)

filePatches, err := git.Diff(repository.rootPath, repository.context.BaseCommitHash)
filePatches, err := git.Diff(repository.context.RootDir, repository.context.BaseCommitHash)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -176,7 +180,11 @@ func (repository *Repository) WithBaseBranch(body func() error) error {
return nil
}

if err := git.Switch(repository.rootPath, repository.context.BaseCommitHash, true); err != nil {
if repository.context.HasUncommittedChanges {
return errors.New("uncommitted changes found in your repository. commit or stash changes your changes and retry")
}

if err := git.Switch(repository.context.RootDir, repository.context.BaseCommitHash, true); err != nil {
return fmt.Errorf("error switching to base branch: %w", err)
}

Expand All @@ -196,10 +204,10 @@ func (repository *Repository) WithBaseBranch(body func() error) error {

func (repository *Repository) restoreCurrent() error {
if repository.context.CurrentBranch == "" {
return git.Switch(repository.rootPath, repository.context.CurrentCommitHash, true)
return git.Switch(repository.context.RootDir, repository.context.CurrentCommitHash, true)
}

return git.Switch(repository.rootPath, repository.context.CurrentBranch, false)
return git.Switch(repository.context.RootDir, repository.context.CurrentBranch, false)
}

func (repository *Repository) fileFor(
Expand Down
14 changes: 13 additions & 1 deletion internal/git/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import (
func GetDefaultBranch(dir string) (string, error) {
name, err := getRevParseAbbrevRef(dir, "origin/HEAD")
if err != nil {
if strings.Contains(err.Error(), "unknown revision") {
return "", nil
}

return "", err
}

Expand All @@ -17,10 +21,18 @@ func GetDefaultBranch(dir string) (string, error) {
// GetCurrentBranch gets the branch name. It is blank when detached.
func GetCurrentBranch(dir string) (string, error) {
name, err := getRevParseAbbrevRef(dir, "HEAD")
if name == "HEAD" || err != nil {
if err != nil {
if strings.Contains(err.Error(), "unknown revision") {
return "", nil
}

return "", err
}

if name == "HEAD" {
return "", nil
}

return name, nil
}

Expand Down
102 changes: 0 additions & 102 deletions internal/git/checkout.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package git

import (
"context"
"fmt"
)

func Switch(rootDir, ref string, detach bool) error {
Expand All @@ -18,104 +17,3 @@ func Switch(rootDir, ref string, detach bool) error {
append(args, ref)...,
)
}

func checkoutFiles(rootDir, ref string, filenames []string) error {
cmd := logAndBuildCommand(
context.TODO(),
"-c",
"advice.detachedHead=false",
"checkout",
ref,
"--pathspec-from-file=-",
"--pathspec-file-nul",
)
cmd.Dir = rootDir

stdin, err := cmd.StdinPipe()
if err != nil {
return err
}

logWriter := &debugLogWriter{}
cmd.Stdout = logWriter
cmd.Stderr = logWriter

if err := cmd.Start(); err != nil {
cmd.Cancel() //nolint:errcheck
return err
}

for _, filename := range filenames {
_, err := stdin.Write([]byte(filename))
if err != nil {
cmd.Cancel() //nolint:errcheck
return err
}

_, err = stdin.Write([]byte{0})
if err != nil {
cmd.Cancel() //nolint:errcheck
return err
}
}

if err := stdin.Close(); err != nil {
cmd.Cancel() //nolint:errcheck
return err
}

if err := cmd.Wait(); err != nil {
cmd.Cancel() //nolint:errcheck
return newError(err, logWriter.AllOutput())
}

// Using pathspec with checkout doesn't update the HEAD ref so do it manually
return basicCommand(context.TODO(), rootDir, "update-ref", "HEAD", ref)
}

func fetchBlobsForRange(rootDir, firstCommitSHA, lastCommitSHA string, filenames []string) error {
objectIDs, err := getObjectIDsForRangeFiles(rootDir, firstCommitSHA, lastCommitSHA, filenames)
if err != nil {
return err
}

return fetchBlobs(rootDir, objectIDs)
}

// Fetches the given list of objects/blobs.
//
// There's no command in git that does this directly but we can get the desired
// behaviour by creating a pack and throwing it away
func fetchBlobs(rootDir string, objectIDs []string) error {
cmd := logAndBuildCommand(context.TODO(), "pack-objects", "--progress", "--stdout")
cmd.Dir = rootDir

stdin, err := cmd.StdinPipe()
if err != nil {
return err
}

logWriter := &debugLogWriter{}
cmd.Stderr = logWriter

if err := cmd.Start(); err != nil {
cmd.Cancel() //nolint:errcheck
return err
}

for _, objectID := range objectIDs {
fmt.Fprintln(stdin, objectID)
}

if err := stdin.Close(); err != nil {
cmd.Cancel() //nolint:errcheck
return err
}

if err := cmd.Wait(); err != nil {
cmd.Cancel() //nolint:errcheck
return newError(err, logWriter.AllOutput())
}

return nil
}
Loading

0 comments on commit b3adf8d

Please sign in to comment.