Exemplo n.º 1
0
func diff(aFilePath, bFilePath string) {
	aFile, err := ioutil.ReadFile(aFilePath)
	if err != nil {
		log.Fatalln("error reading a:", err)
	}

	aYAML, err := yaml.Parse(aFile)
	if err != nil {
		log.Fatalln("error parsing a:", err)
	}

	bFile, err := ioutil.ReadFile(bFilePath)
	if err != nil {
		log.Fatalln("error reading b:", err)
	}

	bYAML, err := yaml.Parse(bFile)
	if err != nil {
		log.Fatalln("error parsing b:", err)
	}

	diffs := compare.Compare(aYAML, bYAML)

	if len(diffs) == 0 {
		fmt.Println("no differences!")
		return
	}

	for _, diff := range diffs {
		fmt.Println("Difference in", strings.Join(diff.Path, "."))

		if diff.A != nil {
			ayaml, err := goyaml.Marshal(diff.A)
			if err != nil {
				panic(err)
			}

			fmt.Printf("  %s has:\n    \x1b[31m%s\x1b[0m\n", aFilePath, strings.Replace(string(ayaml), "\n", "\n    ", -1))
		}

		if diff.B != nil {
			byaml, err := goyaml.Marshal(diff.B)
			if err != nil {
				panic(err)
			}

			fmt.Printf("  %s has:\n    \x1b[32m%s\x1b[0m\n", bFilePath, strings.Replace(string(byaml), "\n", "\n    ", -1))
		}
	}
}
Exemplo n.º 2
0
func (s *S) TestMarshalTypeCache(c *C) {
	var data []byte
	var err error
	func() {
		type T struct{ A int }
		data, err = goyaml.Marshal(&T{})
		c.Assert(err, IsNil)
	}()
	func() {
		type T struct{ B int }
		data, err = goyaml.Marshal(&T{})
		c.Assert(err, IsNil)
	}()
	c.Assert(string(data), Equals, "b: 0\n")
}
Exemplo n.º 3
0
func SaveAuthToken(configPath, authtoken string) (err error) {
	// read the configuration
	oldConfigBytes, err := ioutil.ReadFile(configPath)
	if err != nil {
		return
	}

	c := new(Configuration)
	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
}
Exemplo n.º 4
0
// SaveState writes the given state to the given storage.
func SaveState(storage StorageWriter, state *BootstrapState) error {
	data, err := goyaml.Marshal(state)
	if err != nil {
		return err
	}
	return storage.Put(StateFile, bytes.NewBuffer(data), int64(len(data)))
}
Exemplo n.º 5
0
// Write implements EnvironInfo.Write.
func (info *environInfo) Write() error {
	info.mu.Lock()
	defer info.mu.Unlock()
	data, err := goyaml.Marshal(info.EnvInfo)
	if err != nil {
		return errors.Annotate(err, "cannot marshal environment info")
	}
	// Create a temporary file and rename it, so that the data
	// changes atomically.
	parent, _ := filepath.Split(info.path)
	tmpFile, err := ioutil.TempFile(parent, "")
	if err != nil {
		return errors.Annotate(err, "cannot create temporary file")
	}
	_, err = tmpFile.Write(data)
	// N.B. We need to close the file before renaming it
	// otherwise it will fail under Windows with a file-in-use
	// error.
	tmpFile.Close()
	if err != nil {
		return errors.Annotate(err, "cannot write temporary file")
	}
	if err := utils.ReplaceFile(tmpFile.Name(), info.path); err != nil {
		os.Remove(tmpFile.Name())
		return errors.Annotate(err, "cannot rename new environment info file")
	}
	info.initialized = true
	return nil
}
Exemplo n.º 6
0
func (yh YamlHacker) Reader() io.Reader {
	data, err := goyaml.Marshal(yh)
	if err != nil {
		panic(err)
	}
	return bytes.NewBuffer(data)
}
Exemplo n.º 7
0
func renameRelation(c *C, charmPath, oldName, newName string) {
	path := filepath.Join(charmPath, "metadata.yaml")
	f, err := os.Open(path)
	c.Assert(err, IsNil)
	defer f.Close()
	meta, err := charm.ReadMeta(f)
	c.Assert(err, IsNil)

	replace := func(what map[string]charm.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, Equals, true, Commentf("charm %q does not implement relation %q", charmPath, oldName))

	newmeta, err := goyaml.Marshal(meta)
	c.Assert(err, IsNil)
	ioutil.WriteFile(path, newmeta, 0644)

	f, err = os.Open(path)
	c.Assert(err, IsNil)
	defer f.Close()
	meta, err = charm.ReadMeta(f)
	c.Assert(err, IsNil)
}
Exemplo n.º 8
0
func (e *environ) saveState(state *bootstrapState) error {
	data, err := goyaml.Marshal(state)
	if err != nil {
		return err
	}
	return e.Storage().Put(stateFile, bytes.NewBuffer(data), int64(len(data)))
}
Exemplo n.º 9
0
func main() {
	var file string
	flag.StringVar(&file, "f", "", "Path to file to convert.")
	flag.Parse()
	if file == "" {
		flag.Usage()
		return
	}
	resource, err := apidef.ParseFile(file)
	if err != nil {
		panic(err)
	}
	data, err := goyaml.Marshal(&resource)
	if err != nil {
		panic(err)
	}
	fileInfo, err := os.Lstat(file)
	if err != nil {
		panic(err)
	}
	file = strings.Replace(file, ".json", ".yml", -1)
	err = ioutil.WriteFile(file, data, fileInfo.Mode())
	if err != nil {
		panic(err)
	}
}
Exemplo n.º 10
0
func (formatter_1_18) marshal(config *configInternal) ([]byte, error) {
	format := &format_1_18Serialization{
		Tag:               config.tag,
		DataDir:           config.dataDir,
		LogDir:            config.logDir,
		Jobs:              config.jobs,
		UpgradedToVersion: &config.upgradedToVersion,
		Nonce:             config.nonce,
		CACert:            string(config.caCert),
		OldPassword:       config.oldPassword,
		Values:            config.values,
	}
	if config.servingInfo != nil {
		format.StateServerCert = config.servingInfo.Cert
		format.StateServerKey = config.servingInfo.PrivateKey
		format.APIPort = config.servingInfo.APIPort
		format.StatePort = config.servingInfo.StatePort
		format.SharedSecret = config.servingInfo.SharedSecret
		format.SystemIdentity = config.servingInfo.SystemIdentity
	}
	if config.stateDetails != nil {
		format.StateAddresses = config.stateDetails.addresses
		format.StatePassword = config.stateDetails.password
	}
	if config.apiDetails != nil {
		format.APIAddresses = config.apiDetails.addresses
		format.APIPassword = config.apiDetails.password
	}
	return goyaml.Marshal(format)
}
Exemplo n.º 11
0
// Load configuration settings and setup database connection
func init() {
	globalSettings := make(map[string]string)
	var confFile string
	flag.StringVar(&confFile, "config", "config.yml", "Path to config file")
	flag.Parse()
	if confFile, err := filepath.Abs(confFile); err != nil {
		log.Printf("Cannot find configuration file '%v', using default settings", confFile)
	} else if raw, err := ioutil.ReadFile(confFile); err != nil {
		log.Printf("[%v] Cannot load configuration file '%v', using default settings", os.Getpid(), confFile)
	} else {
		err := goyaml.Unmarshal(raw, &globalSettings)
		if err != nil {
			log.Printf("Cannot load configuration settings: %v", err)
		}
	}
	for setting, value := range defaultSettings() {
		if _, ok := globalSettings[setting]; !ok {
			globalSettings[setting] = value
		}
	}
	msg, err := goyaml.Marshal(&globalSettings)
	if err != nil {
		log.Fatalf("Could not log settings: %v", err)
	}
	log.Printf("Startup settings:\n%s", msg)

	gotcha.StartSession(globalSettings["mongoHost"], globalSettings["mongoUser"],
		globalSettings["mongoPassword"], globalSettings["environment"])
}
Exemplo n.º 12
0
// 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)
}
Exemplo n.º 13
0
Arquivo: init.go Projeto: kublaj/zas
func init() {
	cmdInit.Run = func() {
		path, _ := filepath.Abs(ZAS_DIR)
		if _, err := os.Stat(ZAS_DIR); os.IsNotExist(err) {
			os.Mkdir(ZAS_DIR, os.FileMode(ZAS_DEFAULT_DIR_PERM))
			fmt.Printf("Initialized empty %s repository in %s\n", ZAS_NAME, path)
		} else {
			fmt.Printf("Reinitialized existing %s repository in %s\n", ZAS_NAME, path)
		}
		var (
			data []byte
			err  error
		)
		// If default config variable has fields, we store it as ZAS_CONF_FILE (as defined in constants.go).
		// It overwrites every time we invoke init subcommand.
		if len(ZAS_DEFAULT_CONF) > 0 {
			if data, err = yaml.Marshal(&ZAS_DEFAULT_CONF); err != nil {
				panic(err)
			}
		}
		if err := ioutil.WriteFile(ZAS_CONF_FILE, data, os.FileMode(ZAS_DEFAULT_FILE_PERM)); err != nil {
			panic(err)
		}
	}
	cmdInit.Init()
}
Exemplo n.º 14
0
func (s *S) TestMarshal(c *C) {
	for _, item := range marshalTests {
		data, err := goyaml.Marshal(item.value)
		c.Assert(err, IsNil)
		c.Assert(string(data), Equals, item.data)
	}
}
Exemplo n.º 15
0
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, gc.IsNil)
	for _, t := range getTests {
		ctx := coretesting.Context(c)
		code := cmd.Main(&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, gc.IsNil)
		expected := make(map[string]interface{})
		err = goyaml.Unmarshal(buf, &expected)
		c.Assert(err, gc.IsNil)

		actual := make(map[string]interface{})
		err = goyaml.Unmarshal(ctx.Stdout.(*bytes.Buffer).Bytes(), &actual)
		c.Assert(err, gc.IsNil)
		c.Assert(actual, gc.DeepEquals, expected)
	}
}
Exemplo n.º 16
0
func (m b64yaml) encode() string {
	data, err := goyaml.Marshal(m)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(data)
}
Exemplo n.º 17
0
// Render returns the cloud-init configuration as a YAML file.
func (cfg *Config) Render() ([]byte, error) {
	data, err := yaml.Marshal(cfg.attrs)
	if err != nil {
		return nil, err
	}
	return append([]byte("#cloud-config\n"), data...), nil
}
Exemplo n.º 18
0
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
}
Exemplo n.º 19
0
// cloudinitRunCmd returns the shell command that, when run, will create the
// "machine info" file containing the hostname of a machine.
// That command is destined to be used by cloudinit.
func (info *machineInfo) cloudinitRunCmd() (string, error) {
	yaml, err := goyaml.Marshal(info)
	if err != nil {
		return "", err
	}
	script := fmt.Sprintf(`mkdir -p %s; echo -n %s > %s`, utils.ShQuote(environs.DataDir), utils.ShQuote(string(yaml)), utils.ShQuote(_MAASInstanceFilename))
	return script, nil
}
Exemplo n.º 20
0
func (s *S) TestUnmarshalWholeDocumentWithGetter(c *C) {
	obj := &typeWithGetter{}
	obj.tag = ""
	obj.value = map[string]string{"hello": "world!"}
	data, err := goyaml.Marshal(obj)
	c.Assert(err, IsNil)
	c.Assert(string(data), Equals, "hello: world!\n")
}
Exemplo n.º 21
0
func SaveConfig(file string, config *Config) (err error) {
	data, err := yaml.Marshal(config)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(file, data, 0644)
	return
}
Exemplo n.º 22
0
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)
}
Exemplo n.º 23
0
func (cc CloudConfig) String() string {
	bytes, err := goyaml.Marshal(cc)
	if err == nil {
		return string(bytes)
	} else {
		return ""
	}
}
Exemplo n.º 24
0
func (c *Config) String() string {

	d, err := goyaml.Marshal(c)
	if err != nil {
		glog.Fatal(err)
	}
	return string(d)
}
Exemplo n.º 25
0
func (s *S) BenchmarkMarshal(c *C) {
	var v map[string]interface{}
	goyaml.Unmarshal(data, &v)
	c.ResetTimer()
	for i := 0; i < c.N; i++ {
		goyaml.Marshal(&v)
	}
}
Exemplo n.º 26
0
func formatYAML(yaml yaml.Node) string {
	formatted, err := goyaml.Marshal(yaml)
	if err != nil {
		return fmt.Sprintf("\n\t<%T> %#v", yaml, yaml)
	}

	return fmt.Sprintf("\n\t%s", strings.Replace(string(formatted), "\n", "\n\t", -1))
}
Exemplo n.º 27
0
func (conf *GitWatchConfig) PrintConfig() {
	d, err := goyaml.Marshal(conf)
	if err != nil {
		fmt.Println("Marshal error", err)
		return
	}
	fmt.Println(string(d))
}
Exemplo n.º 28
0
// Return the given interface as a YAML byte slice.
func ToYaml(i interface{}) []byte {
	data, err1 := goyaml.Marshal(i)
	if err1 != nil {
		panic(err1)
		return []byte{}
	}
	return data
}
Exemplo n.º 29
0
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
}
Exemplo n.º 30
0
func PrintConfig(conf *BotConfig) {
	d, err := goyaml.Marshal(conf)
	if err != nil {
		fmt.Println("Marshal error", err)
		return
	}
	fmt.Println("-- Configuration --")
	fmt.Println(string(d))
}