diff options
Diffstat (limited to 'examples/8-jsonpasrser2v2/examplejsontotv.go')
-rw-r--r-- | examples/8-jsonpasrser2v2/examplejsontotv.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/examples/8-jsonpasrser2v2/examplejsontotv.go b/examples/8-jsonpasrser2v2/examplejsontotv.go new file mode 100644 index 0000000..271826c --- /dev/null +++ b/examples/8-jsonpasrser2v2/examplejsontotv.go @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later + +// Example for: *tvloader*, *tvsaver* + +// This example demonstrates loading an SPDX tag-value file from disk into memory, +// and re-saving it to a different file on disk. + +package main + +import ( + "fmt" + "io/ioutil" + "log" + "os" + + "github.com/spdx/tools-golang/jsonloader2v2" + "github.com/spdx/tools-golang/tvsaver" +) + +func main() { + + // check that we've received the right number of arguments + args := os.Args + if len(args) != 3 { + fmt.Printf("Usage: %v <spdx-file-in> <spdx-file-out>\n", args[0]) + fmt.Printf(" Load SPDX 2.2 tag-value file <spdx-file-in>, and\n") + fmt.Printf(" save it out to <spdx-file-out>.\n") + return + } + + // open the SPDX file + jsonData, err := ioutil.ReadFile(args[1]) // b has type []byte + if err != nil { + log.Fatal(err) + } + + // try to load the SPDX file's contents as a tag-value file, version 2.2 + doc, err := jsonloader2v2.Load2_2(jsonData) + if err != nil { + fmt.Printf("Error while parsing %v: %v", args[1], err) + return + } + + // if we got here, the file is now loaded into memory. + fmt.Printf("Successfully loaded %s\n", args[1]) + + // we can now save it back to disk, using tvsaver. + + // create a new file for writing + fileOut := args[2] + w, err := os.Create(fileOut) + if err != nil { + fmt.Printf("Error while opening %v for writing: %v", fileOut, err) + return + } + defer w.Close() + + // try to save the document to disk as an SPDX tag-value file, version 2.2 + err = tvsaver.Save2_2(doc, w) + if err != nil { + fmt.Printf("Error while saving %v: %v", fileOut, err) + return + } + + // it worked + fmt.Printf("Successfully saved %s\n", fileOut) +} |