func main() { t := CircleCIConfig{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) for _, p := range t.Test.Pre { fmt.Println(p) } }
func renameRelation(c *gc.C, charmPath, oldName, newName string) { path := filepath.Join(charmPath, "metadata.yaml") f, err := os.Open(path) c.Assert(err, jc.ErrorIsNil) defer f.Close() meta, err := corecharm.ReadMeta(f) c.Assert(err, jc.ErrorIsNil) replace := func(what map[string]corecharm.Relation) bool { for relName, relation := range what { if relName == oldName { what[newName] = relation delete(what, oldName) return true } } return false } replaced := replace(meta.Provides) || replace(meta.Requires) || replace(meta.Peers) c.Assert(replaced, gc.Equals, true, gc.Commentf("charm %q does not implement relation %q", charmPath, oldName)) newmeta, err := goyaml.Marshal(meta) c.Assert(err, jc.ErrorIsNil) ioutil.WriteFile(path, newmeta, 0644) f, err = os.Open(path) c.Assert(err, jc.ErrorIsNil) defer f.Close() _, err = corecharm.ReadMeta(f) c.Assert(err, jc.ErrorIsNil) }
// toYAML converts the given structure into a deeply nested YAML string. func toYAML(m map[string]interface{}) (string, error) { result, err := yaml.Marshal(m) if err != nil { return "", errors.Wrap(err, "toYAML") } return string(bytes.TrimSpace(result)), nil }
func (s *HollowStash) Save() error { dir, filename := filepath.Split(s.InventoryFile) f, err := ioutil.TempFile(dir, filename) if err != nil { return err } defer f.Close() b, err := yaml.Marshal(*s) if err != nil { return err } _, err = f.Write(b) if err != nil { return err } err = os.Rename(s.InventoryFile, s.InventoryFile+".bak") if err != nil { return err } os.Rename(f.Name(), s.InventoryFile) if err != nil { return err } return nil }
// toYAML converts the given structure into a deeply nested YAML string. func toYAML(m map[string]interface{}) (string, error) { result, err := yaml.Marshal(m) if err != nil { return "", fmt.Errorf("toYAML: %s", err) } return string(bytes.TrimSpace(result)), nil }
/* TODO(colhom): when we fully deprecate instanceCIDR/availabilityZone, this block of logic will go away and be replaced by a single constant string */ func defaultConfigValues(t *testing.T, configYaml string) string { defaultYaml := ` externalDNSName: test.staging.core-os.net keyName: test-key-name region: us-west-1 clusterName: test-cluster-name kmsKeyArn: "arn:aws:kms:us-west-1:xxxxxxxxx:key/xxxxxxxxxxxxxxxxxxx" ` yamlStr := defaultYaml + configYaml c := config.Cluster{} if err := yaml.Unmarshal([]byte(yamlStr), &c); err != nil { t.Errorf("failed umarshalling config yaml: %v :\n%s", err, yamlStr) } if len(c.Subnets) > 0 { for i := range c.Subnets { c.Subnets[i].AvailabilityZone = fmt.Sprintf("dummy-az-%d", i) } } else { //Legacy behavior c.AvailabilityZone = "dummy-az-0" } out, err := yaml.Marshal(&c) if err != nil { t.Errorf("error marshalling cluster: %v", err) } return string(out) }
func (s *migrateAgentEnvUUIDSuite) removeEnvUUIDFromAgentConfig(c *gc.C) { // Read the file in as simple map[string]interface{} and delete // the element, and write it back out again. // First step, read the file contents. filename := agent.ConfigPath(agent.DefaultPaths.DataDir, s.machine.Tag()) data, err := ioutil.ReadFile(filename) c.Assert(err, jc.ErrorIsNil) c.Logf("Data in:\n\n%s\n", data) // Parse it into the map. var content map[string]interface{} err = goyaml.Unmarshal(data, &content) c.Assert(err, jc.ErrorIsNil) // Remove the environment value, and marshal back into bytes. delete(content, "environment") data, err = goyaml.Marshal(content) c.Assert(err, jc.ErrorIsNil) // Write the yaml back out remembering to add the format prefix. data = append([]byte("# format 1.18\n"), data...) c.Logf("Data out:\n\n%s\n", data) err = ioutil.WriteFile(filename, data, 0644) c.Assert(err, jc.ErrorIsNil) // Reset test attributes. cfg, err := agent.ReadConfig(filename) c.Assert(err, jc.ErrorIsNil) s.ctx.realAgentConfig = cfg }
func SaveAuthToken(configPath, authtoken string) (err error) { // empty configuration by default for the case that we can't read it c := new(Configuration) // read the configuration oldConfigBytes, err := ioutil.ReadFile(configPath) if err == nil { // unmarshal if we successfully read the configuration file if err = goyaml.Unmarshal(oldConfigBytes, c); err != nil { return } } // no need to save, the authtoken is already the correct value if c.AuthToken == authtoken { return } // update auth token c.AuthToken = authtoken // rewrite configuration newConfigBytes, err := goyaml.Marshal(c) if err != nil { return } err = ioutil.WriteFile(configPath, newConfigBytes, 0600) return }
func (m b64yaml) encode() string { data, err := goyaml.Marshal(m) if err != nil { panic(err) } return base64.StdEncoding.EncodeToString(data) }
/* The 'getAlert' command returns a GetAlertResponse object. The 'ResultToYaml' function is called whenever "output-format" parameter is set to yaml. */ func resultToYAML(data interface{}) (string, error) { d, err := yaml.Marshal(&data) if err != nil { return "", errors.New("Can not marshal the response into YAML format. " + err.Error()) } return string(d), nil }
// SaveState writes the given state to the given storage. func SaveState(storage storage.StorageWriter, state *BootstrapState) error { data, err := goyaml.Marshal(state) if err != nil { return err } return putState(storage, data) }
func respondError(w http.ResponseWriter, req *http.Request, msg string, statusCode int) { obj := make(map[string]interface{}) obj["message"] = msg obj["type"] = "error" obj["code"] = statusCode switch contentType(req) { case ContentText: http.Error(w, msg, statusCode) case ContentJSON: bytes, err := json.Marshal(obj) if err == nil { http.Error(w, string(bytes), statusCode) } else { http.Error(w, "{\"type\": \"error\", \"message\": \"JSON marshal error\"}", http.StatusInternalServerError) } case ContentYAML: bytes, err := yaml.Marshal(obj) if err == nil { http.Error(w, string(bytes), statusCode) } else { http.Error(w, "type: \"error\"\nmessage: \"JSON marshal error\"", http.StatusInternalServerError) } } }
func (s *cmdControllerSuite) TestControllerLoginCommand(c *gc.C) { user := s.Factory.MakeUser(c, &factory.UserParams{ NoEnvUser: true, Password: "******", }) apiInfo := s.APIInfo(c) serverFile := envcmd.ServerFile{ Addresses: apiInfo.Addrs, CACert: apiInfo.CACert, Username: user.Name(), Password: "******", } serverFilePath := filepath.Join(c.MkDir(), "server.yaml") content, err := goyaml.Marshal(serverFile) c.Assert(err, jc.ErrorIsNil) err = ioutil.WriteFile(serverFilePath, []byte(content), 0644) c.Assert(err, jc.ErrorIsNil) s.run(c, "login", "--server", serverFilePath, "just-a-controller") // Make sure that the saved server details are sufficient to connect // to the api server. api, err := juju.NewAPIFromName("just-a-controller", nil) c.Assert(err, jc.ErrorIsNil) api.Close() }
func (s *GetSuite) TestGetConfig(c *gc.C) { sch := s.AddTestingCharm(c, "dummy") svc := s.AddTestingService(c, "dummy-service", sch) err := svc.UpdateConfigSettings(charm.Settings{"title": "Nearly There"}) c.Assert(err, jc.ErrorIsNil) for _, t := range getTests { ctx := coretesting.Context(c) code := cmd.Main(envcmd.Wrap(&GetCommand{}), ctx, []string{t.service}) c.Check(code, gc.Equals, 0) c.Assert(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "") // round trip via goyaml to avoid being sucked into a quagmire of // map[interface{}]interface{} vs map[string]interface{}. This is // also required if we add json support to this command. buf, err := goyaml.Marshal(t.expected) c.Assert(err, jc.ErrorIsNil) expected := make(map[string]interface{}) err = goyaml.Unmarshal(buf, &expected) c.Assert(err, jc.ErrorIsNil) actual := make(map[string]interface{}) err = goyaml.Unmarshal(ctx.Stdout.(*bytes.Buffer).Bytes(), &actual) c.Assert(err, jc.ErrorIsNil) c.Assert(actual, gc.DeepEquals, expected) } }
func (cs *CassandraStorage) StoreStack(stack *Stack) error { cs.lock.Lock() defer cs.lock.Unlock() exists, err := cs.exists(stack.Name) if err != nil { return err } if exists { Logger.Info("Stack %s already exists", stack.Name) return fmt.Errorf("Stack %s already exists", stack.Name) } if stack.From != "" { exists, err = cs.exists(stack.From) if !exists { Logger.Info("Parent stack %s does not exist", stack.From) return fmt.Errorf("Parent stack %s does not exist", stack.From) } } apps, err := yaml.Marshal(stack.Applications) if err != nil { return err } query := fmt.Sprintf(`INSERT INTO %s.stacks (name, parent, applications) VALUES (?, ?, ?)`, cs.keyspace) err = cs.connection.Query(query, stack.Name, stack.From, apps).Exec() if err != nil { return err } return nil }
func (ts *StackDeployServer) GetStackHandler(w http.ResponseWriter, r *http.Request) { Logger.Debug("Received get stack command") defer r.Body.Close() decoder := json.NewDecoder(r.Body) getRequest := new(GetStackRequest) decoder.Decode(&getRequest) if getRequest.Name == "" { http.Error(w, "Stack name required", http.StatusBadRequest) return } else { stack, err := ts.storage.GetStack(getRequest.Name) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } yamlStack, err := yaml.Marshal(stack) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(yamlStack) } }
func encode(data interface{}) (output []byte, err error) { output, err = yaml.Marshal(data) if err != nil { glog.Errorf("Failed to marshall the structure to yaml, %s, error: %s", data, err) return []byte{}, fmt.Errorf("marshalling failure, data: %V, error: %s", data, err) } return }
func (s *Stack) String() string { yml, err := yaml.Marshal(s) if err != nil { panic(err) } return string(yml) }
// Convert converts a struct (src) to another one (target) using yaml marshalling/unmarshalling. // If the structure are not compatible, this will throw an error as the unmarshalling will fail. func Convert(src, target interface{}) error { newBytes, err := yaml.Marshal(src) if err != nil { return err } return yaml.Unmarshal(newBytes, target) }
func base64yaml(m *config.Config) string { data, err := goyaml.Marshal(m.AllAttrs()) if err != nil { // can't happen, these values have been validated a number of times panic(err) } return base64.StdEncoding.EncodeToString(data) }
func writeCacheFile(filename string, content CacheFile) error { data, err := goyaml.Marshal(content) if err != nil { return errors.Annotate(err, "cannot marshal cache file") } err = ioutil.WriteFile(filename, data, 0600) return errors.Annotate(err, "cannot write file") }
func base64yaml(attrs map[string]interface{}) string { data, err := goyaml.Marshal(attrs) if err != nil { // can't happen, these values have been validated a number of times panic(err) } return base64.StdEncoding.EncodeToString(data) }
// ToYaml takes an interface, marshals it to yaml, and returns a string. It will // always return a string, even on marshal error (empty string). // // This is designed to be called from a template. func ToYaml(v interface{}) string { data, err := yaml.Marshal(v) if err != nil { // Swallow errors inside of a template. return "" } return string(data) }
func respondYAML(w http.ResponseWriter, req *http.Request, val interface{}) { bytes, err := yaml.Marshal(val) if err == nil { w.Write(bytes) } else { respondError(w, req, "Error serializing to YAML: "+err.Error(), http.StatusInternalServerError) } }
func SaveConfig(config *Config, name string) error { data, err := yaml.Marshal(&config) if err != nil { fmt.Println("Failed to marshal the config.") return err } ioutil.WriteFile(configFileName(name), data, 0644) return err }
func main() { //15.209.122.120:4000 etcdAddr := os.Getenv("ETCD_HOST") //hack etcdDir := os.Getenv("WATCH_ETCD_DIR") ///config.yml configfile := os.Getenv("CONFIG") //id_rsa privatekeyfile := os.Getenv("PRIVATE_KEY") //serve container containerid := os.Getenv("SERVE_CONTAINER") machines := []string{fmt.Sprintf("http://%s", etcdAddr)} client := etcd.NewClient(machines) if client == nil { fmt.Errorf("Connection to etcd server failed") } contents, err := ioutil.ReadFile(configfile) if err != nil { fmt.Errorf("Reading file error %s", err) } c := &TopConfig{} if err = yaml.Unmarshal(contents, c); err != nil { fmt.Errorf("UnMarshal error %s", err) } fmt.Printf("Current version is %f \n", c.Version) //watch endpoint := "unix:///var/run/docker.sock" dockerclient, dockererr := docker.NewClient(endpoint) if dockererr != nil { fmt.Errorf("Failed to initiate docker client: %v", dockererr) } for { resp, err := client.Watch(etcdDir, 0, true, nil, nil) if err == nil { fmt.Printf("Action is %s for config: key-> %s value-> %s \n", resp.Action, resp.Node.Key, resp.Node.Value) c, needRestart := updateConfig(c, resp.Node.Key, resp.Node.Value, privatekeyfile) configyaml, err := yaml.Marshal(c) if err != nil { fmt.Errorf("Marshal error %s", err) } err1 := ioutil.WriteFile(configfile, []byte(configyaml), 0666) if err1 != nil { fmt.Errorf("Write file error %s", err1) } if needRestart { fmt.Printf("Restarting container %s \n", containerid) err = dockerclient.RestartContainer(containerid, 10) if err != nil { fmt.Errorf("Restart container fail %s", err) } } } } }
func encodeArgs(hooks []string) []byte { // Marshal to YAML, then encode in base64 to avoid shell escapes. yamlArgs, err := goyaml.Marshal(hookArgs{Hooks: hooks}) if err != nil { // This should not happen: we're in full control. panic(err) } return yamlArgs }
func (a *Application) String() string { a.RLock() yml, err := yaml.Marshal(a) a.RUnlock() if err != nil { panic(err) } return string(yml) }
func (suite *StateSuite) setUpSavedState(c *gc.C, dataDir string) common.BootstrapState { state := common.BootstrapState{ StateInstances: []instance.Id{instance.Id("an-instance-id")}, } content, err := goyaml.Marshal(state) c.Assert(err, jc.ErrorIsNil) err = ioutil.WriteFile(filepath.Join(dataDir, common.StateFile), []byte(content), 0644) c.Assert(err, jc.ErrorIsNil) return state }
func (s *ConstraintsSuite) TestRoundtripYaml(c *gc.C) { for _, t := range constraintsRoundtripTests { c.Logf("test %s", t.Name) data, err := goyaml.Marshal(t.Value) c.Assert(err, jc.ErrorIsNil) var cons constraints.Value err = goyaml.Unmarshal(data, &cons) c.Check(err, jc.ErrorIsNil) c.Check(cons, jc.DeepEquals, t.Value) } }