xref: /aosp_15_r20/external/spdx-tools/examples/8-jsontotv/examplejsontotv.go (revision ba677afa8f67bb56cbc794f4d0e378e0da058e16)
1// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
2
3// Example for: *json*, *tvsaver*
4
5// This example demonstrates loading an SPDX json from disk into memory,
6// and then re-saving it to a different file on disk in tag-value format .
7// Run project: go run examplejsontotv.go ../sample-docs/json/SPDXJSONExample-v2.2.spdx.json example.spdx
8package main
9
10import (
11	"fmt"
12	"os"
13
14	spdx_json "github.com/spdx/tools-golang/json"
15	"github.com/spdx/tools-golang/tvsaver"
16)
17
18func main() {
19
20	// check that we've received the right number of arguments
21	args := os.Args
22	if len(args) != 3 {
23		fmt.Printf("Usage: %v <json-file-in> <spdx-file-out>\n", args[0])
24		fmt.Printf("  Load JSON file <json-file-in>, and\n")
25		fmt.Printf("  save it out to <spdx-file-out>.\n")
26		return
27	}
28
29	// open the SPDX file
30	fileIn := args[1]
31	r, err := os.Open(fileIn)
32	if err != nil {
33		fmt.Printf("Error while opening %v for reading: %v", fileIn, err)
34		return
35	}
36	defer r.Close()
37
38	// try to load the SPDX file's contents as a json file, version 2.2
39	doc, err := spdx_json.Load2_2(r)
40	if err != nil {
41		fmt.Printf("Error while parsing %v: %v", args[1], err)
42		return
43	}
44
45	// if we got here, the file is now loaded into memory.
46	fmt.Printf("Successfully loaded %s\n", args[1])
47
48	// we can now save it back to disk, using tvsaver.
49
50	// create a new file for writing
51	fileOut := args[2]
52	w, err := os.Create(fileOut)
53	if err != nil {
54		fmt.Printf("Error while opening %v for writing: %v", fileOut, err)
55		return
56	}
57	defer w.Close()
58
59	// try to save the document to disk as an SPDX tag-value file, version 2.2
60	err = tvsaver.Save2_2(doc, w)
61	if err != nil {
62		fmt.Printf("Error while saving %v: %v", fileOut, err)
63		return
64	}
65
66	// it worked
67	fmt.Printf("Successfully saved %s\n", fileOut)
68}
69