Expose "unparse", FormatNode and RawAST (#710)

* Export FormatNode so external users can pretty print an AST

Signed-off-by: Tom Wilkie <tom@grafana.com>

* Expose RawAST function.

Signed-off-by: Tom Wilkie <tom@grafana.com>

* Add comment

Signed-off-by: Tom Wilkie <tom@grafana.com>

---------

Signed-off-by: Tom Wilkie <tom@grafana.com>
Co-authored-by: Tom Wilkie <tom@grafana.com>
This commit is contained in:
Charles Korn 2023-06-15 04:56:49 +10:00 committed by GitHub
parent 9639773cf0
commit 7b9f5fd4b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 1 deletions

View File

@ -4,7 +4,11 @@
// customized using formatter.Options. // customized using formatter.Options.
package formatter package formatter
import "github.com/google/go-jsonnet/internal/formatter" import (
"github.com/google/go-jsonnet/ast"
"github.com/google/go-jsonnet/internal/formatter"
"github.com/google/go-jsonnet/internal/parser"
)
// StringStyle controls how the reformatter rewrites string literals. // StringStyle controls how the reformatter rewrites string literals.
// Strings that contain a ' or a " use the optimal syntax to avoid escaping // Strings that contain a ' or a " use the optimal syntax to avoid escaping
@ -46,3 +50,14 @@ func DefaultOptions() Options {
func Format(filename string, input string, options Options) (string, error) { func Format(filename string, input string, options Options) (string, error) {
return formatter.Format(filename, input, options) return formatter.Format(filename, input, options)
} }
// FormatNode returns code that is equivalent to its input but better formatted
// according to the given options.
func FormatNode(node ast.Node, finalFodder ast.Fodder, options Options) (string, error) {
return formatter.FormatNode(node, finalFodder, options)
}
// SnippetToRawAST parses a snippet and returns the resulting AST.
func SnippetToRawAST(filename string, snippet string) (ast.Node, ast.Fodder, error) {
return parser.SnippetToRawAST(ast.DiagnosticFileName(filename), "", snippet)
}

View File

@ -152,6 +152,12 @@ func Format(filename string, input string, options Options) (string, error) {
return "", err return "", err
} }
return FormatNode(node, finalFodder, options)
}
// FormatNode returns code that is equivalent to its input but better formatted
// according to the given options.
func FormatNode(node ast.Node, finalFodder ast.Fodder, options Options) (string, error) {
// Passes to enforce style on the AST. // Passes to enforce style on the AST.
if options.SortImports { if options.SortImports {
SortImports(&node) SortImports(&node)