当前位置: 首页>>代码示例>>Golang>>正文


Golang os.Expand函数代码示例

本文整理汇总了Golang中os.Expand函数的典型用法代码示例。如果您正苦于以下问题:Golang Expand函数的具体用法?Golang Expand怎么用?Golang Expand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Expand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: cmdLine

func (m *Machine) cmdLine() []string {
	result := []string{"--driver", m.driver}
	keys := []string{}
	for k := range m.options {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		v := m.options[k]
		switch val := v.(type) {
		case string:
			result = append(result, "--"+k)
			val = os.Expand(val, func(key string) string { return m.expand(key) })
			result = append(result, val)
		case map[interface{}]interface{}:
			keys := []string{}
			for kk := range val {
				keys = append(keys, kk.(string))
			}
			sort.Strings(keys)
			for _, kk := range keys {
				vv := val[kk]
				result = append(result, "--"+k)
				evv := os.Expand(vv.(string), func(key string) string { return m.expand(key) })
				result = append(result, kk+"="+evv)
			}
		case bool:
			if val {
				result = append(result, "--"+k)
			}
		}
	}
	result = append(result, m.name)
	return result
}
开发者ID:prachpub,项目名称:dpm,代码行数:35,代码来源:provision.go

示例2: Prepare

func (s *ShellExecutor) Prepare(globalConfig *common.Config, config *common.RunnerConfig, build *common.Build) error {
	if globalConfig != nil {
		s.Shell.User = globalConfig.User
	}

	// expand environment variables to have current directory
	wd, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("Getwd: %v", err)
	}

	mapping := func(key string) string {
		switch key {
		case "PWD":
			return wd
		default:
			return ""
		}
	}

	s.DefaultBuildsDir = os.Expand(s.DefaultBuildsDir, mapping)
	s.DefaultCacheDir = os.Expand(s.DefaultCacheDir, mapping)

	// Pass control to executor
	err = s.AbstractExecutor.Prepare(globalConfig, config, build)
	if err != nil {
		return err
	}

	s.Println("Using Shell executor...")
	return nil
}
开发者ID:mikew,项目名称:gitlab-ci-multi-runner,代码行数:32,代码来源:executor_shell.go

示例3: AddContainer

func (lw *LogWatcher) AddContainer(cid string) {
	c, err := lw.docker.InspectContainer(cid)
	if err != nil {
		log.WithFields(log.Fields{
			"ID": cid,
		}).Warn(err)
		return
	}

	var envExpand = func(key string) string {
		for _, v := range c.Config.Env {
			if strings.HasPrefix(v, key+"=") {
				return strings.SplitN(v, "=", 2)[1]
			}
		}
		return ""
	}

	if os.Expand("$DLE_IGNORE", envExpand) != "" {
		log.WithFields(log.Fields{
			"ID": cid,
		}).Info("Ignoring container")
		return
	}

	token := os.Expand("$DLE_TOKEN", envExpand)
	if token == "" {
		token = defaultToken
	}

	lf := log.Fields{
		"ID":    cid,
		"token": token,
	}

	log.WithFields(lf).Info("Watching container")

	logwriter := &LogWriter{
		logline: lw.LogLines,
		token:   token,
	}

	logopts := docker.LogsOptions{
		Container:    cid,
		OutputStream: logwriter,
		ErrorStream:  logwriter,
		Stdout:       true,
		Stderr:       true,
		Follow:       true,
		Tail:         "0",
		RawTerminal:  true,
	}
	err = lw.docker.Logs(logopts)
	if err != nil {
		fmt.Println("error:", err)
	}

	log.WithFields(lf).Info("Stopped watching container")
}
开发者ID:stabenfeldt,项目名称:dle,代码行数:59,代码来源:dle.go

示例4: TestReplaceEnvironment

func TestReplaceEnvironment(t *testing.T) {
	r := ReplaceEnvironment([]string{
		"TMP_DIR=/home/user/please/src/core",
		"PKG=src/core",
		"SRCS=core.go build_env.go",
	})
	assert.Equal(t,
		"/home/user/please/src/core src/core core.go build_env.go",
		os.Expand("$TMP_DIR ${PKG} ${SRCS}", r))
	assert.Equal(t, "", os.Expand("$WIBBLE", r))
}
开发者ID:thought-machine,项目名称:please,代码行数:11,代码来源:build_env_test.go

示例5: externalCommand

