1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
context.go 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-04-25 23:43 . build
package build
import (
stdctx "context"
"os"
"runtime"
"strings"
"time"
)
type Config struct {
ProductId string
ProjectName string
Version string
Model string
Os string
Env []string
}
// Git includes tags and diffs used in some point.
type Git struct {
Branch string
CurrentTag string
PreviousTag string
Commit string
ShortCommit string
FullCommit string
FirstCommit string
URL string
Summary string
TagSubject string
TagContents string
TagBody string
CommitDate time.Time
Dirty bool
}
// Env is the environment variables.
type Env map[string]string
// Copy returns a copy of the environment.
func (e Env) Copy() Env {
out := Env{}
for k, v := range e {
out[k] = v
}
return out
}
// Strings returns the current environment as a list of strings, suitable for
// os executions.
func (e Env) Strings() []string {
result := make([]string, 0, len(e))
for k, v := range e {
result = append(result, k+"="+v)
}
return result
}
type DateFormatFunc func(d time.Time) string
func DefaultDateFormat(d time.Time) string {
return d.UTC().Format(time.RFC3339)
}
// Context carries along some data through the pipes.
type Context struct {
stdctx.Context
Config Config
Env Env
Git Git
Semver Semver
Runtime Runtime
DateFormat DateFormatFunc
Date time.Time
Snapshot bool
}
type Runtime struct {
Goos string
Goarch string
}
// Semver represents a semantic version.
type Semver struct {
Major uint64
Minor uint64
Patch uint64
Prerelease string
}
// NewContext context.
func NewContext(config Config) *Context {
return WrapContext(stdctx.Background(), config)
}
// NewWithTimeout new context with the given timeout.
func NewWithTimeout(config Config, timeout time.Duration) (*Context, stdctx.CancelFunc) {
ctx, cancel := stdctx.WithTimeout(stdctx.Background(), timeout) // nosem
return WrapContext(ctx, config), cancel
}
// WrapContext wraps an existing context.
func WrapContext(ctx stdctx.Context, config Config) *Context {
return &Context{
Context: ctx,
Config: config,
Env: ToEnv(append(os.Environ(), config.Env...)),
Date: time.Now(),
DateFormat: DefaultDateFormat,
Runtime: Runtime{
Goos: runtime.GOOS,
Goarch: runtime.GOARCH,
},
}
}
// ToEnv converts a list of strings to an Env (aka a map[string]string).
func ToEnv(env []string) Env {
r := Env{}
for _, e := range env {
k, v, ok := strings.Cut(e, "=")
if !ok || k == "" {
continue
}
r[k] = v
}
return r
}
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.65

搜索帮助