Watch 0 Star 0 Fork 0

oscstudio / gitenvGo

Sign up for free
Explore and code with more than 2 million developers,Free private repositories !:)
Sign up
Go Gitenv initialize spread retract

Clone or download
envctx.go 1.07 KB
Copy Edit Web IDE Raw Blame History
Charlie authored 2018-06-29 16:50 . support expandenv
package gitenv
import (
"errors"
"fmt"
"os"
"path/filepath"
)
// Envcontext is
type Envcontext struct {
Env map[string]string
}
// NewEnvcontext todo
func NewEnvcontext() (*Envcontext, error) {
exe, err := os.Executable()
if err != nil {
return nil, err
}
ec := &Envcontext{Env: make(map[string]string)}
exedir := filepath.Dir(exe)
if filepath.Base(exedir) == "bin" {
ec.Env["APPDIR"] = filepath.Dir(exedir)
} else {
ec.Env["APPDIR"] = exedir
}
return ec, nil
}
// Append env
func (ec *Envcontext) Append(key, value string) error {
if len(key) == 0 || len(value) == 0 {
return errors.New("Empty key value")
}
ec.Env[key] = value
return nil
}
// Delete Env
func (ec *Envcontext) Delete(key string) error {
if _, ok := ec.Env[key]; ok {
delete(ec.Env, key)
return nil
}
return fmt.Errorf("'%s' not exists", key)
}
// Expand callback
func (ec *Envcontext) Expand(s string) string {
if _, ok := ec.Env[s]; ok {
return ec.Env[s]
}
return os.Getenv(s)
}
// Expandenv is
func (ec *Envcontext) Expandenv(s string) string {
return os.Expand(s, ec.Expand)
}

Help Search