1// Copyright 2018 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 15package cmd 16 17import ( 18 "github.com/spf13/cobra" 19 20 "cuelang.org/go/internal/encoding" 21 "cuelang.org/go/internal/filetypes" 22) 23 24// newDefCmd creates a new eval command 25func newDefCmd(c *Command) *cobra.Command { 26 cmd := &cobra.Command{ 27 Use: "def", 28 Short: "print consolidated definitions", 29 Long: `def prints consolidated configuration as a single file. 30 31Printing is skipped if validation fails. 32 33The --expression flag is used to only print parts of a configuration. 34`, 35 RunE: mkRunE(c, runDef), 36 } 37 38 addOutFlags(cmd.Flags(), true) 39 addOrphanFlags(cmd.Flags()) 40 addInjectionFlags(cmd.Flags(), false) 41 42 cmd.Flags().StringArrayP(string(flagExpression), "e", nil, "evaluate this expression only") 43 44 cmd.Flags().BoolP(string(flagAttributes), "A", false, 45 "display field attributes") 46 47 // TODO: Option to include comments in output. 48 return cmd 49} 50 51func runDef(cmd *Command, args []string) error { 52 b, err := parseArgs(cmd, args, &config{outMode: filetypes.Def}) 53 exitOnErr(cmd, err, true) 54 55 e, err := encoding.NewEncoder(b.outFile, b.encConfig) 56 exitOnErr(cmd, err, true) 57 58 iter := b.instances() 59 defer iter.close() 60 for i := 0; iter.scan(); i++ { 61 var err error 62 if f := iter.file(); f != nil { 63 err = e.EncodeFile(f) 64 } else if i := iter.instance(); i != nil { 65 err = e.EncodeInstance(iter.instance()) 66 } else { 67 err = e.Encode(iter.value()) 68 } 69 exitOnErr(cmd, err, true) 70 } 71 exitOnErr(cmd, iter.err(), true) 72 73 err = e.Close() 74 exitOnErr(cmd, err, true) 75 76 return nil 77} 78