|
| 1 | +// Copyright 2023 The CUE Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// cue-ast-print parses a CUE file and prints its syntax tree, for example: |
| 16 | +// |
| 17 | +// cue-ast-print file.cue |
| 18 | +package main |
| 19 | + |
| 20 | +import ( |
| 21 | + "flag" |
| 22 | + "fmt" |
| 23 | + "log" |
| 24 | + "os" |
| 25 | + |
| 26 | + "cuelang.org/go/cue/errors" |
| 27 | + "cuelang.org/go/cue/load" |
| 28 | + "cuelang.org/go/internal/astinternal" |
| 29 | +) |
| 30 | + |
| 31 | +func main() { |
| 32 | + flag.Usage = func() { |
| 33 | + fmt.Fprint(flag.CommandLine.Output(), ` |
| 34 | +usage of cue-ast: |
| 35 | +
|
| 36 | + cue-ast print [flags] [inputs] |
| 37 | +
|
| 38 | + Write multi-line Go-like representations of CUE syntax trees. |
| 39 | +
|
| 40 | + -omitempty omit empty and invalid values |
| 41 | +
|
| 42 | +See 'cue help inputs' as well. |
| 43 | +`[1:]) |
| 44 | + } |
| 45 | + |
| 46 | + if len(os.Args) < 2 { |
| 47 | + flag.Usage() |
| 48 | + os.Exit(1) |
| 49 | + } |
| 50 | + name, args := os.Args[1], os.Args[2:] |
| 51 | + switch name { |
| 52 | + case "print": |
| 53 | + var cfg astinternal.DebugConfig |
| 54 | + flag.BoolVar(&cfg.OmitEmpty, "omitempty", false, "") |
| 55 | + // Note that DebugConfig also has a Filter func, but that doesn't lend itself well |
| 56 | + // to a command line flag. Perhaps we could provide some commonly used filters, |
| 57 | + // such as "positions only" or "skip positions". |
| 58 | + flag.CommandLine.Parse(args) |
| 59 | + |
| 60 | + // TODO: should we produce output in txtar form for the sake of |
| 61 | + // more clearly separating the AST for each file? |
| 62 | + // [ast.File.Filename] already has the full filename, |
| 63 | + // but as one of the first fields it's not a great separator. |
| 64 | + insts := load.Instances(flag.Args(), &load.Config{}) |
| 65 | + for _, inst := range insts { |
| 66 | + if err := inst.Err; err != nil { |
| 67 | + log.Fatal(errors.Details(err, nil)) |
| 68 | + } |
| 69 | + for _, file := range inst.Files { |
| 70 | + out := astinternal.AppendDebug(nil, file, cfg) |
| 71 | + os.Stdout.Write(out) |
| 72 | + } |
| 73 | + } |
| 74 | + default: |
| 75 | + flag.Usage() |
| 76 | + } |
| 77 | +} |
0 commit comments