File: exampletvtojson.go

package info (click to toggle)
golang-github-spdx-tools-golang 0.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,252 kB
  • sloc: xml: 428; makefile: 22; ansic: 5; python: 2
file content (76 lines) | stat: -rw-r--r-- 1,982 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later

// Example for: *tagvalue*, *json*

// This example demonstrates loading an SPDX tag-value file from disk into memory,
// and re-saving it to a different json file on disk.
// Run project: go run exampletvtojson.go ../sample-docs/tv/hello.spdx example.json
package main

import (
	"fmt"
	"os"

	"github.com/spdx/tools-golang/json"
	"github.com/spdx/tools-golang/tagvalue"
)

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> <json-file-out>\n", args[0])
		fmt.Printf("  Load SPDX tag-value file <spdx-file-in>, and\n")
		fmt.Printf("  save it out to JSON <json-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
	doc, err := tagvalue.Read(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()

	var opt []json.WriteOption
	// you can use WriteOption to change JSON format
	// uncomment the following code to test it
	/*
		opt = append(opt, json.Indent(" "))      // to create multiline json
		opt = append(opt, json.EscapeHTML(true)) // to escape HTML characters
	*/

	// try to save the document to disk as JSON file
	err = json.Write(doc, w, opt...)
	if err != nil {
		fmt.Printf("Error while saving %v: %v", fileOut, err)
		return
	}

	// it worked
	fmt.Printf("Successfully saved %s\n", fileOut)
}