diff options
author | Ujjwal Agarwal <ujjwalcoding012@gmail.com> | 2021-08-06 18:15:01 +0530 |
---|---|---|
committer | Ujjwal Agarwal <ujjwalcoding012@gmail.com> | 2021-08-06 18:15:01 +0530 |
commit | 1bc87f7cbc680e409a1ec51fdfdd93b5d2b49701 (patch) | |
tree | 250966ff349b1e1dab25505774ccddc87a0d6d45 /examples/9-tvtojson | |
parent | 1a9690feffaf2257985570998037cefd196e21aa (diff) | |
download | spdx-tools-1bc87f7cbc680e409a1ec51fdfdd93b5d2b49701.tar.gz |
Examples : add example of jsonloader and remove existing conversion examples
- bug fixes in json saver done as well
- test covereage of jsonparser increased
Signed-off-by: Ujjwal Agarwal <ujjwalcoding012@gmail.com>
Diffstat (limited to 'examples/9-tvtojson')
-rw-r--r-- | examples/9-tvtojson/exampletvtojson.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/examples/9-tvtojson/exampletvtojson.go b/examples/9-tvtojson/exampletvtojson.go new file mode 100644 index 0000000..2c6ec7e --- /dev/null +++ b/examples/9-tvtojson/exampletvtojson.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later + +// Example for: *tvloader*, *jsonsaver* + +// This example demonstrates loading an SPDX tag-value file from disk into memory, +// and re-saving it to a different json file on disk. + +package main + +import ( + "fmt" + "os" + + "github.com/spdx/tools-golang/jsonsaver" + "github.com/spdx/tools-golang/tvloader" +) + +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 + fileIn := args[1] + r, err := os.Open(fileIn) + if err != nil { + fmt.Printf("Error while opening %v for reading: %v", fileIn, err) + return + } + defer r.Close() + + // try to load the SPDX file's contents as a tag-value file, version 2.2 + doc, err := tvloader.Load2_2(r) + 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 jsonsaver. + + // 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 json file, version 2.2 + err = jsonsaver.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) +} |