Beispiel #1
0
// LoadRepositoriesFile takes a file at the given path and returns a RepoFile object
//
// If this returns ErrRepoOutOfDate, it also returns a recovered RepoFile that
// can be saved as a replacement to the out of date file.
func LoadRepositoriesFile(path string) (*RepoFile, error) {
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	r := &RepoFile{}
	err = yaml.Unmarshal(b, r)
	if err != nil {
		return nil, err
	}

	// File is either corrupt, or is from before v2.0.0-Alpha.5
	if r.APIVersion == "" {
		m := map[string]string{}
		if err = yaml.Unmarshal(b, &m); err != nil {
			return nil, err
		}
		r := NewRepoFile()
		for k, v := range m {
			r.Add(&Entry{
				Name:  k,
				URL:   v,
				Cache: fmt.Sprintf("%s-index.yaml", k),
			})
		}
		return r, ErrRepoOutOfDate
	}

	return r, nil
}
Beispiel #2
0
func main() {
	if len(os.Args) != 3 {
		checkErr(fmt.Errorf(usage))
	}
	specFilename := os.Args[1]
	configFilename := os.Args[2]

	specData, err := ReadConfigData(specFilename)
	checkErr(err)

	spec := EnscopeSpec{}
	err = yaml.Unmarshal(specData, &spec)
	checkErr(err)

	configData, err := ReadConfigData(configFilename)
	checkErr(err)

	var data interface{}

	err = yaml.Unmarshal([]byte(configData), &data)
	checkErr(err)

	xData, err := enscope("", spec, data)
	checkErr(err)

	out, err := yaml.Marshal(xData)
	checkErr(err)

	fmt.Print(string(out))
}
func deployerSuccessHandler(w http.ResponseWriter, r *http.Request) {
	valid := &Configuration{}
	err := yaml.Unmarshal(validConfigurationTestCaseData, valid)
	if err != nil {
		status := fmt.Sprintf("cannot unmarshal test case data:%s", err)
		http.Error(w, status, http.StatusInternalServerError)
		return
	}

	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		status := fmt.Sprintf("cannot read request body:%s", err)
		http.Error(w, status, http.StatusInternalServerError)
		return
	}

	result := &Configuration{}
	if err := yaml.Unmarshal(body, result); err != nil {
		status := fmt.Sprintf("cannot unmarshal request body:%s", err)
		http.Error(w, status, http.StatusInternalServerError)
		return
	}

	if !reflect.DeepEqual(valid, result) {
		status := fmt.Sprintf("error in http handler:\nwant:%s\nhave:%s\n",
			util.ToYAMLOrError(valid), util.ToYAMLOrError(result))
		http.Error(w, status, http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}
// Unmarshal creates and returns an ExpandedTemplate from an ExpansionResponse.
func (er *ExpansionResponse) Unmarshal() (*ExpandedTemplate, error) {
	template := &ExpandedTemplate{}
	if err := yaml.Unmarshal([]byte(er.Config), &template.Config); err != nil {
		return nil, fmt.Errorf("cannot unmarshal config (%s):\n%s", err, er.Config)
	}

	if err := yaml.Unmarshal([]byte(er.Layout), &template.Layout); err != nil {
		return nil, fmt.Errorf("cannot unmarshal layout (%s):\n%s", err, er.Layout)
	}

	return template, nil
}
Beispiel #5
0
// DecodeInto parses a YAML or JSON string and stores it in obj. Returns an error
// if data.Kind is set and doesn't match the type of obj. Obj should be a
// pointer to an api type.
// If obj's version doesn't match that in data, an attempt will be made to convert
// data into obj's version.
func (s *Scheme) DecodeInto(data []byte, obj interface{}) error {
	if len(data) == 0 {
		// This is valid YAML, but it's a bad idea not to return an error
		// for an empty string-- that's almost certainly not what the caller
		// was expecting.
		return errors.New("empty input")
	}
	dataVersion, dataKind, err := s.DataVersionAndKind(data)
	if err != nil {
		return err
	}
	objVersion, objKind, err := s.ObjectVersionAndKind(obj)
	if err != nil {
		return err
	}
	if dataKind == "" {
		// Assume objects with unset Kind fields are being unmarshalled into the
		// correct type.
		dataKind = objKind
	}
	if dataVersion == "" {
		// Assume objects with unset Version fields are being unmarshalled into the
		// correct type.
		dataVersion = objVersion
	}

	if objVersion == dataVersion {
		// Easy case!
		err = yaml.Unmarshal(data, obj)
		if err != nil {
			return err
		}
	} else {
		external, err := s.NewObject(dataVersion, dataKind)
		if err != nil {
			return err
		}
		// yaml is a superset of json, so we use it to decode here. That way,
		// we understand both.
		err = yaml.Unmarshal(data, external)
		if err != nil {
			return err
		}
		err = s.converter.Convert(external, obj, 0, s.generateConvertMeta(dataVersion, objVersion))
		if err != nil {
			return err
		}
	}

	// Version and Kind should be blank in memory.
	return s.SetVersionAndKind("", "", obj)
}
func TestYAMLPrinterPrint(t *testing.T) {
	type testStruct struct {
		Key        string         `json:"Key"`
		Map        map[string]int `json:"Map"`
		StringList []string       `json:"StringList"`
		IntList    []int          `json:"IntList"`
	}
	testData := testStruct{
		"testValue",
		map[string]int{"TestSubkey": 1},
		[]string{"a", "b", "c"},
		[]int{1, 2, 3},
	}
	printer := &YAMLPrinter{}
	buf := bytes.NewBuffer([]byte{})

	err := printer.Print([]byte("invalidJSON"), buf)
	if err == nil {
		t.Error("Error: didn't fail on invalid JSON data")
	}

	jTestData, err := json.Marshal(&testData)
	if err != nil {
		t.Fatal("Unexpected error: couldn't marshal test data")
	}
	err = printer.Print(jTestData, buf)
	if err != nil {
		t.Fatal(err)
	}
	var poutput testStruct
	err = yaml.Unmarshal(buf.Bytes(), &poutput)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(testData, poutput) {
		t.Errorf("Test data and unmarshaled data are not equal: %#v vs %#v", poutput, testData)
	}

	obj := &api.Pod{
		ObjectMeta: api.ObjectMeta{Name: "foo"},
	}
	buf.Reset()
	printer.PrintObj(obj, buf)
	var objOut api.Pod
	err = yaml.Unmarshal([]byte(buf.String()), &objOut)
	if err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(obj, &objOut) {
		t.Errorf("Unexpected inequality: %#v vs %#v", obj, &objOut)
	}
}
Beispiel #7
0
func tryDecodeSingle(data []byte) (parsed bool, manifest v1beta1.ContainerManifest, pod api.Pod, err error) {
	// TODO: should be api.Scheme.Decode
	// This is awful.  DecodeInto() expects to find an APIObject, which
	// Manifest is not.  We keep reading manifest for now for compat, but
	// we will eventually change it to read Pod (at which point this all
	// becomes nicer).  Until then, we assert that the ContainerManifest
	// structure on disk is always v1beta1.  Read that, convert it to a
	// "current" ContainerManifest (should be ~identical), then convert
	// that to a Pod (which is a well-understood conversion).  This
	// avoids writing a v1beta1.ContainerManifest -> api.Pod
	// conversion which would be identical to the api.ContainerManifest ->
	// api.Pod conversion.
	if err = yaml.Unmarshal(data, &manifest); err != nil {
		return false, manifest, pod, err
	}
	newManifest := api.ContainerManifest{}
	if err = api.Scheme.Convert(&manifest, &newManifest); err != nil {
		return false, manifest, pod, err
	}
	if errs := validation.ValidateManifest(&newManifest); len(errs) > 0 {
		err = fmt.Errorf("invalid manifest: %v", errs)
		return false, manifest, pod, err
	}
	if err = api.Scheme.Convert(&newManifest, &pod); err != nil {
		return true, manifest, pod, err
	}
	// Success.
	return true, manifest, pod, nil
}
func TestStrategicMergePatch(t *testing.T) {
	tc := TestCases{}
	err := yaml.Unmarshal(testCaseData, &tc)
	if err != nil {
		t.Errorf("can't unmarshal test cases: %v", err)
		return
	}

	var e MergeItem
	for _, c := range tc.StrategicMergePatchCases {
		result, err := StrategicMergePatchData(toJSON(c.Original), toJSON(c.Patch), e)
		if err != nil {
			t.Errorf("error patching: %v:\noriginal:\n%s\npatch:\n%s",
				err, toYAML(c.Original), toYAML(c.Patch))
		}

		// Sort the lists that have merged maps, since order is not significant.
		result, err = sortMergeListsByName(result, e)
		if err != nil {
			t.Errorf("error sorting result object: %v", err)
		}
		cResult, err := sortMergeListsByName(toJSON(c.Result), e)
		if err != nil {
			t.Errorf("error sorting result object: %v", err)
		}

		if !reflect.DeepEqual(result, cResult) {
			t.Errorf("patching failed: %s\noriginal:\n%s\npatch:\n%s\nexpected result:\n%s\ngot result:\n%s",
				c.Description, toYAML(c.Original), toYAML(c.Patch), jsonToYAML(cResult), jsonToYAML(result))
		}
	}
}
func readSimpleService(filename string) SimpleService {
	inData, err := ReadConfigData(filename)
	checkErr(err)

	simpleService := SimpleService{}
	err = yaml.Unmarshal(inData, &simpleService)
	checkErr(err)

	if simpleService.Name == "" {
		_, simpleService.Name = ParseDockerImage(simpleService.Image)
		// TODO: encode/scrub the name
	}
	simpleService.Name = strings.ToLower(simpleService.Name)

	// TODO: Validate the image name and extract exposed ports

	// TODO: Do more validation
	if !util.IsDNSLabel(simpleService.Name) {
		checkErr(fmt.Errorf("name (%s) is not a valid DNS label", simpleService.Name))
	}

	if simpleService.Replicas == 0 {
		simpleService.Replicas = 1
	}

	return simpleService
}
Beispiel #10
0
// parseMessageBlock
func parseMessageBlock(data []byte) (*hapi.Metadata, *SumCollection, error) {
	// This sucks.
	parts := bytes.Split(data, []byte("\n...\n"))
	if len(parts) < 2 {
		return nil, nil, errors.New("message block must have at least two parts")
	}

	md := &hapi.Metadata{}
	sc := &SumCollection{}

	if err := yaml.Unmarshal(parts[0], md); err != nil {
		return md, sc, err
	}
	err := yaml.Unmarshal(parts[1], sc)
	return md, sc, err
}
Beispiel #11
0
func TestDurationMarshalJSONUnmarshalYAML(t *testing.T) {
	cases := []struct {
		input Duration
	}{
		{Duration{}},
		{Duration{5 * time.Second}},
		{Duration{2 * time.Minute}},
		{Duration{time.Hour + 3*time.Millisecond}},
	}

	for i, c := range cases {
		input := DurationHolder{c.input}
		jsonMarshalled, err := json.Marshal(&input)
		if err != nil {
			t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err)
		}

		var result DurationHolder
		if err := yaml.Unmarshal(jsonMarshalled, &result); err != nil {
			t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err)
		}

		if input.D != result.D {
			t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result)
		}
	}
}
Beispiel #12
0
func MergeAttributesFilesForMap(omap map[string]interface{}, files []string) map[string]interface{} {

	newMap := make(map[string]interface{})
	newMap["default"] = omap

	// loop over attributes files
	// merge override files to default files
	for _, file := range files {
		var data interface{}
		yml, err := ioutil.ReadFile(file)
		if err != nil {
			panic(err)
		}
		// yaml to data
		err = yaml.Unmarshal(yml, &data)
		if err != nil {
			panic(err)
		}
		data, err = transform(data)
		if err != nil {
			panic(err)
		}
		// data to map
		json := data.(map[string]interface{})
		omap = mergemap.Merge(newMap, json)
	}
	return ProcessOverride(newMap)
}
Beispiel #13
0
// helper function to encode the build step to
// a json string. Primarily used for plugins, which
// expect a json encoded string in stdin or arg[1].
func toCommand(s *State, n *parser.DockerNode) []string {
	p := payload{
		Workspace: s.Workspace,
		Repo:      s.Repo,
		Build:     s.Build,
		Job:       s.Job,
		Vargs:     n.Vargs,
	}

	y, err := yaml.Marshal(n.Vargs)
	if err != nil {
		log.Debug(err)
	}
	p.Vargs = map[string]interface{}{}
	err = yamljson.Unmarshal(y, &p.Vargs)
	if err != nil {
		log.Debug(err)
	}

	p.System = &plugin.System{
		Version: s.System.Version,
		Link:    s.System.Link,
	}

	b, _ := json.Marshal(p)
	return []string{"--", string(b)}
}
func parseCredentials(bytes []byte) ([]NamedRegistryCredential, error) {
	r := []NamedRegistryCredential{}
	if err := yaml.Unmarshal(bytes, &r); err != nil {
		return []NamedRegistryCredential{}, fmt.Errorf("cannot unmarshal credentials file (%#v)", err)
	}
	return r, nil
}
func (d *deployer) callServiceWithConfiguration(method, operation string, configuration *common.Configuration) (*common.Configuration, error) {
	callback := func(e error) error {
		return fmt.Errorf("cannot %s configuration: %s", operation, e)
	}

	y, err := yaml.Marshal(configuration)
	if err != nil {
		return nil, callback(err)
	}

	reader := ioutil.NopCloser(bytes.NewReader(y))
	resp, err := d.callService(method, d.getBaseURL(), reader, callback)

	if err != nil {
		return nil, err
	}

	result := &common.Configuration{}
	if len(resp) != 0 {
		if err := yaml.Unmarshal(resp, &result); err != nil {
			return nil, fmt.Errorf("cannot unmarshal response: (%v)", err)
		}
	}
	return result, nil
}
Beispiel #16
0
func extractFromFile(filename string) (api.BoundPod, error) {
	var pod api.BoundPod

	glog.V(3).Infof("Reading config file %q", filename)
	file, err := os.Open(filename)
	if err != nil {
		return pod, err
	}
	defer file.Close()

	data, err := ioutil.ReadAll(file)
	if err != nil {
		return pod, err
	}

	manifest := &api.ContainerManifest{}
	// TODO: use api.Scheme.DecodeInto
	if err := yaml.Unmarshal(data, manifest); err != nil {
		return pod, fmt.Errorf("can't unmarshal file %q: %v", filename, err)
	}

	if err := api.Scheme.Convert(manifest, &pod); err != nil {
		return pod, fmt.Errorf("can't convert pod from file %q: %v", filename, err)
	}

	hostname, err := os.Hostname() //TODO: kubelet name would be better
	if err != nil {
		return pod, err
	}

	if len(pod.UID) == 0 {
		hasher := md5.New()
		fmt.Fprintf(hasher, "host:%s", hostname)
		fmt.Fprintf(hasher, "file:%s", filename)
		util.DeepHashObject(hasher, pod)
		pod.UID = hex.EncodeToString(hasher.Sum(nil)[0:])
		glog.V(5).Infof("Generated UID %q for pod %q from file %s", pod.UID, pod.Name, filename)
	}
	if len(pod.Namespace) == 0 {
		hasher := adler32.New()
		fmt.Fprint(hasher, filename)
		// TODO: file-<sum>.hostname would be better, if DNS subdomains
		// are allowed for namespace (some places only allow DNS
		// labels).
		pod.Namespace = fmt.Sprintf("file-%08x-%s", hasher.Sum32(), hostname)
		glog.V(5).Infof("Generated namespace %q for pod %q from file %s", pod.Namespace, pod.Name, filename)
	}
	// TODO(dchen1107): BoundPod is not type of runtime.Object. Once we allow kubelet talks
	// about Pod directly, we can use SelfLinker defined in package: latest
	// Currently just simply follow the same format in resthandler.go
	pod.ObjectMeta.SelfLink = fmt.Sprintf("/api/v1beta2/pods/%s?namespace=%s",
		pod.Name, pod.Namespace)

	if glog.V(4) {
		glog.Infof("Got pod from file %q: %#v", filename, pod)
	} else {
		glog.V(1).Infof("Got pod from file %q: %s.%s (%s)", filename, pod.Namespace, pod.Name, pod.UID)
	}
	return pod, nil
}
// Unmarshal creates and returns an ExpansionResult from an ExpansionResponse.
func (eResponse *ExpansionResponse) Unmarshal() (*ExpansionResult, error) {
	var config map[string]interface{}
	if err := yaml.Unmarshal([]byte(eResponse.Config), &config); err != nil {
		return nil, fmt.Errorf("cannot unmarshal config (%s):\n%s", err, eResponse.Config)
	}

	var layout map[string]interface{}
	if err := yaml.Unmarshal([]byte(eResponse.Layout), &layout); err != nil {
		return nil, fmt.Errorf("cannot unmarshal layout (%s):\n%s", err, eResponse.Layout)
	}

	return &ExpansionResult{
		Config: config,
		Layout: layout,
	}, nil
}
Beispiel #18
0
func newEtcdController(kubeBoot *KubeBoot, v *Volume, spec *EtcdClusterSpec) (*EtcdController, error) {
	k := &EtcdController{
		kubeBoot: kubeBoot,
	}

	modelTemplatePath := path.Join(kubeBoot.ModelDir, spec.ClusterKey+".config")
	modelTemplate, err := ioutil.ReadFile(modelTemplatePath)
	if err != nil {
		return nil, fmt.Errorf("error reading model template %q: %v", modelTemplatePath, err)
	}

	cluster := &EtcdCluster{}
	cluster.Spec = spec
	cluster.VolumeMountPath = v.Mountpoint

	model, err := ExecuteTemplate("model-etcd-"+spec.ClusterKey, string(modelTemplate), cluster)
	if err != nil {
		return nil, fmt.Errorf("error executing etcd model template %q: %v", modelTemplatePath, err)
	}

	err = yaml.Unmarshal([]byte(model), cluster)
	if err != nil {
		return nil, fmt.Errorf("error parsing etcd model template %q: %v", modelTemplatePath, err)
	}
	k.cluster = cluster

	return k, nil
}
Beispiel #19
0
func TestDurationUnmarshalYAML(t *testing.T) {
	cases := []struct {
		input  string
		result Duration
	}{
		{"d: 0s\n", Duration{}},
		{"d: 5s\n", Duration{5 * time.Second}},
		{"d: 2m0s\n", Duration{2 * time.Minute}},
		{"d: 1h0m0.003s\n", Duration{time.Hour + 3*time.Millisecond}},

		// Units with zero values can optionally be dropped
		{"d: 2m\n", Duration{2 * time.Minute}},
		{"d: 1h0.003s\n", Duration{time.Hour + 3*time.Millisecond}},
	}

	for _, c := range cases {
		var result DurationHolder
		if err := yaml.Unmarshal([]byte(c.input), &result); err != nil {
			t.Errorf("Failed to unmarshal input %q: %v", c.input, err)
		}
		if result.D != c.result {
			t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result)
		}
	}
}
Beispiel #20
0
// DataToObjects converts the raw JSON data into API objects
func DataToObjects(m meta.RESTMapper, t runtime.ObjectTyper, data []byte) (result []runtime.Object, errors []error) {
	configObj := []runtime.RawExtension{}

	if err := yaml.Unmarshal(data, &configObj); err != nil {
		errors = append(errors, fmt.Errorf("config unmarshal: %v", err))
		return result, errors
	}

	for i, in := range configObj {
		version, kind, err := t.DataVersionAndKind(in.RawJSON)
		if err != nil {
			errors = append(errors, fmt.Errorf("item[%d] kind: %v", i, err))
			continue
		}

		mapping, err := m.RESTMapping(kind, version)
		if err != nil {
			errors = append(errors, fmt.Errorf("item[%d] mapping: %v", i, err))
			continue
		}

		obj, err := mapping.Codec.Decode(in.RawJSON)
		if err != nil {
			errors = append(errors, fmt.Errorf("item[%d] decode: %v", i, err))
			continue
		}
		result = append(result, obj)
	}
	return
}
Beispiel #21
0
func parseYAML(s string) interface{} {
	var x interface{}
	if err := yaml.Unmarshal([]byte(s), &x); err != nil {
		panic(err)
	}
	return x
}
Beispiel #22
0
// ReadValues will parse YAML byte data into a Values.
func ReadValues(data []byte) (vals Values, err error) {
	err = yaml.Unmarshal(data, &vals)
	if len(vals) == 0 {
		vals = Values{}
	}
	return
}
Beispiel #23
0
// Tests that validation works fine when spec contains "type": "any" instead of "type": "object"
// Ref: https://github.com/kubernetes/kubernetes/issues/24309
func TestTypeOAny(t *testing.T) {
	data, err := readSwaggerFile()
	if err != nil {
		t.Errorf("failed to read swagger file: %v", err)
	}
	// Replace type: "any" in the spec by type: "object" and verify that the validation still passes.
	newData := strings.Replace(string(data), `"type": "object"`, `"type": "any"`, -1)
	schema, err := NewSwaggerSchemaFromBytes([]byte(newData), nil)
	if err != nil {
		t.Errorf("Failed to load: %v", err)
	}
	tests := []string{
		"validPod.yaml",
	}
	for _, test := range tests {
		podBytes, err := readPod(test)
		if err != nil {
			t.Errorf("could not read file: %s, err: %v", test, err)
		}
		// Verify that pod has at least one label (labels are type "any")
		var pod api.Pod
		err = yaml.Unmarshal(podBytes, &pod)
		if err != nil {
			t.Errorf("error in unmarshalling pod: %v", err)
		}
		if len(pod.Labels) == 0 {
			t.Errorf("invalid test input: the pod should have at least one label")
		}
		err = schema.ValidateBytes(podBytes)
		if err != nil {
			t.Errorf("unexpected error %s, for pod %s", err, string(podBytes))
		}
	}
}
func TestTimeMarshalJSONUnmarshalYAML(t *testing.T) {
	cases := []struct {
		input Time
	}{
		{Time{}},
		{Date(1998, time.May, 5, 5, 5, 5, 50, time.UTC).Rfc3339Copy()},
		{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Rfc3339Copy()},
	}

	for _, c := range cases {
		input := TimeHolder{c.input}
		jsonMarshalled, err := json.Marshal(&input)
		if err != nil {
			t.Errorf("1: Failed to marshal input: '%v': %v", input, err)
		}

		var result TimeHolder
		err = yaml.Unmarshal(jsonMarshalled, &result)
		if err != nil {
			t.Errorf("2: Failed to unmarshal '%+v': %v", string(jsonMarshalled), err)
		}

		if !reflect.DeepEqual(input, result) {
			t.Errorf("3: Failed to marshal input '%+v': got %+v", input, result)
		}
	}
}
Beispiel #25
0
func TestTimeMarshalJSONUnmarshalYAML(t *testing.T) {
	cases := []struct {
		input Time
	}{
		{Time{}},
		{Date(1998, time.May, 5, 5, 5, 5, 50, time.Local).Rfc3339Copy()},
		{Date(1998, time.May, 5, 5, 5, 5, 0, time.Local).Rfc3339Copy()},
	}

	for i, c := range cases {
		input := TimeHolder{c.input}
		jsonMarshalled, err := json.Marshal(&input)
		if err != nil {
			t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err)
		}

		var result TimeHolder
		err = yaml.Unmarshal(jsonMarshalled, &result)
		if err != nil {
			t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err)
		}

		iN, iO := input.T.Zone()
		oN, oO := result.T.Zone()
		if iN != oN || iO != oO {
			t.Errorf("%d-3: Time zones differ before and after serialization %s:%d %s:%d", i, iN, iO, oN, oO)
		}

		if input.T.UnixNano() != result.T.UnixNano() {
			t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result)
		}
	}
}
Beispiel #26
0
func TestStrategicMergePatch(t *testing.T) {
	tc := StrategicMergePatchTestCases{}
	err := yaml.Unmarshal(createStrategicMergePatchTestCaseData, &tc)
	if err != nil {
		t.Errorf("can't unmarshal test cases: %v", err)
		return
	}

	var e MergeItem
	for _, c := range tc.TestCases {
		cOriginal, cPatch, cModified := testCaseToJSONOrFail(t, c)

		// Test patch generation
		patch, err := CreateStrategicMergePatch(cOriginal, cModified, e)
		if err != nil {
			t.Errorf("error generating patch: %s:\n%v", err, toYAMLOrError(c.StrategicMergePatchTestCaseData))
		}

		// Sort the lists that have merged maps, since order is not significant.
		patch, err = sortMergeListsByName(patch, e)
		if err != nil {
			t.Errorf("error: %s sorting patch object:\n%v", err, patch)
		}

		if !reflect.DeepEqual(patch, cPatch) {
			t.Errorf("patch generation failed:\n%vgot patch:\n%v", toYAMLOrError(c.StrategicMergePatchTestCaseData), jsonToYAMLOrError(patch))
		}

		// Test patch application
		testPatchApplication(t, cOriginal, cPatch, cModified, c.Description)
	}
}
func TestIntOrStringMarshalJSONUnmarshalYAML(t *testing.T) {
	cases := []struct {
		input IntOrString
	}{
		{IntOrString{Kind: IntstrInt, IntVal: 123}},
		{IntOrString{Kind: IntstrString, StrVal: "123"}},
	}

	for _, c := range cases {
		input := IntOrStringHolder{c.input}
		jsonMarshalled, err := json.Marshal(&input)
		if err != nil {
			t.Errorf("1: Failed to marshal input: '%v': %v", input, err)
		}

		var result IntOrStringHolder
		err = yaml.Unmarshal(jsonMarshalled, &result)
		if err != nil {
			t.Errorf("2: Failed to unmarshal '%+v': %v", string(jsonMarshalled), err)
		}

		if !reflect.DeepEqual(input, result) {
			t.Errorf("3: Failed to marshal input '%+v': got %+v", input, result)
		}
	}
}
Beispiel #28
0
func getDescriptionFile(path string) (*scaffolt.GeneratorDescription, error) {
	fullPath := filepath.Join(path, GeneratorDescriptionFile)
	var m scaffolt.GeneratorDescription
	var t string
	if engine.IsFile(fullPath + ".json") {
		t = "json"
	} else if engine.IsFile(fullPath + ".yaml") {
		t = "yaml"
	} else if engine.IsFile(fullPath + "yml") {
		t = "yml"
	} else {
		return nil, fmt.Errorf("Could not find a generator description in path: %s", path)
	}

	bs, err := ioutil.ReadFile(fullPath + "." + t)
	if err != nil {
		return nil, err
	}

	switch t {
	case "json":
		err = json.Unmarshal(bs, &m)
	case "yaml", "yml":
		err = yaml.Unmarshal(bs, &m)
	default:
		err = errors.New("ERROR")
	}

	if err != nil {
		return nil, err
	}
	return &m, err
}
// GetConfiguration reads and returns the actual configuration
// of the resources described by a cached configuration.
func (d *deployer) GetConfiguration(cached *Configuration) (*Configuration, error) {
	errors := &Error{}
	actual := &Configuration{}
	for _, resource := range cached.Resources {
		rtype := url.QueryEscape(resource.Type)
		rname := url.QueryEscape(resource.Name)
		url := fmt.Sprintf("%s/%s/%s", d.getBaseURL(), rtype, rname)
		body, err := d.callService("GET", url, nil, func(e error) error {
			return fmt.Errorf("cannot get configuration for resource (%s)", e)
		})
		if err != nil {
			log.Println(errors.appendError(err))
			continue
		}

		if len(body) != 0 {
			result := &Resource{Name: resource.Name, Type: resource.Type}
			if err := yaml.Unmarshal(body, &result.Properties); err != nil {
				return nil, fmt.Errorf("cannot get configuration for resource (%v)", err)
			}

			actual.Resources = append(actual.Resources, result)
		}
	}

	if len(errors.errors) > 0 {
		return nil, errors
	}

	return actual, nil
}
Beispiel #30
0
func (cfg *config) configFromFile(path string) error {
	eCfg, err := embed.ConfigFromFile(path)
	if err != nil {
		return err
	}
	cfg.Config = *eCfg

	// load extra config information
	b, rerr := ioutil.ReadFile(path)
	if rerr != nil {
		return rerr
	}
	if yerr := yaml.Unmarshal(b, &cfg.configProxy); yerr != nil {
		return yerr
	}
	if cfg.FallbackJSON != "" {
		if err := cfg.fallback.Set(cfg.FallbackJSON); err != nil {
			plog.Panicf("unexpected error setting up discovery-fallback flag: %v", err)
		}
		cfg.Fallback = cfg.fallback.String()
	}
	if cfg.ProxyJSON != "" {
		if err := cfg.proxy.Set(cfg.ProxyJSON); err != nil {
			plog.Panicf("unexpected error setting up proxyFlag: %v", err)
		}
		cfg.Proxy = cfg.proxy.String()
	}
	return nil
}