Skip to content

Commit

Permalink
Merge pull request #31 from kcmvp/build-version
Browse files Browse the repository at this point in the history
#9: auto set the version information from git hash
  • Loading branch information
kcmvp authored Dec 28, 2023
2 parents 02b641f + 8ba559a commit 0f97b82
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
with:
go-version: '1.21.4'
- name: Test
run: go test ./...
run: go test -v ./...
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
env:
Expand Down
19 changes: 11 additions & 8 deletions cmd/action/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package action

import (
"bufio"
"errors"
"fmt"
"io/fs"
"os"
Expand Down Expand Up @@ -71,26 +72,28 @@ var buildCommand = func(_ *cobra.Command, args ...string) error {
}
bm := map[string]string{}
for _, dir := range dirs {
mf, err := findMain(dir)
mainFile, err := findMain(dir)
if err != nil {
return err
}
if len(mf) > 0 {
if len(mainFile) > 0 {
// action
binary := strings.TrimSuffix(filepath.Base(mf), ".go")
binary := strings.TrimSuffix(filepath.Base(mainFile), ".go")
if f, exists := bm[binary]; exists {
return fmt.Errorf("file %s has already built as %s, please rename %s", f, binary, mf)
return fmt.Errorf("file %s has already built as %s, please rename %s", f, binary, mainFile)
}
output := filepath.Join(internal.CurProject().Root(), internal.CurProject().Target(), binary)
if _, err := exec.Command("go", "build", "-o", output, mf).CombinedOutput(); err != nil { //nolint
return err
output := filepath.Join(internal.CurProject().Target(), binary)
versionFlag := fmt.Sprintf("-X '%s/infra.buildVersion=%s'", internal.CurProject().Module(), internal.Version())
if _, err := exec.Command("go", "build", "-ldflags", versionFlag, "-o", output, mainFile).CombinedOutput(); err != nil { //nolint
return errors.New(color.RedString("failed to build the project: %s", err.Error()))
}
fmt.Printf("Build %s to %s successfully\n", mf, output)
fmt.Printf("Build %s to %s successfully\n", mainFile, output)
bm[binary] = output
} else {
color.Yellow("Can not find main function in package %s", dir)
}
}
//
return nil
}

Expand Down
17 changes: 17 additions & 0 deletions cmd/initializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ const defaultVersion = "v1.55.1"
//go:embed resources/.golangci.yaml
var golangci []byte

//go:embed resources/version.tmpl
var versionTmp []byte

func setupVersion() {
// check config folder
// create version.go
infra := filepath.Join(internal.CurProject().Root(), "infra")
if _, err := os.Stat(infra); err != nil {
os.Mkdir(infra, 0700) // nolint
}
ver := filepath.Join(infra, "version.go")
if _, err := os.Stat(ver); err != nil {
os.WriteFile(ver, versionTmp, 0o666) //nolint
}
}

var initializerFunc = func(_ *cobra.Command, _ []string) {
fmt.Println("Initialize configuration ......")
_, ok := lo.Find(internal.CurProject().Plugins(), func(plugin lo.Tuple4[string, string, string, string]) bool {
Expand All @@ -38,6 +54,7 @@ var initializerFunc = func(_ *cobra.Command, _ []string) {
}
}
internal.CurProject().Setup(true)
setupVersion()
}

// initializerCmd represents the init command
Expand Down
9 changes: 9 additions & 0 deletions cmd/resources/version.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Package config This file is generated by gob
package infra

// buildVersion don't change this
var buildVersion string

func Version() string {
return buildVersion
}
4 changes: 3 additions & 1 deletion main.go → gob.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ Copyright © 2023 kcheng.mvp@gmail.com
*/
package main

import "github.com/kcmvp/gob/cmd"
import (
"github.com/kcmvp/gob/cmd"
)

func main() {
cmd.Execute()
Expand Down
9 changes: 9 additions & 0 deletions infra/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Package config This file is generated by gob
package infra

// buildVersion don't change this, `gob build` would set this according to git commit hash
var buildVersion = "unknown"

func Version() string {
return buildVersion
}
3 changes: 1 addition & 2 deletions internal/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"github.com/samber/lo"
lop "github.com/samber/lo/parallel"
"os"
"os/exec"
"path/filepath"
"strings"
)
Expand Down Expand Up @@ -78,7 +77,7 @@ func (project *Project) Setup(init bool) {
project.viper.WriteConfigAs(project.Configuration())
}
// always generate hook script
if _, err := exec.Command("git", "status").CombinedOutput(); err != nil {
if !InGit() {
if init {
color.Yellow("Project is not in the source control")
}
Expand Down
31 changes: 31 additions & 0 deletions internal/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,37 @@ func (project *Project) InstallPlugin(url string, aliasAndCommand ...string) err
}
}

func InGit() bool {
_, err := exec.Command("git", "status").CombinedOutput()
return err == nil
}

var unknownVersion = "unknown"

func Version() string {
if output, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput(); err == nil {
hash := strings.ReplaceAll(string(output), "\n", "")
output, err = exec.Command("git", "describe", "--tag", hash).CombinedOutput()
if err != nil {
return unknownVersion
}
tag := strings.ReplaceAll(string(output), "\n", "")
output, _ = exec.Command("git", "status", "--short").CombinedOutput()
if lo.ContainsBy(strings.Split(string(output), "\n"), func(line string) bool {
line = strings.TrimSpace(strings.ToUpper(line))
return strings.HasPrefix(line, "M ") ||
strings.HasSuffix(line, "D ") ||
strings.HasSuffix(line, "?? ")
}) {
return fmt.Sprintf("%s@stage", tag)
}
if output, err = exec.Command("git", "show", "--format=%cd", "--date=format:%Y/%m/%d", hash).CombinedOutput(); err == nil {
return fmt.Sprintf("%s@%s", tag, strings.ReplaceAll(string(output), "\n", ""))
}
}
return unknownVersion
}

// Windows return true when current os is Windows
func Windows() bool {
return runtime.GOOS == "windows"
Expand Down
5 changes: 5 additions & 0 deletions internal/project_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,8 @@ func TestInstallPlugin(t *testing.T) {
assert.Equal(t, plugin.B, "callvisv7")
assert.Equal(t, plugin.C, "run")
}

func TestVersion(t *testing.T) {
//assert.True(t, strings.HasPrefix(Version(), "v0.0.2"))
//assert.True(t, strings.Contains(Version(), "@"))
}

0 comments on commit 0f97b82

Please sign in to comment.