func (g *goemon) externalCommand(command, file string) bool {
	var cmd *exec.Cmd
	command = os.Expand(command, func(s string) string {
		switch s {
		case "GOEMON_TARGET_FILE":
			return file
		case "GOEMON_TARGET_BASE":
			return filepath.Base(file)
		case "GOEMON_TARGET_DIR":
			return filepath.ToSlash(filepath.Dir(file))
		case "GOEMON_TARGET_EXT":
			return filepath.Ext(file)
		case "GOEMON_TARGET_NAME":
			fn := filepath.Base(file)
			ext := filepath.Ext(file)
			return fn[:len(fn)-len(ext)]
		}
		return os.Getenv(s)
	})
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", command)
	} else {
		cmd = exec.Command("sh", "-c", command)
	}
	g.Logger.Println("executing", command)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		g.Logger.Println(err)
		return false
	}
	return true
}
开发者ID:todashuta,项目名称:goemon,代码行数:34,代码来源:command.go

示例6: main

func main() {
	fmt.Println(os.ExpandEnv("HOME = $HOME; GOROOT = $GOROOT"))

	fmt.Println(os.Expand("$GOROOT", func(s string) string {
		return s + " = " + os.Getenv(s)
	}))
}
开发者ID:CodyGuo,项目名称:Go-Cody,代码行数:7,代码来源:main.go

示例7: ParseEnv

// ParseEnv parses io.Reader into an arrays of strings
// representing the environment, in the form "key=value".
func ParseEnv(r io.Reader) ([]string, error) {
	sysenv := env2Map(os.Environ())
	localenv := make(map[string]string)
	mapping := func(key string) string {
		value, ok := localenv[key]
		if !ok {
			value, ok = sysenv[key]
		}
		return value
	}

	env := []string{}
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		entry := strings.TrimSpace(scanner.Text())
		if len(entry) == 0 {
			continue
		}

		pair := strings.SplitN(entry, "=", 2)
		key := pair[0]
		value := os.Expand(pair[1], mapping)
		localenv[key] = value
		env = append(env, fmt.Sprintf("%s=%s", key, value))
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("procker: parse env error: %s", err)
	}

	return env, nil
}
开发者ID:jweslley,项目名称:procker,代码行数:34,代码来源:support.go

示例8: testExpand

func testExpand(name string) {
	testStr := fmt.Sprintf("hello, ${%s}", name)
	newStr := os.Expand(testStr, func(s string) string {
		return "My " + s
	})
	fmt.Println(newStr)
}
开发者ID:me020523,项目名称:learning-golang,代码行数:7,代码来源:test-os.go

示例9: parseURLPrefixTag

// parseURLPrefixTag expects an input in the form of 'tag-host/path'
// and returns the lower cased host plus the path unaltered if the
// prefix matches the tag.
func parseURLPrefixTag(s, prefix string, env map[string]string) (host, path string, ok bool) {
	s = strings.TrimSpace(s)
	if !strings.HasPrefix(s, prefix) {
		return "", "", false
	}

	// split host/path
	p := strings.SplitN(s[len(prefix):], "/", 2)
	if len(p) != 2 {
		log.Printf("[WARN] consul: Invalid %s tag %q", prefix, s)
		return "", "", false
	}

	// expand $x or ${x} to env[x] or ""
	expand := func(s string) string {
		return os.Expand(s, func(x string) string {
			if env == nil {
				return ""
			}
			return env[x]
		})
	}

	host = strings.ToLower(expand(strings.TrimSpace(p[0])))
	path = "/" + expand(strings.TrimSpace(p[1]))

	return host, path, true
}
开发者ID:ycaihua,项目名称:fabio,代码行数:31,代码来源:parse.go

示例10: makeEnvMap

// makeEnvMap parse the given env string set and returns a new envMap
func makeEnvMap(set []string, inherit bool, ref ...*envMap) *envMap {
	env := make(envMap)
	for _, kv := range set {
		if strings.Contains(kv, PathListSeparator) {
			kv = strings.Replace(kv, PathListSeparator, string(os.PathListSeparator), -1)
		}

		kv = os.Expand(kv, func(key string) string {
			for _, r := range append(ref, &env) {
				if v, ok := (*r)[key]; ok {
					return v
				}
			}
			if v := os.Getenv(key); inherit && v != "" {
				return v
			} else {
				return "" //key
			}

		})

		if pair := strings.Split(kv, "="); len(pair) < 2 {
			env[pair[0]] = ""
		} else if len(pair) > 2 {
			pair = strings.FieldsFunc(kv, getQuoteSplitter('='))
			env[pair[0]] = pair[1]
		} else {
			env[pair[0]] = pair[1]

		}

	}
	return &env
}
开发者ID:Fiery,项目名称:go-run,代码行数:35,代码来源:env.go

