github.com/jbendotnet/noms@v0.0.0-20190904222105-c43e4293ea92/cmd/noms/noms_json.go (about) 1 // Copyright 2019 Attic Labs, Inc. All rights reserved. 2 // Licensed under the Apache License, version 2.0: 3 // http://www.apache.org/licenses/LICENSE-2.0 4 5 package main 6 7 import ( 8 "fmt" 9 "io" 10 "os" 11 12 "github.com/attic-labs/kingpin" 13 14 "github.com/attic-labs/noms/cmd/util" 15 "github.com/attic-labs/noms/go/config" 16 "github.com/attic-labs/noms/go/d" 17 "github.com/attic-labs/noms/go/util/json" 18 ) 19 20 func nomsJSON(noms *kingpin.Application) (*kingpin.CmdClause, util.KingpinHandler) { 21 // noms json in <db-spec> <file-or-> 22 // noms json out <path-spec> <file-or-> 23 jsonCmd := noms.Command("json", "Import or export JSON.") 24 25 jsonIn := jsonCmd.Command("in", "imports data into Noms from JSON") 26 structsIn := jsonIn.Flag("structs", "JSON objects will be imported to structs, otherwise maps").Bool() 27 toDB := jsonIn.Arg("to", "Database spec to import to").Required().String() 28 fromFile := jsonIn.Arg("from", "File to import from, or '@' to import from stdin").Required().String() 29 30 jsonOut := jsonCmd.Command("out", "exports data from Noms to JSON") 31 structsOut := jsonOut.Flag("structs", "Enable export of Noms structs (to JSON objects)").Default("false").Bool() 32 fromPath := jsonOut.Arg("path", "Absolute path to value to export").Required().String() 33 toFile := jsonOut.Arg("to", "File to export to, or '@' to export to stdout").Required().String() 34 indent := jsonOut.Flag("indent", "Number of spaces to indent when pretty-printing").Default("\t").String() 35 36 return jsonCmd, func(input string) int { 37 switch input { 38 case jsonIn.FullCommand(): 39 return nomsJSONIn(*fromFile, *toDB, json.FromOptions{Structs: *structsIn}) 40 case jsonOut.FullCommand(): 41 return nomsJSONOut(*fromPath, *toFile, json.ToOptions{Lists: true, Maps: true, Sets: true, Structs: *structsOut, Indent: *indent}) 42 } 43 d.Panic("notreached") 44 return 1 45 } 46 } 47 48 func nomsJSONIn(from, to string, opts json.FromOptions) int { 49 cfg := config.NewResolver() 50 db, err := cfg.GetDatabase(to) 51 d.CheckErrorNoUsage(err) 52 53 var r io.ReadCloser 54 if from == "@" { 55 r = os.Stdin 56 } else { 57 r, err = os.Open(from) 58 d.CheckErrorNoUsage(err) 59 } 60 defer r.Close() 61 62 v, err := json.FromJSON(r, db, opts) 63 d.CheckErrorNoUsage(err) 64 65 ref := db.WriteValue(v) 66 db.Flush() 67 fmt.Printf("#%s\n", ref.TargetHash().String()) 68 return 0 69 } 70 71 func nomsJSONOut(from, to string, opts json.ToOptions) int { 72 cfg := config.NewResolver() 73 _, val, err := cfg.GetPath(from) 74 d.CheckErrorNoUsage(err) 75 76 var w io.WriteCloser 77 if to == "@" { 78 w = os.Stdout 79 } else { 80 w, err = os.Create(to) 81 d.CheckErrorNoUsage(err) 82 } 83 defer w.Close() 84 85 err = json.ToJSON(val, w, opts) 86 d.CheckErrorNoUsage(err) 87 return 0 88 }