aboutsummaryrefslogtreecommitdiff
path: root/jsonsaver/saver2v2/save_document.go
blob: 3fc37c789c046368301ae46a49d618e25c47dd5b (plain)
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
77
// Package saver2v2 contains functions to render and write a json
// formatted version of an in-memory SPDX document and its sections
// (version 2.2).
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
package saver2v2

import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/spdx/tools-golang/spdx"
	"github.com/spdx/tools-golang/spdxlib"
)

// RenderDocument2_2 is the main entry point to take an SPDX in-memory
// Document (version 2.2), and render it to the received *bytes.Buffer.
// It is only exported in order to be available to the jsonsaver package,
// and typically does not need to be called by client code.
func RenderDocument2_2(doc *spdx.Document2_2, buf *bytes.Buffer) error {

	jsondocument := make(map[string]interface{})
	// start to parse the creationInfo
	if doc.CreationInfo == nil {
		return fmt.Errorf("document had nil CreationInfo section")
	}
	renderCreationInfo2_2(doc.CreationInfo, jsondocument)

	// save otherlicenses from sodx struct to json
	if doc.OtherLicenses != nil {
		renderOtherLicenses2_2(doc.OtherLicenses, jsondocument)
	}

	// save document level annotations
	if doc.Annotations != nil {
		ann, _ := renderAnnotations2_2(doc.Annotations, spdx.MakeDocElementID("", string(doc.CreationInfo.SPDXIdentifier)))
		jsondocument["annotations"] = ann
	}

	// save document describes
	describes, _ := spdxlib.GetDescribedPackageIDs2_2(doc)
	if describes != nil {
		var describesID []string
		for _, v := range describes {
			describesID = append(describesID, spdx.RenderElementID(v))
		}
		jsondocument["documentDescribes"] = describesID
	}

	// save packages from spdx to json
	if doc.Packages != nil {
		renderPackage2_2(doc, jsondocument)
	}

	// save files and snippets from spdx to json
	if doc.UnpackagedFiles != nil {
		renderFiles2_2(doc, jsondocument)
		renderSnippets2_2(doc, jsondocument)
	}

	// save reviews from spdx to json
	if doc.Reviews != nil {
		renderReviews2_2(doc.Reviews, jsondocument)
	}

	// save relationships  from spdx to json
	if doc.Relationships != nil {
		renderRelationships2_2(doc.Relationships, jsondocument)
	}

	jsonspec, err := json.MarshalIndent(jsondocument, "", "\t")
	if err != nil {
		return err
	}
	buf.Write(jsonspec)
	return nil
}