本文整理汇总了Golang中os.ExpandEnv函数的典型用法代码示例。如果您正苦于以下问题:Golang ExpandEnv函数的具体用法?Golang ExpandEnv怎么用?Golang ExpandEnv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ExpandEnv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: run
func run(c *cli.Context) error {
args := c.Args()
if len(args) < 3 {
return errors.New("a directory, log file and command is required")
}
workingDir := os.ExpandEnv(args[0])
logFile := os.ExpandEnv(args[1])
fullCommand := os.ExpandEnv(args[2])
command, cmdArgs, err := parseCommand(fullCommand)
if err != nil {
return errors.WithStack(err)
}
log, err := os.Create(logFile)
if err != nil {
return errors.WithStack(err)
}
cmd := exec.Command(command, cmdArgs...)
fmt.Println(cmd.Path)
cmd.Dir = workingDir
cmd.Stdout = log
cmd.Stderr = log
return cmd.Run()
}
示例2: createNewConfigIfNeeded
func createNewConfigIfNeeded() {
newConfigPath := os.ExpandEnv("$HOME/.config/mumbledj/config.yaml.new")
// Check if we should write an updated config file to config.yaml.new.
if assetInfo, err := AssetInfo("config.yaml"); err == nil {
asset, _ := Asset("config.yaml")
if configFile, err := os.Open(os.ExpandEnv("$HOME/.config/mumbledj/config.yaml")); err == nil {
configInfo, _ := configFile.Stat()
defer configFile.Close()
if configNewFile, err := os.Open(newConfigPath); err == nil {
defer configNewFile.Close()
configNewInfo, _ := configNewFile.Stat()
if assetInfo.ModTime().Unix() > configNewInfo.ModTime().Unix() {
// The config asset is newer than the config.yaml.new file.
// Write a new config.yaml.new file.
ioutil.WriteFile(os.ExpandEnv(newConfigPath), asset, 0644)
logrus.WithFields(logrus.Fields{
"file_path": newConfigPath,
}).Infoln("An updated default configuration file has been written.")
}
} else if assetInfo.ModTime().Unix() > configInfo.ModTime().Unix() {
// The config asset is newer than the existing config file.
// Write a config.yaml.new file.
ioutil.WriteFile(os.ExpandEnv(newConfigPath), asset, 0644)
logrus.WithFields(logrus.Fields{
"file_path": newConfigPath,
}).Infoln("An updated default configuration file has been written.")
}
}
}
}
示例3: EnsureSystemRuby
func (cmd *Cmd) EnsureSystemRuby() {
cmd.Env = []string{
os.ExpandEnv("PATH=${PATH}"),
os.ExpandEnv("USER=${USER}"),
os.ExpandEnv("HOME=${HOME}"),
}
}
示例4: authenticate
func (c *Client) authenticate() error {
if c.cert != nil {
return nil
}
cert_fname := filepath.Join(os.ExpandEnv(CertDir), "usercert.pem")
key_fname := filepath.Join(os.ExpandEnv(CertDir), "userkey.pem")
//FIXME:
// X509_USER_PROXY doesn't have a format tls.LoadX509KeyPair understands
// if os.Getenv("X509_USER_PROXY") != "" {
// cert_fname = os.Getenv("X509_USER_PROXY")
// key_fname = cert_fname
// }
cert, err := tls.LoadX509KeyPair(cert_fname, key_fname)
if err != nil {
user_cert, user_key, err := LoadCert(cert_fname, key_fname)
if err != nil {
//fmt.Printf("ami: error while trying to load certificate. try running:\n $ go-ami setup-auth\n")
return ErrAuth
}
cert, err = tls.X509KeyPair(user_cert, user_key)
if err != nil {
return err
}
}
c.cert = &cert
return nil
}
示例5: serve
func serve(config *Config) error {
http.Handle("/df", Command{CommandRunner: &commands.DiskCommand{}})
http.Handle("/service/", config.Services)
if config.ServerCertificate == "" {
return http.ListenAndServe(config.BindAddress, nil)
}
certFile := os.ExpandEnv(config.ServerCertificate)
keyFile := os.ExpandEnv(config.ServerPrivate)
caCertFile := os.ExpandEnv(config.CACertificate)
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert},
ClientCAs: x509.NewCertPool(),
}
caCerts, err := ioutil.ReadFile(caCertFile)
if err != nil {
return err
}
tlsConfig.ClientCAs.AppendCertsFromPEM(caCerts)
l, err := tls.Listen("tcp", config.BindAddress, tlsConfig)
if err != nil {
return err
}
return http.Serve(l, nil)
}
示例6: parseLink
func parseLink(params []string) (srcPath, dstPath string, mode os.FileMode, err error) {
length := len(params)
if length < 1 || length > 3 {
err = fmt.Errorf("invalid link statement")
return
}
if length > 2 {
var parsed uint64
parsed, err = strconv.ParseUint(params[2], 0, 64)
if err != nil {
return
}
mode = os.FileMode(parsed)
} else {
mode = 0755
}
dstPath = os.ExpandEnv(params[0])
srcPath = dstPath
if length > 1 {
srcPath = os.ExpandEnv(params[1])
}
return
}
示例7: CreateAgent
func CreateAgent() error {
path, err := osext.Executable()
if err != nil {
return err
}
fileDir := os.ExpandEnv("$HOME/Library/LaunchAgents")
err = os.MkdirAll(fileDir, 0755)
if err != nil {
return err
}
err = changePermissions(fileDir)
if err != nil {
return err
}
filePath := os.ExpandEnv("$HOME/Library/LaunchAgents/local.dlite.plist")
file, err := os.Create(filePath)
if err != nil {
return err
}
plist := fmt.Sprintf(template, path)
_, err = file.WriteString(plist)
if err != nil {
return err
}
return changePermissions(filePath)
}
示例8: expandFields
// ExpandFields goes through a Package type to expand any environment variables
// contained within, or expand XML structures referrenced before.
func expandFields(pkg *Package) Package {
// Reflect may throw type-errors (can't trust ourselves with writing good
// code, now, can we?) so catch any panics and rewrite them as a general
// type of error.
defer func() {
if r := recover(); r != nil {
panic(ErrParseType)
}
}()
// TODO rewrite for more generality in substructs
// TODO remove duplicate code
valOf := reflect.ValueOf(pkg).Elem()
for i := 0; i < valOf.NumField(); i++ {
field := valOf.Field(i)
if field.Kind() == reflect.Struct {
for j := 0; j < field.NumField(); j++ {
expanded := os.ExpandEnv(field.Field(j).String())
field.Field(j).SetString(expanded)
}
} else {
expanded := os.ExpandEnv(field.String())
field.SetString(expanded)
os.Setenv(valOf.Type().Field(i).Name, field.String())
}
}
return *pkg
}
示例9: createShims
func (e *registryEntry) createShims() {
exeproxy := os.ExpandEnv("${ProgramFiles(x86)}\\exeproxy\\exeproxy.exe")
if !pathExists(exeproxy) {
return
}
if !pathExists(shimsPath) {
os.MkdirAll(shimsPath, 0)
}
if shims, ok := e.Installer.options()["shims"]; ok {
for _, v := range shims.([]interface{}) {
shimTarget := strings.Replace(v.(string), "${version}", e.Version, -1)
shimTarget = os.ExpandEnv(shimTarget)
shim := filepath.Join(shimsPath, filepath.Base(shimTarget))
if pathExists(shim) {
os.Remove(shim)
}
log.Printf("Creating shim for %s (%s)\n", shimTarget, shim)
system(exeproxy, "exeproxy-copy", shim, shimTarget)
}
}
}
示例10: main
func main() {
var rootDir, folder string
var err error
flag.StringVar(&rootDir, "root", os.ExpandEnv("$HOME/Maildir"), "path to maildir")
flag.StringVar(&folder, "folder", "", "maildir folder name to put email (empty for inbox)")
flag.StringVar(&cache.path, "cache", os.ExpandEnv("$HOME/.cache/maildir-put.cache"),
"path to store message-ids to drop duplicate messages")
flag.BoolVar(&cache.useRedis, "redis", false, "use redis for cache storage")
flag.StringVar(&cache.redisOptions.Addr, "redis-addr", "127.0.0.1:6379", "redis address")
flag.Int64Var(&cache.redisOptions.DB, "redis-db", 0, "redis base")
flag.StringVar(&cache.redisOptions.Password, "redis-password", "", "redis password")
if flag.Parse(); !flag.Parsed() {
flag.PrintDefaults()
os.Exit(1)
}
if err = cache.OpenCache(); err != nil {
log.Fatalf("Can't open cache: %s", err.Error())
}
if hostname, err = os.Hostname(); err != nil {
log.Fatalf("Can't get hostname: %s", err.Error())
}
md, err := maildir.New(rootDir, true)
if err != nil {
log.Fatalf("Can't open maildir: %s", err.Error())
}
for _, subfolder := range strings.Split(folder, "/") {
if subfolder != "" {
md, err = md.Child(subfolder, true)
if err != nil {
log.Fatalf("Can't open maildir: %s", err.Error())
}
}
}
dec := json.NewDecoder(os.Stdin)
for {
msg := new(Message)
err = dec.Decode(msg)
if err == nil {
err = msg.Process(md)
}
if err == io.EOF {
break
} else if err != nil {
log.Printf("Cannot read input message: %s", err.Error())
}
}
if err = cache.Dump(); err != nil {
log.Printf("warning: can't dump cache: %s", err.Error())
}
}
示例11: CreateDisk
func CreateDisk(sshKey string, size int) error {
sshKey = os.ExpandEnv(sshKey)
keyBytes, err := ioutil.ReadFile(sshKey)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
tarball := tar.NewWriter(buffer)
files := []struct {
Name string
Body []byte
}{
{"dhyve, please format-me", []byte("dhyve, please format-me")},
{".ssh/authorized_keys", keyBytes},
}
for _, file := range files {
if err = tarball.WriteHeader(&tar.Header{
Name: file.Name,
Mode: 0644,
Size: int64(len(file.Body)),
}); err != nil {
return err
}
if _, err = tarball.Write(file.Body); err != nil {
return err
}
}
if err = tarball.Close(); err != nil {
return err
}
path := os.ExpandEnv("$HOME/.dlite/disk.img")
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(buffer.Bytes())
if err != nil {
return err
}
_, err = f.Seek(int64(size*1073741824-1), 0)
if err != nil {
return err
}
_, err = f.Write([]byte{0})
if err != nil {
return err
}
return changePermissions(path)
}
示例12: installBox
func installBox(ctx *cobra.Command, args []string) {
if len(args) < 2 {
ErrorExit(ctx, "Needs two arguments to install <BOX FILE|URL> as <BOX NAME>")
}
boxName := args[0]
dstPath := os.ExpandEnv(BOX_ROOT_DIR + boxName + BOX_FILE_EXTENSION)
if _, err := os.Lstat(dstPath); err == nil {
if !boolForce {
log.Fatalf("%s has already installed", boxName)
}
if err := os.Remove(dstPath); err != nil {
log.Fatalf("Could not remove %s, error %s", boxName, err)
}
}
if err := os.MkdirAll(os.ExpandEnv(BOX_ROOT_DIR), 0755); err != nil {
log.Fatal(err)
}
dstFile, err := os.Create(dstPath)
if err != nil {
log.Fatalf("Could not create a file, error %s", err)
}
defer dstFile.Close()
srcPath := args[1]
if strings.HasPrefix(srcPath, "http://") || strings.HasPrefix(srcPath, "https://") {
resp, err := http.Get(srcPath)
if err != nil {
log.Fatalf("Could not download: %s, error %s", srcPath, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
log.Fatalf("Could not download: %s, HTTP status %s", srcPath, resp.Status)
}
if _, err := io.Copy(dstFile, resp.Body); err != nil {
log.Fatalf("Could not download: %s, error %s", srcPath, err)
}
} else {
srcPath = filepath.Clean(srcPath)
srcFile, err := os.Open(srcPath)
if err != nil {
log.Fatalf("Could not open: %s, error %s", srcPath, err)
}
defer srcFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
log.Fatalf("Could not download: %s, error %s", srcPath, err)
}
}
fmt.Printf("%s: Installed %s\n", COMMAND, boxName)
}
示例13: Interpolate
func (c *ConfigWrapper) Interpolate() {
if c.Config != nil {
c.Interface.Network.Host = os.ExpandEnv(c.Interface.Network.Host)
c.Interface.Socket.Path = os.ExpandEnv(c.Interface.Socket.Path)
c.Paths.StageDir = os.ExpandEnv(c.Paths.StageDir)
c.Paths.StorageDir = os.ExpandEnv(c.Paths.StorageDir)
}
}
示例14: DeleteOldest
// DeleteOldest deletes the oldest file in the cache.
func (c *Cache) DeleteOldest() error {
files, _ := ioutil.ReadDir(os.ExpandEnv(viper.GetString("cache.directory")))
if len(files) > 0 {
sort.Sort(SortFilesByAge(files))
os.Remove(fmt.Sprintf("%s/%s", os.ExpandEnv(viper.GetString("cache.directory")), files[0].Name()))
return nil
}
return errors.New("There are no files currently cached")
}
示例15: init
// registers all resource related steps
func init() {
RegisterSteps(func(c *Context) {
c.When(`^I parse the file "(.+?)"$`, func(fileName string) {
expandedFileName := os.ExpandEnv(fileName)
if expandedFileName == "" {
c.Fail("File name '%s' (expanded to '%s') is empty !", fileName, expandedFileName)
return
}
if _, err := os.Stat(expandedFileName); err != nil {
c.Fail("File '%s' (expanded to '%s') does not exists: %v", fileName, expandedFileName, err)
return
}
_, err := c.ParseResource(expandedFileName)
if err != nil {
c.Fail("Failed to parse file '%s' (expanded to '%s'): %v", fileName, expandedFileName, err)
return
}
})
c.When(`^I create resources from the file "(.+?)"$`, func(fileName string) {
expandedFileName := os.ExpandEnv(fileName)
if expandedFileName == "" {
c.Fail("File name '%s' (expanded to '%s') is empty !", fileName, expandedFileName)
return
}
if _, err := os.Stat(expandedFileName); err != nil {
c.Fail("File '%s' (expanded to '%s') does not exists: %v", fileName, expandedFileName, err)
return
}
r, err := c.ParseResource(expandedFileName)
if err != nil {
c.Fail("Failed to parse file '%s' (expanded to '%s'): %v", fileName, expandedFileName, err)
return
}
if err = r.Visit(CreateResource); err != nil {
c.Fail("Failed to create resource from file '%s' (expanded to '%s'): %v", fileName, expandedFileName, err)
return
}
})
c.When(`^I delete all resources with "(.+?)"$`, func(selector string) {
err := c.DeleteResourcesBySelector(selector)
if err != nil {
c.Fail("Failed to delete resources with '%s': %v", selector, err)
return
}
})
})
}