func safeName(name string) string { travis, haveTravis := syscall.Getenv("TRAVIS") buildId, haveBuildId := syscall.Getenv("TRAVIS_JOB_NUMBER") if !haveTravis || !haveBuildId || travis != "true" { return name } return name + "_travis-" + buildId }
func main() { es_access_key, ok := syscall.Getenv("ES_ACCESS_KEY") if ok != true { fmt.Printf("You must set the environment variable: ES_ACCESS_KEY\n") os.Exit(1) } es_secret_key, ok := syscall.Getenv("ES_SECRET_KEY") if ok != true { fmt.Printf("You must set the environment variable: ES_SECRET_KEY\n") os.Exit(1) } url := "https://api.enstratus.com/api/enstratus/2012-06-15/geography/Cloud" request, _ := http.NewRequest("GET", url, nil) request.Header.Add("accept", "application/json") request.Header.Add("x-esauth-access", es_access_key) request.Header.Add("x-esauth-timestamp", string(GetTimeString())) request.Header.Add("x-es-details", "basic") request.Header.Add("user-agent", ES_UA) sig := SignRequest(es_access_key, es_secret_key, ES_UA, "GET", "geography/Cloud") request.Header.Add("x-esauth-signature", sig) client := &http.Client{} response, err := client.Do(request) if err != nil { fmt.Printf("%s", err) os.Exit(1) } else { defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Printf("%s", err) os.Exit(1) } switch { case response.StatusCode >= 400 && response.StatusCode <= 599: e := &EnstratusError{} err := json.Unmarshal([]byte(contents), &e) if err != nil { fmt.Printf("JSON Decoding error: %s\n", err) os.Exit(1) } fmt.Printf("%s\n", e.Error.Message) os.Exit(1) } clouds := &CloudList{} jsonerr := json.Unmarshal([]byte(contents), &clouds) if jsonerr != nil { fmt.Printf("JSON Decoding error: %s\n", jsonerr) os.Exit(1) } spew.Dump(clouds) } }
func getEnv(e1, e2, d string) string { if r, found := syscall.Getenv(e1); found { return r } if r, found := syscall.Getenv(e2); found { return r } return d }
func initLocal() { // consult $TZ to find the time zone to use. // no $TZ means use the system default /etc/localtime. // $TZ="" means use UTC. // $TZ="foo" means use /usr/share/zoneinfo/foo. tz, ok := syscall.Getenv("TZ") switch { case !ok: z, err := loadZoneFile("", "/etc/localtime") if err == nil { localLoc = *z localLoc.name = "Local" return } case tz != "" && tz != "UTC": if z, err := loadLocation(tz); err == nil { localLoc = *z return } } // Fall back to UTC. localLoc.name = "UTC" }
// ServerMode returns the Gin server mode as per environment or default. func ServerMode() string { mode, ok := syscall.Getenv("SERVER_MODE") if !ok { mode = DefaultServerMode } return mode }
// ApplyWithError populates the flag given the flag set and environment func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error { val := true if f.EnvVar != "" { for _, envVar := range strings.Split(f.EnvVar, ",") { envVar = strings.TrimSpace(envVar) if envVal, ok := syscall.Getenv(envVar); ok { if envVal == "" { val = false break } envValBool, err := strconv.ParseBool(envVal) if err != nil { return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) } val = envValBool break } } } eachName(f.Name, func(name string) { if f.Destination != nil { set.BoolVar(f.Destination, name, val, f.Usage) return } set.Bool(name, val, f.Usage) }) return nil }
func main() { flag.Parse() dir := flag.Arg(0) // new directory x | xx | xxx pwd, _ := syscall.Getenv("PWD") // ~/aaa/bbbb/xxx/yyy/zzzzz tb := str.Split(pwd, "/") newPath := "" isPresent := false for i := 0; i < len(tb); i++ { newPath += tb[i] + "/" if str.HasPrefix(tb[i], dir) { isPresent = true break } } if !isPresent { err := "Directory " + dir + " non trouvé dans path " + pwd fmt.Println(err) os.Exit(16) // echo $? } fmt.Println("cd " + newPath) // ~/aaa/bbbb/xxx/ }
// ApplyWithError populates the flag given the flag set and environment func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error { if f.EnvVar != "" { for _, envVar := range strings.Split(f.EnvVar, ",") { envVar = strings.TrimSpace(envVar) if envVal, ok := syscall.Getenv(envVar); ok { envValDuration, err := time.ParseDuration(envVal) if err != nil { return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err) } f.Value = envValDuration break } } } eachName(f.Name, func(name string) { if f.Destination != nil { set.DurationVar(f.Destination, name, f.Value, f.Usage) return } set.Duration(name, f.Value, f.Usage) }) return nil }
// ApplyWithError populates the flag given the flag set and environment func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error { if f.EnvVar != "" { for _, envVar := range strings.Split(f.EnvVar, ",") { envVar = strings.TrimSpace(envVar) if envVal, ok := syscall.Getenv(envVar); ok { envValFloat, err := strconv.ParseFloat(envVal, 10) if err != nil { return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err) } f.Value = float64(envValFloat) break } } } eachName(f.Name, func(name string) { if f.Destination != nil { set.Float64Var(f.Destination, name, f.Value, f.Usage) return } set.Float64(name, f.Value, f.Usage) }) return nil }
func TestFixedGOROOT(t *testing.T) { if runtime.GOOS == "plan9" { t.Skipf("skipping plan9, it is inconsistent by allowing GOROOT to be updated by Setenv") } // Restore both the real GOROOT environment variable, and runtime's copies: if orig, ok := syscall.Getenv("GOROOT"); ok { defer syscall.Setenv("GOROOT", orig) } else { defer syscall.Unsetenv("GOROOT") } envs := runtime.Envs() oldenvs := append([]string{}, envs...) defer runtime.SetEnvs(oldenvs) // attempt to reuse existing envs backing array. want := runtime.GOROOT() runtime.SetEnvs(append(envs[:0], "GOROOT="+want)) if got := runtime.GOROOT(); got != want { t.Errorf(`initial runtime.GOROOT()=%q, want %q`, got, want) } if err := syscall.Setenv("GOROOT", "/os"); err != nil { t.Fatal(err) } if got := runtime.GOROOT(); got != want { t.Errorf(`after setenv runtime.GOROOT()=%q, want %q`, got, want) } if err := syscall.Unsetenv("GOROOT"); err != nil { t.Fatal(err) } if got := runtime.GOROOT(); got != want { t.Errorf(`after unsetenv runtime.GOROOT()=%q, want %q`, got, want) } }
// ServerConfig returns the Gin server config as per environment or default. func ServerConfig() string { addr, _ := syscall.Getenv("SERVER_ADDR") var port string if portStr, ok := syscall.Getenv("SERVER_PORT"); !ok { port = DefaultPort } else { portUInt, err := strconv.ParseUint(portStr, 10, 16) if err != nil || portUInt > 65535 { log.Notice("Invalid port \"%s\", using %s instead.", portStr, DefaultPort) port = DefaultPort } else { port = portStr } } return fmt.Sprintf("%s:%s", addr, port) }
func init() { switch path, _ := syscall.Getenv("GOCOVOUT"); path { case "": // No tracing case "-": Default.Tracer = fdwriter(syscall.Stdout) default: // Add the process ID to the filename. // TODO handle PID reuse by checking if file exists. path += "." + itoa(syscall.Getpid()) mode := syscall.O_WRONLY | syscall.O_CREAT | syscall.O_TRUNC fd, err := syscall.Open(path, mode, 0666) if err != nil { msg := "gocov: failed to create log file: " msg += err.Error() + "\n" write(fdwriter(syscall.Stderr), []byte(msg)) syscall.Exit(1) } Default.Tracer = fdwriter(int(fd)) } // Remove GOCOVOUT from environ, to prevent noise from child processes. // TODO Don't do this; append .pid to output filename. syscall.Setenv("GOCOVOUT", "") }
// ApplyWithError populates the flag given the flag set and environment func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error { if f.EnvVar != "" { for _, envVar := range strings.Split(f.EnvVar, ",") { envVar = strings.TrimSpace(envVar) if envVal, ok := syscall.Getenv(envVar); ok { newVal := &Int64Slice{} for _, s := range strings.Split(envVal, ",") { s = strings.TrimSpace(s) if err := newVal.Set(s); err != nil { return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err) } } f.Value = newVal break } } } eachName(f.Name, func(name string) { if f.Value == nil { f.Value = &Int64Slice{} } set.Var(f.Value, name, f.Usage) }) return nil }
func init() { log.EnableDebugLogging() flag.StringVar(&add, "add", "", "Server to add to the connection manager") flag.StringVar(&connect, "connect", "", "Stored server to connect to") flag.StringVar(&domain, "domain", "", "AD domain") flag.StringVar(&ip, "ip", "", "Server ip address") flag.BoolVar(&list, "list", false, "List the stored servers") flag.BoolVar(&nla, "nla", true, "Use network level authentication (yes/no)") flag.BoolVar(&debug, "debug", false, "Enable debugging") flag.StringVar(&remove, "remove", "", "Server to remove from the connection manager") flag.StringVar(&username, "username", "", "AD username") flag.StringVar(&app, "app", "", "Remote Application") homePath, _ := syscall.Getenv("HOME") configFile = path.Join(homePath, ".xfcm") // check if the configuration file exists filePathExists, err := pathExists(configFile, true) // print if we encountered an error checking if the path existed if err != nil { log.Error(err) } // if the path didn't exist, create the file if !filePathExists { createConfigFile(configFile) } }
// applyWithError populates the flag given the flag set and environment func (f UintFlag) applyWithError(set *flag.FlagSet) error { if f.EnvVar != "" { for _, envVar := range strings.Split(f.EnvVar, ",") { envVar = strings.TrimSpace(envVar) if envVal, ok := syscall.Getenv(envVar); ok { envValInt, err := strconv.ParseUint(envVal, 0, 64) if err != nil { return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err) } f.Value = uint(envValInt) break } } } eachName(f.Name, func(name string) { if f.Destination != nil { set.UintVar(f.Destination, name, f.Value, f.Usage) return } set.Uint(name, f.Value, f.Usage) }) return nil }
func initLocal() { // 初始化location // consult $TZ to find the time zone to use. // no $TZ means use the system default /etc/localtime. // $TZ="" means use UTC. // $TZ="foo" means use /usr/share/zoneinfo/foo. tz, ok := syscall.Getenv("TZ") // 查询TZ变量 switch { case !ok: // 如果不存在TZ变量 z, err := loadZoneFile("", "/etc/localtime") // 从etc载入localtime文件 if err == nil { // 如果没有错误 localLoc = *z // 设置localLoc localLoc.name = "Local" // 设置location名 return } case tz != "" && tz != "UTC": // 存在tz变量,并且不等于空和UTC if z, err := loadLocation(tz); err == nil { localLoc = *z return } } // Fall back to UTC. localLoc.name = "UTC" // 设置location为UTC }
func loadString(name string, out *reflect.Value) { data, found := syscall.Getenv(name) if !found { return } out.SetString(data) }
func initTest(t *testing.T) (*Client, *Index) { appID, haveAppID := syscall.Getenv("ALGOLIA_APPLICATION_ID") apiKey, haveApiKey := syscall.Getenv("ALGOLIA_API_KEY") if !haveApiKey || !haveAppID { t.Fatalf("Need ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY") } client := NewClient(appID, apiKey) client.SetTimeout(1000, 10000) hosts := make([]string, 3) hosts[0] = appID + "-1.algolia.net" hosts[1] = appID + "-2.algolia.net" hosts[2] = appID + "-3.algolia.net" client = NewClientWithHosts(appID, apiKey, hosts) index := client.InitIndex(safeName("àlgol?à-go")) return client, index }
func readEnvParam(name string) syscall.Handle { v, _ := syscall.Getenv(name) var x uintptr for i := 0; i < len(v); i++ { x = x*10 + uintptr(v[i]-'0') } return syscall.Handle(x) }
func loadBool(name string, out *reflect.Value) { data, found := syscall.Getenv(name) if !found { return } result := data != "0" && data != "false" out.SetBool(result) }
// Fetch data from system env, based on existing config keys. func (cfg *Config) Env() *Config { keys := getKeys(cfg.Root) for _, key := range keys { if val, exist := syscall.Getenv(strings.ToUpper(strings.Join(key, "_"))); exist { cfg.Set(strings.Join(key, "."), val) } } return cfg }
func Test_ReadEnv(t *testing.T) { clear() err := ReadEnv("test/.env") assert.NoError(t, err) assert.Equal(t, "jpfuentes2", os.Getenv("TWITTER")) assert.Equal(t, "jpfuentes2", os.Getenv("GITHUB")) assert.Equal(t, "http://jacquesfuentes.com", os.Getenv("WEB")) // should not exist _, found := syscall.Getenv("A_COMMENT") assert.False(t, found) // should exist but be blank blank, found := syscall.Getenv("BLANK_COMMENT") assert.True(t, found) assert.Equal(t, "", blank) }
// Getenverror retrieves the value of the environment variable named by the key. // It returns the value and an error, if any. func Getenverror(key string) (value string, err error) { if len(key) == 0 { return "", EINVAL } val, found := syscall.Getenv(key) if !found { return "", ENOENV } return val, nil }
func ExpandEnv(s string) string { return os.Expand(s, func(key string) string { if key == "$" { return key } else { v, _ := syscall.Getenv(key) return v } }) }
func loadInteger(name string, out *reflect.Value) { data, found := syscall.Getenv(name) if !found { return } d, err := strconv.ParseInt(data, 10, 64) if err != nil { panic(fmt.Errorf("field type of %s cannot be parsed into integer", name)) } out.SetInt(d) }
func isEnvVarSet(envVars string) bool { for _, envVar := range strings.Split(envVars, ",") { envVar = strings.TrimSpace(envVar) if _, ok := syscall.Getenv(envVar); ok { // TODO: Can't use this for bools as // set means that it was true or false based on // Bool flag type, should work for other types return true } } return false }
func testSetGetenv(t *testing.T, key, value string) { err := syscall.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := syscall.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } }
func ssh(instances *ec2.InstancesResp) { found := 0 list := make([]string, 0) var name, address string for _, reservation := range instances.Reservations { for _, instance := range reservation.Instances { vpc := instance.VpcId name = "UNNAMED" for _, tag := range instance.Tags { if tag.Key == "Name" { name = tag.Value } } // print name dnsName := instance.DNSName if dnsName == "" { dnsName = "-" } ipAddress := instance.PrivateIpAddress if ipAddress == "" { ipAddress = "-" } if vpc != "" { address = ipAddress } else { address = dnsName } list = append(list, name+": "+address) found++ } } if found > 1 { fmt.Println("Too many matches. Be more specific:") for _, item := range list { fmt.Println(item) } os.Exit(3) } fmt.Println("Launching SSH to", name, "at", address) sshCommand, err := exec.LookPath("ssh") if err != nil { fmt.Println("Couldn't find SSH...") os.Exit(5) } terminal, _ := syscall.Getenv("TERM") fmt.Println("Terminal:", terminal) //cmd := exec.Command("setterm", "-term "+terminal) //cmd.Run() syscall.Exec(sshCommand, []string{"ssh", address}, []string{"TERM=" + terminal}) }
// Parse parses environment variables into v, which must be a pointer to a // struct. Because of the way envvar uses reflection, the fields in v must be // exported, i.e. start with a capital letter. For each field in v, Parse will // get the environment variable with the same name as the field and set the // field to the value of that environment variable, converting it to the // appropriate type if needed. // // Parse supports two struct tags, which can be used together or separately. The // struct tag `envvar` can be used to specify the name of the environment // variable that corresponds to a field. If the `envvar` struct tag is not // provided, the default is to look for an environment variable with the same // name as the field. The struct tag `default` can be used to set the default // value for a field. The default value must be a string, but will be converted // to match the type of the field as needed. If the `default` struct tag is not // provided, the corresponding environment variable is required, and Parse will // return an error if it is not defined. When the `default` struct tag is // provided, the environment variable is considered optional, and if set, the // value of the environment variable will override the default value. // // Parse will return an UnsetVariableError if a required environment variable // was not set. It will also return an error if there was a problem converting // environment variable values to the proper type or setting the fields of v. func Parse(v interface{}) error { // Make sure the type of v is what we expect. typ := reflect.TypeOf(v) if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct { return fmt.Errorf("envvar: Error in Parse: type must be a pointer to a struct. Got: %T", v) } structType := typ.Elem() val := reflect.ValueOf(v) if val.IsNil() { return fmt.Errorf("envvar: Error in Parse: argument cannot be nil.") } structVal := val.Elem() // Iterate through the fields of v and set each field. for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) varName := field.Name customName := field.Tag.Get("envvar") if customName != "" { varName = customName } var varVal string defaultVal, foundDefault, err := getStructTag(field, "default") if err != nil { return err } envVal, foundEnv := syscall.Getenv(varName) if foundEnv { // If we found an environment variable corresponding to this field. Use // the value of the environment variable. This overrides the default // (if any). varVal = envVal } else { if foundDefault { // If we did not find an environment variable corresponding to this // field, but there is a default value, use the default value. varVal = defaultVal } else { // If we did not find an environment variable corresponding to this // field and there is not a default value, we are missing a required // environment variable. Return an error. return UnsetVariableError{VarName: varName} } } // Set the value of the field. if err := setFieldVal(structVal.Field(i), varName, varVal); err != nil { return err } } return nil }
/* setup() is tasked with running the setup code from within the namespace, * before the target executable is invoked. It is designed to only execute the * correct hooks for the features the namespace was created with. */ func setup() error { // Read in container environment variables. nsId, _ := syscall.Getenv("LXNS_ID") // Read in container configuration. config, e := GetConfig(os.NewFile(3, "-")) if e != nil { return fmt.Errorf("Failed to import configuration: %v", e) } // Create a key set to check flags against. nsCloneFlags := make(map[string]struct{}) for _, v := range config.Features { nsCloneFlags[v] = empty } // Do we have networking namespace? if _, ok := nsCloneFlags["net"]; ok { if e := SetupNetwork(config.NetworkAddr); e != nil { return e } } // Do we have mounting namespace? if _, ok := nsCloneFlags["ns"]; ok { // If we have PID namespace, then mount /proc if _, ok := nsCloneFlags["pid"]; ok { if e := syscall.Mount("proc", "/proc", "proc", syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV, ""); e != nil { return fmt.Errorf("Failed to mount proc: %v", e) } } // Change our root filesystem using pivot_root syscall if len(config.RootFS) > 0 { PivotRoot(config.RootFS) } } // Do we have hostname namespace? if _, ok := nsCloneFlags["uts"]; ok { hostname := fmt.Sprintf("lxns-%s", nsId) if e := syscall.Sethostname([]byte(hostname)); e != nil { return e } } return nil }