Skip to content

Commit

Permalink
fix: hard coded ref as master
Browse files Browse the repository at this point in the history
This fix allows auto detecting the ref if `commit-ref` is not set.

Signed-off-by: Noel Georgi <[email protected]>
  • Loading branch information
frezbo committed Sep 21, 2022
1 parent 9023e3a commit 6380738
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
40 changes: 40 additions & 0 deletions cmd/conform/enforce.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"

git "github.com/go-git/go-git/v5"
"github.com/spf13/cobra"

"github.com/siderolabs/conform/internal/enforcer"
Expand Down Expand Up @@ -41,6 +42,14 @@ var enforceCmd = &cobra.Command{

if commitRef := cmd.Flags().Lookup("commit-ref").Value.String(); commitRef != "" {
opts = append(opts, policy.WithCommitRef(commitRef))
} else {
mainBranch, err := detectMainBranch()
if err != nil {
return fmt.Errorf("failed to detect main branch: %w", err)
}
if mainBranch != "" {
opts = append(opts, policy.WithCommitRef(fmt.Sprintf("refs/heads/%s", mainBranch)))
}
}

if baseBranch := cmd.Flags().Lookup("base-branch").Value.String(); baseBranch != "" {
Expand All @@ -61,3 +70,34 @@ func init() {
enforceCmd.Flags().String("base-branch", "", "base branch to compare with")
rootCmd.AddCommand(enforceCmd)
}

func detectMainBranch() (string, error) {
mainBranch := "main"

repo, err := git.PlainOpen(".")
if err != nil {
// not a git repo, ignore
return "", nil //nolint:nilerr
}

c, err := repo.Config()
if err != nil {
return "", fmt.Errorf("failed to get repository configuration: %w", err)
}

rawConfig := c.Raw

const branchSectionName = "branch"

branchSection := rawConfig.Section(branchSectionName)
for _, b := range branchSection.Subsections {
remote := b.Option("remote")
if remote == git.DefaultRemoteName {
mainBranch = b.Name

break
}
}

return mainBranch, nil
}
1 change: 0 additions & 1 deletion internal/policy/policy_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ func WithRevisionRange(o string) Option {
func NewDefaultOptions(setters ...Option) *Options {
opts := &Options{
CommitMsgFile: nil,
CommitRef: "refs/heads/master",
}

for _, setter := range setters {
Expand Down

0 comments on commit 6380738

Please sign in to comment.