Skip to content

Commit

Permalink
derive git branch name automatically when possible, eat the errors fo…
Browse files Browse the repository at this point in the history
…r external calls to rely on the locally sourced information when needed
  • Loading branch information
can3p committed Apr 5, 2024
1 parent 8c9f871 commit dc779c6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
4 changes: 2 additions & 2 deletions cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,21 @@ func GenerateCommand() *cobra.Command {

var projectName string
var githubRepo string
var gitBranch string

if err != nil {
log.Println(err)
} else {
projectName = p.Name
githubRepo = p.GithubRepo
gitBranch = p.GitBranch
}

path, err := os.Getwd()
if err != nil {
log.Println(err)
}

var gitBranch string = "main"

generateCmd.Flags().String("project-name", projectName, "Project and binary name, current folder name by default")
generateCmd.Flags().String("github-repo", githubRepo, "Github repo in form user/repo")
generateCmd.Flags().String("git-branch", gitBranch, "Git branch to refer in the readme")
Expand Down
29 changes: 28 additions & 1 deletion internal/project/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package project

import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand All @@ -13,6 +14,7 @@ import (
type Project struct {
Name string
GithubRepo string
GitBranch string
}

func ResolveProjectFromCwd() (*Project, error) {
Expand All @@ -26,12 +28,19 @@ func ResolveProjectFromCwd() (*Project, error) {
currentRepo, err := resolveGitRepo()

if err != nil {
return nil, errors.Wrapf(err, "Failed to resolve github repo")
fmt.Fprintln(os.Stderr, "Failed to resolve github repo, it will have to be specified manually")
}

currentBranch, err := resolveGitBranch()

if err != nil {
fmt.Fprintln(os.Stderr, "Failed to resolve current git branch, it will have to be specified manually")
}

return &Project{
Name: cwdFolder,
GithubRepo: currentRepo,
GitBranch: currentBranch,
}, nil
}

Expand All @@ -54,3 +63,21 @@ func resolveGitRepo() (string, error) {

return repo, nil
}

func resolveGitBranch() (string, error) {
cmd := exec.Command("git", "branch", "--no-color", "--show-current")

var out bytes.Buffer
cmd.Stdout = &out

err := cmd.Run()

if err != nil {
return "", err
}

branch := out.String()
branch = strings.TrimSpace(branch)

return branch, nil
}

0 comments on commit dc779c6

Please sign in to comment.