Skip to content

Commit

Permalink
Merge pull request rookie-ninja#1 from dongxuny/master
Browse files Browse the repository at this point in the history
Move git related functions from rk-common to rk
  • Loading branch information
dongxuny authored Sep 6, 2021
2 parents be612fc + 4691ff8 commit 4b33c8a
Show file tree
Hide file tree
Showing 11 changed files with 237 additions and 277 deletions.
7 changes: 4 additions & 3 deletions commands/build/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package build

import (
"errors"
"github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/common"
"github.com/urfave/cli/v2"
Expand Down Expand Up @@ -38,9 +39,9 @@ func buildAction(ctx *cli.Context) error {
}
chain := common.NewActionChain()
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down
11 changes: 6 additions & 5 deletions commands/build/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package build

import (
"context"
"errors"
"fmt"
"github.com/fatih/color"
"github.com/ghodss/yaml"
Expand Down Expand Up @@ -172,7 +173,7 @@ func ExecScriptAfter(ctx *cli.Context) error {
}

func WriteRkMetaFile(ctx *cli.Context) error {
meta := rkcommon.GetRkMetaFromCmd()
meta := common.GetRkMetaFromCmd()

// 5: Write to .rk/git.yaml file
color.White("- Write files to %s", path.Join(common.BuildTarget, rkcommon.RkMetaFilePath))
Expand All @@ -191,9 +192,9 @@ func BuildGoFile(ctx *cli.Context) error {
// Create .rk folder first
os.MkdirAll(path.Join(common.BuildTarget, path.Dir(rkcommon.RkMetaFilePath)), os.ModePerm)

// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}

// 1: create directory named as target and sub folders
Expand Down Expand Up @@ -224,7 +225,7 @@ func BuildGoFile(ctx *cli.Context) error {
args := []string{
"build",
"-o",
fmt.Sprintf("target/bin/%s", rkcommon.GetGoPkgName()),
fmt.Sprintf("target/bin/%s", common.TargetPkgName),
}

// append user provided args
Expand Down
7 changes: 4 additions & 3 deletions commands/clear/clear.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package clear

import (
"errors"
rkcommon "github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/common"
"github.com/urfave/cli/v2"
Expand All @@ -25,9 +26,9 @@ func Clear() *cli.Command {
func clearAction(ctx *cli.Context) error {
chain := common.NewActionChain()
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down
3 changes: 1 addition & 2 deletions commands/docker/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"bufio"
"context"
"github.com/fatih/color"
rkcommon "github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/common"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
Expand Down Expand Up @@ -80,7 +79,7 @@ func runDockerImage(ctx *cli.Context) error {
}

func buildDockerImage(ctx *cli.Context) error {
meta := rkcommon.GetRkMetaFromCmd()
meta := common.GetRkMetaFromCmd()

if len(common.BuildConfig.Docker.Build.Registry) < 1 {
common.BuildConfig.Docker.Build.Registry = meta.Name
Expand Down
7 changes: 4 additions & 3 deletions commands/docker/docker_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package docker

import (
"errors"
"github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/commands/build"
"github.com/rookie-ninja/rk/common"
Expand Down Expand Up @@ -36,9 +37,9 @@ func buildAction(ctx *cli.Context) error {
chain := common.NewActionChain()
chain.Add("Validate docker environment", validateDockerCommand, false)
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down
7 changes: 4 additions & 3 deletions commands/docker/docker_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package docker

import (
"errors"
"github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/commands/build"
"github.com/rookie-ninja/rk/common"
Expand Down Expand Up @@ -33,9 +34,9 @@ func runAction(ctx *cli.Context) error {
chain := common.NewActionChain()
chain.Add("Validate docker environment", validateDockerCommand, false)
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down
9 changes: 5 additions & 4 deletions commands/pack/pack.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package pack

import (
"errors"
"fmt"
"github.com/fatih/color"
"github.com/rookie-ninja/rk-common/common"
Expand Down Expand Up @@ -33,9 +34,9 @@ func packAction(ctx *cli.Context) error {
}
chain := common.NewActionChain()
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down Expand Up @@ -64,7 +65,7 @@ func packAction(ctx *cli.Context) error {
}

func compressTarget(ctx *cli.Context) error {
meta := rkcommon.GetRkMetaFromCmd()
meta := common.GetRkMetaFromCmd()
packName := fmt.Sprintf("%s-%s.tar.gz", meta.Name, meta.Version)

args := []string{
Expand Down
9 changes: 5 additions & 4 deletions commands/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package run

import (
"errors"
"fmt"
"github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk/commands/build"
Expand Down Expand Up @@ -34,9 +35,9 @@ func runAction(ctx *cli.Context) error {

chain := common.NewActionChain()
chain.Add("Clearing target folder", func(ctx *cli.Context) error {
// 0: Move to dir of where go.mod file exists
if err := os.Chdir(rkcommon.GetGoWd()); err != nil {
return err
// 0: Not dir of where go.mod file exists
if !rkcommon.FileExists("go.mod") {
return errors.New("not a go directory, failed to lookup go.mod file")
}
return os.RemoveAll(common.BuildTarget)
}, false)
Expand Down Expand Up @@ -73,7 +74,7 @@ func runBinary(ctx *cli.Context) error {
syscall.SIGQUIT)

os.Chdir(common.BuildTarget)
cmd := exec.Command(fmt.Sprintf("./bin/%s", rkcommon.GetGoPkgName()))
cmd := exec.Command(fmt.Sprintf("./bin/%s", common.TargetPkgName))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

Expand Down
147 changes: 142 additions & 5 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@ import (
"fmt"
"github.com/fatih/color"
"github.com/ghodss/yaml"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/pkg/errors"
"github.com/rogpeppe/go-internal/modfile"
rkcommon "github.com/rookie-ninja/rk-common/common"
"github.com/rookie-ninja/rk-logger"
"github.com/rookie-ninja/rk-query"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go/build"
"io/ioutil"
"os"
"path"
"strings"
"time"
)

Expand Down Expand Up @@ -54,9 +61,11 @@ var (
"compress": true
}`

logger *zap.Logger
factory *rkquery.EventFactory
BuildConfig = &BootConfig{}
logger *zap.Logger
factory *rkquery.EventFactory
BuildConfig = &BootConfig{}
TargetPkgName = getPkgName()
TargetGitInfo = getGitInfo()
)

type BootConfig struct {
Expand Down Expand Up @@ -166,7 +175,7 @@ func UnmarshalBootConfig(configFilePath string, config interface{}) error {
configFilePath = path.Join(wd, configFilePath)
}

bytes := rkcommon.TryReadFile(configFilePath)
bytes := TryReadFile(configFilePath)
if len(bytes) < 1 {
return errors.New(fmt.Sprintf("Failed to read build.yaml file from path:%s", configFilePath))
}
Expand All @@ -179,5 +188,133 @@ func UnmarshalBootConfig(configFilePath string, config interface{}) error {
}

func GetGoPathBin() string {
return path.Join(rkcommon.GetGoEnv().GoPath, "bin")
return path.Join(build.Default.GOPATH, "bin")
}

// TryReadFile reads files with provided path, use working directory if given path is relative path.
// Ignoring error while reading.
func TryReadFile(filePath string) []byte {
if len(filePath) < 1 {
return make([]byte, 0)
}

if !path.IsAbs(filePath) {
// Ignore error
wd, _ := os.Getwd()
filePath = path.Join(wd, filePath)
}

if bytes, err := ioutil.ReadFile(filePath); err != nil {
return bytes
} else {
return bytes
}
}

// getPkgName will try best to retrieve package name by bellow priority.
// 1: Read from go.mod file
// 2: Read from current directory
// 3: Return empty if nothing matched
func getPkgName() string {
// Read from go.mod
if rkcommon.FileExists("go.mod") {
if bytes := rkcommon.TryReadFile("go.mod"); len(bytes) > 0 {
return path.Base(modfile.ModulePath(bytes))
}
}

// Read current directory name
if res, err := os.Getwd(); err == nil {
return path.Base(res)
}

// Return empty
return ""
}

func getGitInfo() *rkcommon.Git {
res := &rkcommon.Git{
Commit: &rkcommon.Commit{
Committer: &rkcommon.Committer{},
},
}

opt := &git.PlainOpenOptions{
DetectDotGit: true,
}
if repo, err := git.PlainOpenWithOptions(".", opt); err == nil {
// Parse URL
if config, e1 := repo.Config(); e1 == nil {
// Iterate map
for _, v := range config.Remotes {
if len(v.URLs) > 0 {
res.Url = strings.TrimSuffix(v.URLs[0], ".git")
}
break
}
}

// Get current head
var head plumbing.Hash
if ref, e1 := repo.Head(); e1 == nil {
head = ref.Hash()
}

// Parse branch
if iter, e1 := repo.Branches(); e1 == nil {
iter.ForEach(func(ref *plumbing.Reference) error {
if ref.Hash() == head {
res.Branch = ref.Name().Short()
}
return nil
})
}

// Parse tag
if tag, e1 := repo.TagObject(head); e1 == nil {
res.Tag = tag.Name
}

// Parse commit
if commit, e1 := repo.CommitObject(head); e1 == nil {
res.Commit.Committer.Name = commit.Committer.Name
res.Commit.Committer.Email = commit.Committer.Email
res.Commit.Date = commit.Author.When.Format(object.DateFormat)
res.Commit.Id = commit.ID().String()
if len(res.Commit.Id) > 7 {
res.Commit.IdAbbr = commit.ID().String()[:7]
}
res.Commit.Sub = commit.Message
}
}

return res
}

// GetRkMetaFromCmd construct RkMeta from local environment
func GetRkMetaFromCmd() *rkcommon.RkMeta {
meta := &rkcommon.RkMeta{}

// Load package name from go.mod file
meta.Name = TargetPkgName

// Load current git info from local git
meta.Git = TargetGitInfo

// Load version
if len(meta.Git.Tag) < 1 {
// Tag is empty, let's try to construct version as <branch>-<commit IdAbbr>
if len(meta.Git.Branch) < 1 {
// Branch is empty, we will use commit IdAbbr instead
meta.Version = meta.Git.Commit.IdAbbr
} else {
// <branch>-<commit IdAbbr>
meta.Version = strings.Join([]string{meta.Git.Branch, meta.Git.Commit.IdAbbr}, "-")
}
} else {
// Use tag as version
meta.Version = meta.Git.Tag
}

return meta
}
Loading

0 comments on commit 4b33c8a

Please sign in to comment.