Apply more golint recommendations (#201)

* Apply more golint recommendations

* Update dumpstdlibast.go to include StdAst comment

* Improve dump.go package comment.
This commit is contained in:
Marcelo Cantos 2018-02-28 17:11:18 +11:00 committed by Dave Cunningham
parent ed5f280c59
commit 88519c3704
10 changed files with 73 additions and 39 deletions

View File

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Package ast provides AST nodes and ancillary structures and algorithms.
package ast package ast
import ( import (

View File

@ -1,3 +1,10 @@
///////////////////////////////////////////////////////////
// This file was auto-generated by cmd/dumpstdlibast.go. //
// https://github.com/google/go-jsonnet#generated-stdlib //
// //
// --------------- DO NOT EDIT BY HAND! --------------- //
///////////////////////////////////////////////////////////
package ast package ast
var p3Var = "$" var p3Var = "$"
@ -2768,6 +2775,8 @@ var p1 = &Source{
"\n", "\n",
}, },
} }
// StdAst is the AST for the standard library.
var StdAst = &DesugaredObject{ var StdAst = &DesugaredObject{
NodeBase: NodeBase{ NodeBase: NodeBase{
loc: LocationRange{ loc: LocationRange{

View File

@ -18,16 +18,17 @@ package ast
import "sort" import "sort"
func (i *IdentifierSet) Append(idents Identifiers) { // AddIdentifiers adds a slice of identifiers to an identifier set.
func (i IdentifierSet) AddIdentifiers(idents Identifiers) {
for _, ident := range idents { for _, ident := range idents {
i.Add(ident) i.Add(ident)
} }
} }
// ToOrderedSlice returns the elements of the current set as a ordered slice // ToOrderedSlice returns the elements of the current set as an ordered slice.
func (set IdentifierSet) ToOrderedSlice() []Identifier { func (i IdentifierSet) ToOrderedSlice() []Identifier {
var s []Identifier var s []Identifier
for v := range set { for v := range i {
s = append(s, v) s = append(s, v)
} }
sort.Sort(identifierSorter(s)) sort.Sort(identifierSorter(s))

View File

@ -43,9 +43,22 @@ func main() {
dump.Config.HidePrivateFields = false dump.Config.HidePrivateFields = false
dump.Config.StripPackageNames = true dump.Config.StripPackageNames = true
dump.Config.VariableName = "StdAst" dump.Config.VariableName = "StdAst"
dump.Config.VariableDescription = "StdAst is the AST for the standard library."
ast := dump.Sdump(node) ast := dump.Sdump(node)
file.WriteString("package ast\n\n") file.WriteString(header)
file.WriteString(ast) file.WriteString(ast)
file.Sync() file.Close()
} }
var header = `
///////////////////////////////////////////////////////////
// This file was auto-generated by cmd/dumpstdlibast.go. //
// https://github.com/google/go-jsonnet#generated-stdlib //
// //
// --------------- DO NOT EDIT BY HAND! --------------- //
///////////////////////////////////////////////////////////
package ast
`[1:]

View File

@ -14,6 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Package dump can dump a Go data structure to Go source file, so that it can
// be statically embedded into other code.
package dump package dump
import ( import (
@ -35,6 +37,7 @@ type Options struct {
HidePrivateFields bool HidePrivateFields bool
HomePackage string HomePackage string
VariableName string VariableName string
VariableDescription string
} }
// Config is the default config used when calling Dump // Config is the default config used when calling Dump
@ -42,6 +45,7 @@ var Config = Options{
StripPackageNames: false, StripPackageNames: false,
HidePrivateFields: true, HidePrivateFields: true,
VariableName: "Obj", VariableName: "Obj",
VariableDescription: "",
} }
type dumpState struct { type dumpState struct {
@ -157,8 +161,15 @@ func (s *dumpState) dumpMap(v reflect.Value) {
} }
func (s *dumpState) dump(value interface{}) { func (s *dumpState) dump(value interface{}) {
if value == nil { writeVar := func() {
if s.config.VariableDescription != "" {
fmt.Fprintf(s.w, "\n// %s\n", s.config.VariableDescription)
}
s.w.Write([]byte("var " + s.config.VariableName + " = ")) s.w.Write([]byte("var " + s.config.VariableName + " = "))
}
if value == nil {
writeVar()
printNil(s.w) printNil(s.w)
s.newline() s.newline()
return return
@ -170,7 +181,7 @@ func (s *dumpState) dump(value interface{}) {
s.dumpReusedPointerVal(v) s.dumpReusedPointerVal(v)
s.w.Write([]byte("var " + s.config.VariableName + " = ")) writeVar()
if v.Kind() == reflect.Ptr && v.IsNil() { if v.Kind() == reflect.Ptr && v.IsNil() {
printNil(s.w) printNil(s.w)
} else { } else {

View File

@ -24,8 +24,8 @@ type pointerMap struct {
primitivePointers []uintptr primitivePointers []uintptr
} }
// GetPointers: Given a structure, it will recursively map all pointers mentioned in the tree, // GetPointers recursively maps all pointers mentioned in a tree, breaking
// breaking circular references and provide list of: // circular references, and provides a list of:
// * all pointers // * all pointers
// * all pointers that were referenced at least twice // * all pointers that were referenced at least twice
// * all pointers that point to primitive type // * all pointers that point to primitive type

View File

@ -120,13 +120,13 @@ func usage(o io.Writer) {
func safeStrToInt(str string) (i int) { func safeStrToInt(str string) (i int) {
i, err := strconv.Atoi(str) i, err := strconv.Atoi(str)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: Invalid integer \"%s\"\n", str) fmt.Fprintf(os.Stderr, "Invalid integer \"%s\"\n", str)
os.Exit(1) os.Exit(1)
} }
return return
} }
type Command int type command int
const ( const (
commandEval = iota commandEval = iota
@ -134,7 +134,7 @@ const (
) )
type config struct { type config struct {
cmd Command cmd command
inputFiles []string inputFiles []string
outputFile string outputFile string
filenameIsCode bool filenameIsCode bool
@ -167,20 +167,18 @@ func getVarVal(s string) (string, string, error) {
if exists { if exists {
return name, content, nil return name, content, nil
} }
return "", "", fmt.Errorf("ERROR: Environment variable %v was undefined.", name) return "", "", fmt.Errorf("environment variable %v was undefined", name)
} else {
return name, parts[1], nil
} }
return name, parts[1], nil
} }
func getVarFile(s string, imp string) (string, string, error) { func getVarFile(s string, imp string) (string, string, error) {
parts := strings.SplitN(s, "=", 2) parts := strings.SplitN(s, "=", 2)
name := parts[0] name := parts[0]
if len(parts) == 1 { if len(parts) == 1 {
return "", "", fmt.Errorf("ERROR: argument not in form <var>=<file> \"%s\".", s) return "", "", fmt.Errorf(`argument not in form <var>=<file> "%s"`, s)
} else {
return name, fmt.Sprintf("%s @'%s'", imp, strings.Replace(parts[1], "'", "''", -1)), nil
} }
return name, fmt.Sprintf("%s @'%s'", imp, strings.Replace(parts[1], "'", "''", -1)), nil
} }
type processArgsStatus int type processArgsStatus int
@ -217,7 +215,7 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
} else if arg == "-o" || arg == "--output-file" { } else if arg == "-o" || arg == "--output-file" {
outputFile := nextArg(&i, args) outputFile := nextArg(&i, args)
if len(outputFile) == 0 { if len(outputFile) == 0 {
return processArgsStatusFailure, fmt.Errorf("ERROR: -o argument was empty string") return processArgsStatusFailure, fmt.Errorf("-o argument was empty string")
} }
config.outputFile = outputFile config.outputFile = outputFile
} else if arg == "--" { } else if arg == "--" {
@ -231,13 +229,13 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
if arg == "-s" || arg == "--max-stack" { if arg == "-s" || arg == "--max-stack" {
l := safeStrToInt(nextArg(&i, args)) l := safeStrToInt(nextArg(&i, args))
if l < 1 { if l < 1 {
return processArgsStatusFailure, fmt.Errorf("ERROR: Invalid --max-stack value: %d", l) return processArgsStatusFailure, fmt.Errorf("invalid --max-stack value: %d", l)
} }
vm.MaxStack = l vm.MaxStack = l
} else if arg == "-J" || arg == "--jpath" { } else if arg == "-J" || arg == "--jpath" {
dir := nextArg(&i, args) dir := nextArg(&i, args)
if len(dir) == 0 { if len(dir) == 0 {
return processArgsStatusFailure, fmt.Errorf("ERROR: -J argument was empty string") return processArgsStatusFailure, fmt.Errorf("-J argument was empty string")
} }
if dir[len(dir)-1] != '/' { if dir[len(dir)-1] != '/' {
dir += "/" dir += "/"
@ -302,14 +300,14 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
} else if arg == "-t" || arg == "--max-trace" { } else if arg == "-t" || arg == "--max-trace" {
l := safeStrToInt(nextArg(&i, args)) l := safeStrToInt(nextArg(&i, args))
if l < 0 { if l < 0 {
return processArgsStatusFailure, fmt.Errorf("ERROR: Invalid --max-trace value: %d", l) return processArgsStatusFailure, fmt.Errorf("invalid --max-trace value: %d", l)
} }
vm.ErrorFormatter.SetMaxStackTraceSize(l) vm.ErrorFormatter.SetMaxStackTraceSize(l)
} else if arg == "-m" || arg == "--multi" { } else if arg == "-m" || arg == "--multi" {
config.evalMulti = true config.evalMulti = true
outputDir := nextArg(&i, args) outputDir := nextArg(&i, args)
if len(outputDir) == 0 { if len(outputDir) == 0 {
return processArgsStatusFailure, fmt.Errorf("ERROR: -m argument was empty string") return processArgsStatusFailure, fmt.Errorf("-m argument was empty string")
} }
if outputDir[len(outputDir)-1] != '/' { if outputDir[len(outputDir)-1] != '/' {
outputDir += "/" outputDir += "/"
@ -320,13 +318,12 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
} else if arg == "-S" || arg == "--string" { } else if arg == "-S" || arg == "--string" {
vm.StringOutput = true vm.StringOutput = true
} else if len(arg) > 1 && arg[0] == '-' { } else if len(arg) > 1 && arg[0] == '-' {
return processArgsStatusFailure, fmt.Errorf("ERROR: Unrecognized argument: %s", arg) return processArgsStatusFailure, fmt.Errorf("unrecognized argument: %s", arg)
} else { } else {
remainingArgs = append(remainingArgs, arg) remainingArgs = append(remainingArgs, arg)
} }
} else { } else {
return processArgsStatusFailure, fmt.Errorf("The Go implementation currently does not support jsonnet fmt.") return processArgsStatusFailure, fmt.Errorf("the Go implementation currently does not support jsonnet fmt")
} }
} }
@ -335,7 +332,7 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
want = "code" want = "code"
} }
if len(remainingArgs) == 0 { if len(remainingArgs) == 0 {
return processArgsStatusFailureUsage, fmt.Errorf("ERROR: Must give %s", want) return processArgsStatusFailureUsage, fmt.Errorf("must give %s", want)
} }
// TODO(dcunnin): Formatter allows multiple files in test and in-place mode. // TODO(dcunnin): Formatter allows multiple files in test and in-place mode.
@ -343,7 +340,7 @@ func processArgs(givenArgs []string, config *config, vm *jsonnet.VM) (processArg
if !multipleFilesAllowed { if !multipleFilesAllowed {
if len(remainingArgs) > 1 { if len(remainingArgs) > 1 {
return processArgsStatusFailure, fmt.Errorf("ERROR: Only one %s is allowed", want) return processArgsStatusFailure, fmt.Errorf("only one %s is allowed", want)
} }
} }
@ -390,7 +387,7 @@ func writeMultiOutputFiles(output map[string]string, outputDir, outputFile strin
// Iterate through the map in order. // Iterate through the map in order.
keys := make([]string, 0, len(output)) keys := make([]string, 0, len(output))
for k, _ := range output { for k := range output {
keys = append(keys, k) keys = append(keys, k)
} }
sort.Strings(keys) sort.Strings(keys)
@ -511,7 +508,7 @@ func main() {
status, err := processArgs(os.Args[1:], &config, vm) status, err := processArgs(os.Args[1:], &config, vm)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err.Error()) fmt.Fprintln(os.Stderr, "ERROR: "+err.Error())
} }
switch status { switch status {
case processArgsStatusContinue: case processArgsStatusContinue:

View File

@ -1,3 +1,4 @@
// Package linter analyses Jsonnet code for code "smells".
package linter package linter
import ( import (

View File

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Package parser reads Jsonnet files and parses them into AST nodes.
package parser package parser
import ( import (

View File

@ -33,7 +33,7 @@ func visitNext(a ast.Node, inObject bool, vars ast.IdentifierSet, state *analysi
return return
} }
state.err = analyzeVisit(a, inObject, vars) state.err = analyzeVisit(a, inObject, vars)
state.freeVars.Append(a.FreeVariables()) state.freeVars.AddIdentifiers(a.FreeVariables())
} }
func analyzeVisit(a ast.Node, inObject bool, vars ast.IdentifierSet) error { func analyzeVisit(a ast.Node, inObject bool, vars ast.IdentifierSet) error {