func parse(in []byte) (*ast.File, error) { switch lexMode(in) { case lexModeHcl: return hclParser.Parse(in) case lexModeJson: return jsonParser.Parse(in) } return nil, fmt.Errorf("unknown config format") }
// format parses src, prints the corresponding AST, verifies the resulting // src is syntactically correct, and returns the resulting src or an error // if any. func format(src []byte) ([]byte, error) { formatted, err := Format(src) if err != nil { return nil, err } // make sure formatted output is syntactically correct if _, err := parser.Parse(formatted); err != nil { return nil, fmt.Errorf("parse: %s\n%s", err, src) } return formatted, nil }
// Format formats src HCL and returns the result. func Format(src []byte) ([]byte, error) { node, err := parser.Parse(src) if err != nil { return nil, err } var buf bytes.Buffer if err := DefaultConfig.Fprint(&buf, node); err != nil { return nil, err } // Add trailing newline to result buf.WriteString("\n") return buf.Bytes(), nil }