示例11: getCmd

// getCmd returns exec.Cmd
// binary names will be evaluated with Env here since this is the last step before Run()
func (a *app) getCmd() (*exec.Cmd, error) {
	path, err := exec.LookPath(a.bin)
	if err != nil {
		if path, err = exec.LookPath(os.Expand(a.bin, func(key string) string {
			if v, ok := (*Env)[key]; ok {
				return v
			} else {
				return ""
			}
		})); err != nil {
			return nil, fmt.Errorf("installing %v is in your future...", a.bin)
		}
	}
	cmd := exec.Command(path, a.arg...)
	if a.dir != "" {
		cmd.Dir = a.dir
	}

	cmd.Env = Env.combine(append(a.env, os.Environ()...)).list()
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr

	if len(Env.list()) > 0 {
		logger.Printf("Env: %s\n", Env)
	}
	logger.Printf("Command loaded: %s\n", a.cmd)

	return cmd, nil
}
开发者ID:Fiery,项目名称:go-run,代码行数:30,代码来源:app.go

示例12: parseURLPrefixTag

// parseURLPrefixTag expects an input in the form of 'tag-host/path[ opts]'
// and returns the lower cased host and the unaltered path if the
// prefix matches the tag.
func parseURLPrefixTag(s, prefix string, env map[string]string) (route, opts string, ok bool) {
	// expand $x or ${x} to env[x] or ""
	expand := func(s string) string {
		return os.Expand(s, func(x string) string {
			if env == nil {
				return ""
			}
			return env[x]
		})
	}

	s = strings.TrimSpace(s)
	if !strings.HasPrefix(s, prefix) {
		return "", "", false
	}
	s = strings.TrimSpace(s[len(prefix):])

	p := strings.SplitN(s, " ", 2)
	if len(p) == 2 {
		opts = p[1]
	}
	s = p[0]

	p = strings.SplitN(s, "/", 2)
	if len(p) == 1 {
		log.Printf("[WARN] consul: Invalid %s tag %q - You need to have a trailing slash!", prefix, s)
		return "", "", false
	}
	host, path := p[0], p[1]

	return strings.ToLower(expand(host)) + "/" + expand(path), opts, true
}
开发者ID:eBay,项目名称:fabio,代码行数:35,代码来源:parse.go

示例13: get

func (e *EnvMap) get(
	key string, top *EnvMap, processQueue map[string]*EnvMap,
	cache map[string]string,
) (string, bool) {
	resolve := func(s string) string {
		if value, ok := cache[s]; ok == true {
			return value
		}
		if last, ok := processQueue[s]; ok == true {
			// If this is the last element in this environment map
			// then we return ""
			if last == nil {
				return ""
			}
			processQueue[s] = last.parent
			r, _ := last.get(s, top, processQueue, cache)
			return r
		}
		processQueue[s] = top
		r, _ := top.get(s, top, processQueue, cache)
		return r
	}

	for e != nil {
		if value, ok := e.env[key]; ok == true {
			processQueue[key] = e.parent
			s := os.Expand(value, resolve)
			delete(processQueue, key)
			return s, true
		}
		e = e.parent
	}
	return "", false
}
开发者ID:wallyqs,项目名称:util,代码行数:34,代码来源:envmap.go

示例14: executePostProvision

func (m *Machine) executePostProvision() ([]string, error) {

	fmt.Println("Executing post-provision commands...")

	out := []string{}
	for _, p := range m.postProvision() {

		fmt.Printf("  ... '%s'\n", p)
		args, err := shellwords.Parse(p)
		if err != nil {
			return []string{}, err
		}

		if args[0] == "scp" {
			// it's docker-machine sub-command
			args = append([]string{"docker-machine", "-s", dpmHome()}, args...)
		}

		for i := range args {
			args[i] = os.Expand(args[i], func(key string) string { return m.expand(key) })
		}

		cmd := exec.Command(args[0], args[1:]...)

		if args[0] == "docker" {
			cmd.Env = m.GetEnv()
		}

		o, err := cmd.CombinedOutput()
		out = append(out, string(o))
	}
	return out, nil
}
开发者ID:prachpub,项目名称:dpm,代码行数:33,代码来源:provision.go

示例15: ExpandFromMap

func ExpandFromMap(template string, m map[string]interface{}) string {
	return os.Expand(template, func(s string) string {
		if v, ok := m[s]; ok {
			return fmt.Sprintf("%v", v)
		}
		return "[?]"
	})
}
开发者ID:robertocs,项目名称:cepiot,代码行数:8,代码来源:template.go


注:本文中的os.Expand函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。