예제 #1
0
파일: main.go 프로젝트: fatih/hclfmt
// If in == nil, the source is the contents of the file with the given filename.
func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error {
	if in == nil {
		f, err := os.Open(filename)
		if err != nil {
			return err
		}
		defer f.Close()
		in = f
	}

	src, err := ioutil.ReadAll(in)
	if err != nil {
		return err
	}

	res, err := printer.Format(src)
	if err != nil {
		return err
	}

	if *write {
		err = ioutil.WriteFile(filename, res, 0644)
	} else {
		_, err = out.Write(res)
	}

	return err
}
예제 #2
0
// This will only work operate on []interface{}, map[string]interface{}, and
// primitive types.
func encodeHCL(i interface{}) ([]byte, error) {
	state := &encodeState{}
	err := state.encode(i)
	if err != nil {
		return nil, err
	}

	hcl := state.Bytes()
	if len(hcl) == 0 {
		return hcl, nil
	}

	// the HCL parser requires an assignment. Strip it off again later
	fakeAssignment := append([]byte("X = "), hcl...)

	// use the real hcl parser to verify our output, and format it canonically
	hcl, err = printer.Format(fakeAssignment)
	if err != nil {
		return nil, err
	}

	// now strip that first assignment off
	eq := regexp.MustCompile(`=\s+`).FindIndex(hcl)

	return hcl[eq[1]:], nil
}
예제 #3
0
// If in == nil, the source is the contents of the file with the given filename.
func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error {
	if in == nil {
		f, err := os.Open(filename)
		if err != nil {
			return err
		}
		defer f.Close()
		in = f
	}

	src, err := ioutil.ReadAll(in)
	if err != nil {
		return err
	}

	res, err := printer.Format(src)
	if err != nil {
		return err
	}
	// Files should end with newlines
	res = append(res, []byte("\n")...)

	if !bytes.Equal(src, res) {
		// formatting has changed
		if opts.List {
			fmt.Fprintln(out, filename)
		}
		if opts.Write {
			err = ioutil.WriteFile(filename, res, 0644)
			if err != nil {
				return err
			}
		}
		if opts.Diff {
			data, err := diff(src, res)
			if err != nil {
				return fmt.Errorf("computing diff: %s", err)
			}
			fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename)
			out.Write(data)
		}
	}

	if !opts.List && !opts.Write && !opts.Diff {
		_, err = out.Write(res)
	}

	return err
}