diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9aef43af..1b4fbad4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,7 +22,7 @@ New **code files** should include a [short-form SPDX ID](https://spdx.org/ids) a
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
```
-New **documentation files** should include a [short-form SPDX ID](https://spdx.org/ids) at the top, indicating the project license for code, which is CC-BY-4.0. This should look like the following:
+New **documentation files** should include a [short-form SPDX ID](https://spdx.org/ids) at the top, indicating the project license for documentation, which is CC-BY-4.0. This should look like the following:
```
SPDX-License-Identifier: CC-BY-4.0
diff --git a/README.md b/README.md
index 3d5a5a7a..38f8d185 100644
--- a/README.md
+++ b/README.md
@@ -1,42 +1,39 @@
[](https://github.com/spdx/tools-golang/actions)
[](https://coveralls.io/github/spdx/tools-golang)
-# tools-golang
+# SPDX tools-golang
tools-golang is a collection of Go packages intended to make it easier for
Go programs to work with [SPDX®](https://spdx.org/) files.
-This software is in an early state, and its API may change significantly.
-
## Recent news
-2021-03-20: **v0.1.0**: initial pre-v1 release tagged, prior to making more
-extensive API changes in some pending PRs.
+2021-07-04: **v0.2.0**: added support for parsing SPDX JSON files as well as
+other improvements and bugfixes. See [RELEASE-NOTES.md](./RELEASE-NOTES.md)
+for full details.
## What it does
tools-golang currently works with files conformant to versions 2.1 and 2.2
-of the SPDX specification, available at: https://spdx.org/specifications
+of the SPDX specification, available at: https://spdx.dev/specifications
tools-golang provides the following packages:
* *spdx* - in-memory data model for the sections of an SPDX document
-* *tvloader* - tag-value file loader
-* *tvsaver* - tag-value file saver
-* *rdfloader* - RDF file loader
+* *tvloader* - tag-value document loader
+* *tvsaver* - tag-value document saver
+* *rdfloader* - RDF document loader
+* *jsonloader* - JSON document loader
* *builder* - builds "empty" SPDX document (with hashes) for directory contents
* *idsearcher* - searches for [SPDX short-form IDs](https://spdx.org/ids/) and builds SPDX document
* *licensediff* - compares concluded licenses between files in two packages
* *reporter* - generates basic license count report from SPDX document
+* *spdxlib* - various utility functions for manipulating SPDX documents in memory
* *utils* - various utility functions that support the other tools-golang packages
Examples for how to use these packages can be found in the `examples/`
directory.
-RDF support was added by @RishabhBhatnagar as part of his Google Summer of
-Code 2020 project, and is in the process of being merged into the main
-tools-golang code.
-
## What it doesn't do
tools-golang doesn't currently do any of the following:
@@ -56,6 +53,19 @@ tools-golang uses https://github.com/spdx/gordf to manage RDF input and output.
Other than that, tools-golang does not require anything outside the Go standard
library.
+## Contributors
+
+Thank you to all of the contributors to spdx/tools-golang. A full list can be
+found in the GitHub repo and in [the release notes](RELEASE-NOTES.md).
+
+In particular, thank you to the following for major contributions:
+
+JSON parsing support was added by @specter25 as part of his Google Summer of
+Code 2021 project.
+
+RDF parsing support was added by @RishabhBhatnagar as part of his Google Summer
+of Code 2020 project.
+
## Licenses
As indicated in `LICENSE-code`, tools-golang **source code files** are
diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md
new file mode 100644
index 00000000..be167562
--- /dev/null
+++ b/RELEASE-NOTES.md
@@ -0,0 +1,43 @@
+SPDX-License-Identifier: CC-BY-4.0
+
+# Release Notes for spdx/tools-golang
+
+## 0.2.0
+
+Released on: 2021-07-04
+
+### New Features and Enhancements
+* Add support for parsing SPDX JSON: #72, #75, #83, #84, #87
+ * bug fixes in interim versions: #77, #78, #79, #80, #81, #82
+* Improve handling of multiple hash checksum types: #41, #49, #60
+* Enable filtering relationships by various relationship types: #71, #74
+* Improve package license visibility: #65, #66
+* Rename primary branch to 'main': #69
+* Add release notes and push release: #85, #90
+
+### Bug fixes
+* Fix multiline (``) wrapping for various fields: #31, #53, #58, #89, #76
+* Fix special SPDX IDs in right-hand side of Relationships: #59, #63, #68
+* Throw error when parsing tag-value elements without SPDX IDs: #26, #64
+* Fix missing colon in 'excludes' for Package Verification Code when saving tag-value documents: #86, #88
+* Fix incorrect license statement: #70
+
+### Contributors
+* @autarch
+* @bisakhmondal
+* @ianling
+* @matthewkmayer
+* @RishabhBhatnagar
+* @specter25
+* @swinslow
+
+## 0.1.0
+
+Released on: 2021-03-20
+
+### Contributors
+* @abhishekspeer
+* @goneall
+* @RishabhBhatnagar
+* @rtgdk
+* @swinslow
diff --git a/examples/8-jsonloader/result.txt b/examples/8-jsonloader/result.txt
new file mode 100644
index 00000000..7909ccf2
--- /dev/null
+++ b/examples/8-jsonloader/result.txt
@@ -0,0 +1,346 @@
+SPDXVersion: SPDX-2.2
+DataLicense: CC0-1.0
+SPDXID: SPDXRef-DOCUMENT
+DocumentName: SPDX-Tools-v2.0
+DocumentNamespace: http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301
+ExternalDocumentRef: DocumentRef-spdx-tool-1.2 http://spdx.org/spdxdocs/spdx-tools-v1.2-3F2504E0-4F89-41D3-9A0C-0305E82C3301 SHA1:d6a770ba38583ed4bb4525bd96e50461655d2759
+LicenseListVersion: 3.9
+Creator: Person: Jane Doe
+Creator: Organization: ExampleCodeInspect
+Creator: Tool: LicenseFind-1.0
+Created: 2010-01-29T18:30:22Z
+CreatorComment: This package has been shipped in source and binary form.
+The binaries were created with gcc 4.5.1 and expect to link to
+compatible system run time libraries.
+DocumentComment: This document was created using SPDX 2.0 using licenses from the web site.
+
+##### Unpackaged files
+
+FileName: ./package/foo.c
+SPDXID: SPDXRef-File
+FileType: SOURCE
+FileChecksum: SHA1: d6a770ba38583ed4bb4525bd96e50461655d2758
+FileChecksum: MD5: 624c1abb3664f4b35547e7c73864ad24
+LicenseConcluded: (LGPL-2.0-only OR LicenseRef-2)
+LicenseInfoInFile: GPL-2.0-only
+LicenseInfoInFile: LicenseRef-2
+LicenseComments: The concluded license was taken from the package level that the file was included in.
+FileCopyrightText: Copyright 2008-2010 John Smith
+FileComment: The concluded license was taken from the package level that the file was included in.
+This information was found in the COPYING.txt file in the xyz directory.
+FileNotice: Copyright (c) 2001 Aaron Lehmann aaroni@vitelus.com
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the �Software�), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED �AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+FileContributor: The Regents of the University of California
+FileContributor: Modified by Paul Mundt lethal@linux-sh.org
+FileContributor: IBM Corporation
+FileAttributionText: The Regents of the University of California
+FileAttributionText: Modified by Paul Mundt lethal@linux-sh.org
+FileAttributionText: IBM Corporation
+
+##### Package: glibc
+
+PackageName: glibc
+SPDXID: SPDXRef-Package
+PackageVersion: 2.11.1
+PackageFileName: glibc-2.11.1.tar.gz
+PackageSupplier: Person: Jane Doe (jane.doe@example.com)
+PackageOriginator: Organization: ExampleCodeInspect (contact@example.com)
+PackageDownloadLocation: http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz
+FilesAnalyzed: true
+PackageVerificationCode: d6a770ba38583ed4bb4525bd96e50461655d2758 (excludes: ./package.spdx)
+PackageChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
+PackageChecksum: SHA256: 11b6d3ee554eedf79299905a98f9b9a04e498210b59f15094c916c91d150efcd
+PackageChecksum: MD5: 624c1abb3664f4b35547e7c73864ad24
+PackageHomePage: http://ftp.gnu.org/gnu/glibc
+PackageSourceInfo: uses glibc-2_11-branch from git://sourceware.org/git/glibc.git.
+PackageLicenseConcluded: (LGPL-2.0-only OR LicenseRef-3)
+PackageLicenseInfoFromFiles: GPL-2.0-only
+PackageLicenseInfoFromFiles: LicenseRef-2
+PackageLicenseInfoFromFiles: LicenseRef-1
+PackageLicenseDeclared: (LGPL-2.0-only AND LicenseRef-3)
+PackageLicenseComments: The license for this project changed with the release of version x.y. The version of the project included here post-dates the license change.
+PackageCopyrightText: Copyright 2008-2010 John Smith
+PackageSummary: GNU C library.
+PackageDescription: The GNU C Library defines functions that are specified by the ISO C standard, as well as additional features specific to POSIX and other derivatives of the Unix operating system, and extensions specific to GNU systems.
+ExternalRef: SECURITY cpe23Type cpe:2.3:a:pivotal_software:spring_framework:4.1.0:*:*:*:*:*:*:*
+ExternalRef: OTHER http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301#LocationRef-acmeforge acmecorp/acmenator/4.1.3-alpha
+ExternalRefComment: This is the external ref for Acme
+PackageAttributionText: The GNU C Library is free software. See the file COPYING.LIB for copying conditions, and LICENSES for notices about a few contributions that require these additional notices to be distributed. License copyright years may be listed using range notation, e.g., 1996-2015, indicating that every year in the range, inclusive, is a copyrightable year that would otherwise be listed individually.
+
+FileName: ./lib-source/commons-lang3-3.1-sources.jar
+SPDXID: SPDXRef-CommonsLangSrc
+FileType: ARCHIVE
+FileChecksum: SHA1: c2b4e1c67a2d28fced849ee1bb76e7391b93f125
+LicenseConcluded: Apache-2.0
+LicenseInfoInFile: Apache-2.0
+FileCopyrightText: Copyright 2001-2011 The Apache Software Foundation
+FileComment: This file is used by Jena
+FileNotice: Apache Commons Lang
+Copyright 2001-2011 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).
+
+This product includes software from the Spring Framework,
+under the Apache License 2.0 (see: StringUtils.containsWhitespace())
+FileContributor: Apache Software Foundation
+FileAttributionText: Apache Software Foundation
+
+FileName: ./src/org/spdx/parser/DOAPProject.java
+SPDXID: SPDXRef-DoapSource
+FileType: SOURCE
+FileChecksum: SHA1: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
+LicenseConcluded: Apache-2.0
+LicenseInfoInFile: Apache-2.0
+FileCopyrightText: Copyright 2010, 2011 Source Auditor Inc.
+FileContributor: Protecode Inc.
+FileContributor: SPDX Technical Team Members
+FileContributor: Open Logic Inc.
+FileContributor: Source Auditor Inc.
+FileContributor: Black Duck Software In.c
+FileAttributionText: Protecode Inc.
+FileAttributionText: SPDX Technical Team Members
+FileAttributionText: Open Logic Inc.
+FileAttributionText: Source Auditor Inc.
+FileAttributionText: Black Duck Software In.c
+
+SnippetSPDXIdentifier: SPDXRef-Snippet
+SnippetFromFileSPDXID: SPDXRef-DoapSource
+SnippetByteRange: 310:420
+SnippetLineRange: 5:23
+SnippetLicenseConcluded: GPL-2.0-only
+LicenseInfoInSnippet: GPL-2.0-only
+SnippetLicenseComments: The concluded license was taken from package xyz, from which the snippet was copied into the current file. The concluded license information was found in the COPYING.txt file in package xyz.
+SnippetCopyrightText: Copyright 2008-2010 John Smith
+SnippetComment: This snippet was identified as significant and highlighted in this Apache-2.0 file, when a commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under GPL-2.0.
+SnippetName: from linux kernel
+
+FileName: ./lib-source/jena-2.6.3-sources.jar
+SPDXID: SPDXRef-JenaLib
+FileType: ARCHIVE
+FileChecksum: SHA1: 3ab4e1c67a2d28fced849ee1bb76e7391b93f125
+LicenseConcluded: LicenseRef-1
+LicenseInfoInFile: LicenseRef-1
+LicenseComments: This license is used by Jena
+FileCopyrightText: (c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
+FileComment: This file belongs to Jena
+FileContributor: Apache Software Foundation
+FileContributor: Hewlett Packard Inc.
+FileAttributionText: Apache Software Foundation
+FileAttributionText: Hewlett Packard Inc.
+
+##### Package: Saxon
+
+PackageName: Saxon
+SPDXID: SPDXRef-Saxon
+PackageVersion: 8.8
+PackageFileName: saxonB-8.8.zip
+PackageDownloadLocation: https://sourceforge.net/projects/saxon/files/Saxon-B/8.8.0.7/saxonb8-8-0-7j.zip/download
+FilesAnalyzed: false
+PackageChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
+PackageHomePage: http://saxon.sourceforge.net/
+PackageLicenseConcluded: MPL-1.0
+PackageLicenseDeclared: MPL-1.0
+PackageLicenseComments: Other versions available for a commercial license
+PackageCopyrightText: Copyright Saxonica Ltd
+PackageDescription: The Saxon package is a collection of tools for processing XML documents.
+
+##### Package: Jena
+
+PackageName: Jena
+SPDXID: SPDXRef-fromDoap-0
+PackageVersion: 3.12.0
+PackageDownloadLocation: https://search.maven.org/remotecontent?filepath=org/apache/jena/apache-jena/3.12.0/apache-jena-3.12.0.tar.gz
+FilesAnalyzed: false
+PackageHomePage: http://www.openjena.org/
+PackageLicenseConcluded: NOASSERTION
+PackageLicenseDeclared: NOASSERTION
+PackageCopyrightText: NOASSERTION
+ExternalRef: PACKAGE_MANAGER purl pkg:maven/org.apache.jena/apache-jena@3.12.0
+
+##### Package: Apache Commons Lang
+
+PackageName: Apache Commons Lang
+SPDXID: SPDXRef-fromDoap-1
+PackageDownloadLocation: NOASSERTION
+FilesAnalyzed: false
+PackageHomePage: http://commons.apache.org/proper/commons-lang/
+PackageLicenseConcluded: NOASSERTION
+PackageLicenseDeclared: NOASSERTION
+PackageCopyrightText: NOASSERTION
+
+##### Other Licenses
+
+LicenseID: LicenseRef-1
+ExtractedText: /*
+ * (c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+LicenseID: LicenseRef-2
+ExtractedText: This package includes the GRDDL parser developed by Hewlett Packard under the following license:
+� Copyright 2007 Hewlett-Packard Development Company, LP
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+LicenseID: LicenseRef-4
+ExtractedText: /*
+ * (c) Copyright 2009 University of Bristol
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+LicenseID: LicenseRef-Beerware-4.2
+ExtractedText: "THE BEER-WARE LICENSE" (Revision 42):
+phk@FreeBSD.ORG wrote this file. As long as you retain this notice you
+can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return Poul-Henning Kamp
+LicenseName: Beer-Ware License (Version 42)
+LicenseCrossReference: http://people.freebsd.org/~phk/
+LicenseComment:
+The beerware license has a couple of other standard variants.
+
+LicenseID: LicenseRef-3
+ExtractedText: The CyberNeko Software License, Version 1.0
+
+
+(C) Copyright 2002-2005, Andy Clark. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+3. The end-user documentation included with the redistribution,
+ if any, must include the following acknowledgment:
+ "This product includes software developed by Andy Clark."
+ Alternately, this acknowledgment may appear in the software itself,
+ if and wherever such third-party acknowledgments normally appear.
+
+4. The names "CyberNeko" and "NekoHTML" must not be used to endorse
+ or promote products derived from this software without prior
+ written permission. For written permission, please contact
+ andyc@cyberneko.net.
+
+5. Products derived from this software may not be called "CyberNeko",
+ nor may "CyberNeko" appear in their name, without prior written
+ permission of the author.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+LicenseName: CyberNeko License
+LicenseCrossReference: http://people.apache.org/~andyc/neko/LICENSE
+LicenseCrossReference: http://justasample.url.com
+LicenseComment: This is tye CyperNeko License
+
+##### Relationships
+
+Relationship: SPDXRef-DOCUMENT CONTAINS SPDXRef-Package
+Relationship: SPDXRef-DOCUMENT COPY_OF DocumentRef-spdx-tool-1.2:SPDXRef-ToolsElement
+Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-File
+Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-Package
+Relationship: SPDXRef-Package CONTAINS SPDXRef-JenaLib
+Relationship: SPDXRef-Package DYNAMIC_LINK SPDXRef-Saxon
+Relationship: SPDXRef-CommonsLangSrc GENERATED_FROM NOASSERTION
+Relationship: SPDXRef-JenaLib CONTAINS SPDXRef-Package
+Relationship: SPDXRef-File GENERATED_FROM SPDXRef-fromDoap-0
+
+##### Annotations
+
+Annotator: Person: File Commenter
+AnnotationDate: 2011-01-29T18:30:22Z
+AnnotationType: OTHER
+SPDXREF: SPDXRef-File
+AnnotationComment: File level annotation
+
+Annotator: Person: Package Commenter
+AnnotationDate: 2011-01-29T18:30:22Z
+AnnotationType: OTHER
+SPDXREF: SPDXRef-Package
+AnnotationComment: Package level annotation
+
+Annotator: Person: Jane Doe ()
+AnnotationDate: 2010-01-29T18:30:22Z
+AnnotationType: OTHER
+SPDXREF: SPDXRef-DOCUMENT
+AnnotationComment: Document level annotation
+
+Annotator: Person: Joe Reviewer
+AnnotationDate: 2010-02-10T00:00:00Z
+AnnotationType: REVIEW
+SPDXREF: SPDXRef-DOCUMENT
+AnnotationComment: This is just an example. Some of the non-standard licenses look like they are actually BSD 3 clause licenses
+
+Annotator: Person: Suzanne Reviewer
+AnnotationDate: 2011-03-13T00:00:00Z
+AnnotationType: REVIEW
+SPDXREF: SPDXRef-DOCUMENT
+AnnotationComment: Another example reviewer.
+
diff --git a/examples/9-jsonsaver/exampletvtojson.go b/examples/9-jsonsaver/exampletvtojson.go
new file mode 100644
index 00000000..79816c18
--- /dev/null
+++ b/examples/9-jsonsaver/exampletvtojson.go
@@ -0,0 +1,68 @@
+// 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"
+ "os"
+
+ "github.com/spdx/tools-golang/jsonloader"
+ "github.com/spdx/tools-golang/jsonsaver"
+)
+
+func main() {
+
+ // check that we've received the right number of arguments
+ args := os.Args
+ if len(args) != 3 {
+ fmt.Printf("Usage: %v \n", args[0])
+ fmt.Printf(" Load SPDX 2.2 tag-value file , and\n")
+ fmt.Printf(" save it out to .\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 := jsonloader.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 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 = 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)
+}
diff --git a/examples/9-jsonsaver/sample.json b/examples/9-jsonsaver/sample.json
new file mode 100644
index 00000000..b02dc5b0
--- /dev/null
+++ b/examples/9-jsonsaver/sample.json
@@ -0,0 +1,417 @@
+{
+ "SPDXID": "SPDXRef-DOCUMENT",
+ "spdxVersion": "SPDX-2.2",
+ "creationInfo": {
+ "comment": "This package has been shipped in source and binary form.\nThe binaries were created with gcc 4.5.1 and expect to link to\ncompatible system run time libraries.",
+ "created": "2010-01-29T18:30:22Z",
+ "creators": [
+ "Person: Jane Doe",
+ "Organization: ExampleCodeInspect",
+ "Tool: LicenseFind-1.0"
+ ],
+ "licenseListVersion": "3.9"
+ },
+ "name": "SPDX-Tools-v2.0",
+ "dataLicense": "CC0-1.0",
+ "comment": "This document was created using SPDX 2.0 using licenses from the web site.",
+ "externalDocumentRefs": [
+ {
+ "checksum": {
+ "algorithm": "SHA1",
+ "checksumValue": "d6a770ba38583ed4bb4525bd96e50461655d2759"
+ },
+ "externalDocumentId": "DocumentRef-spdx-tool-1.2",
+ "spdxDocument": "http://spdx.org/spdxdocs/spdx-tools-v1.2-3F2504E0-4F89-41D3-9A0C-0305E82C3301"
+ }
+ ],
+ "hasExtractedLicensingInfos": [
+ {
+ "extractedText": "/*\n * (c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/",
+ "licenseId": "LicenseRef-1"
+ },
+ {
+ "extractedText": "This package includes the GRDDL parser developed by Hewlett Packard under the following license:\n� Copyright 2007 Hewlett-Packard Development Company, LP\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: \n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. \nThe name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. \nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ "licenseId": "LicenseRef-2"
+ },
+ {
+ "extractedText": "/*\n * (c) Copyright 2009 University of Bristol\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/",
+ "licenseId": "LicenseRef-4"
+ },
+ {
+ "extractedText": "\"THE BEER-WARE LICENSE\" (Revision 42):\nphk@FreeBSD.ORG wrote this file. As long as you retain this notice you\ncan do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return Poul-Henning Kamp \u003c/\nLicenseName: Beer-Ware License (Version 42)\nLicenseCrossReference: http://people.freebsd.org/~phk/\nLicenseComment: \nThe beerware license has a couple of other standard variants.",
+ "licenseId": "LicenseRef-Beerware-4.2"
+ },
+ {
+ "comment": "This is tye CyperNeko License",
+ "extractedText": "The CyberNeko Software License, Version 1.0\n\n \n(C) Copyright 2002-2005, Andy Clark. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer. \n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\n3. The end-user documentation included with the redistribution,\n if any, must include the following acknowledgment: \n \"This product includes software developed by Andy Clark.\"\n Alternately, this acknowledgment may appear in the software itself,\n if and wherever such third-party acknowledgments normally appear.\n\n4. The names \"CyberNeko\" and \"NekoHTML\" must not be used to endorse\n or promote products derived from this software without prior \n written permission. For written permission, please contact \n andyc@cyberneko.net.\n\n5. Products derived from this software may not be called \"CyberNeko\",\n nor may \"CyberNeko\" appear in their name, without prior written\n permission of the author.\n\nTHIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, \nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT \nOF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR \nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \nEVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ "licenseId": "LicenseRef-3",
+ "name": "CyberNeko License",
+ "seeAlsos": [
+ "http://people.apache.org/~andyc/neko/LICENSE",
+ "http://justasample.url.com"
+ ]
+ }
+ ],
+ "annotations": [
+ {
+ "annotationDate": "2010-01-29T18:30:22Z",
+ "annotationType": "OTHER",
+ "annotator": "Person: Jane Doe ()",
+ "comment": "Document level annotation"
+ },
+ {
+ "annotationDate": "2010-02-10T00:00:00Z",
+ "annotationType": "REVIEW",
+ "annotator": "Person: Joe Reviewer",
+ "comment": "This is just an example. Some of the non-standard licenses look like they are actually BSD 3 clause licenses"
+ },
+ {
+ "annotationDate": "2011-03-13T00:00:00Z",
+ "annotationType": "REVIEW",
+ "annotator": "Person: Suzanne Reviewer",
+ "comment": "Another example reviewer."
+ }
+ ],
+ "documentNamespace": "http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301",
+ "documentDescribes": [
+ "SPDXRef-File",
+ "SPDXRef-Package"
+ ],
+ "packages": [
+ {
+ "SPDXID": "SPDXRef-Package",
+ "annotations": [
+ {
+ "annotationDate": "2011-01-29T18:30:22Z",
+ "annotationType": "OTHER",
+ "annotator": "Person: Package Commenter",
+ "comment": "Package level annotation"
+ }
+ ],
+ "attributionTexts": [
+ "The GNU C Library is free software. See the file COPYING.LIB for copying conditions, and LICENSES for notices about a few contributions that require these additional notices to be distributed. License copyright years may be listed using range notation, e.g., 1996-2015, indicating that every year in the range, inclusive, is a copyrightable year that would otherwise be listed individually."
+ ],
+ "checksums": [
+ {
+ "algorithm": "MD5",
+ "checksumValue": "624c1abb3664f4b35547e7c73864ad24"
+ },
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "85ed0817af83a24ad8da68c2b5094de69833983c"
+ },
+ {
+ "algorithm": "SHA256",
+ "checksumValue": "11b6d3ee554eedf79299905a98f9b9a04e498210b59f15094c916c91d150efcd"
+ }
+ ],
+ "copyrightText": "Copyright 2008-2010 John Smith",
+ "description": "The GNU C Library defines functions that are specified by the ISO C standard, as well as additional features specific to POSIX and other derivatives of the Unix operating system, and extensions specific to GNU systems.",
+ "downloadLocation": "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz",
+ "externalRefs": [
+ {
+ "referenceCategory": "SECURITY",
+ "referenceLocator": "cpe:2.3:a:pivotal_software:spring_framework:4.1.0:*:*:*:*:*:*:*",
+ "referenceType": "cpe23Type"
+ },
+ {
+ "comment": "This is the external ref for Acme",
+ "referenceCategory": "OTHER",
+ "referenceLocator": "acmecorp/acmenator/4.1.3-alpha",
+ "referenceType": "http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301#LocationRef-acmeforge"
+ }
+ ],
+ "filesAnalyzed": true,
+ "hasFiles": [
+ "SPDXRef-DoapSource",
+ "SPDXRef-CommonsLangSrc",
+ "SPDXRef-JenaLib"
+ ],
+ "homepage": "http://ftp.gnu.org/gnu/glibc",
+ "licenseComments": "The license for this project changed with the release of version x.y. The version of the project included here post-dates the license change.",
+ "licenseConcluded": "(LGPL-2.0-only OR LicenseRef-3)",
+ "licenseDeclared": "(LGPL-2.0-only AND LicenseRef-3)",
+ "licenseInfoFromFiles": [
+ "GPL-2.0-only",
+ "LicenseRef-2",
+ "LicenseRef-1"
+ ],
+ "name": "glibc",
+ "originator": "Organization: ExampleCodeInspect (contact@example.com)",
+ "packageFileName": "glibc-2.11.1.tar.gz",
+ "packageVerificationCode": {
+ "packageVerificationCodeExcludedFiles": [
+ "./package.spdx"
+ ],
+ "packageVerificationCodeValue": "d6a770ba38583ed4bb4525bd96e50461655d2758"
+ },
+ "sourceInfo": "uses glibc-2_11-branch from git://sourceware.org/git/glibc.git.",
+ "summary": "GNU C library.",
+ "supplier": "Person: Jane Doe (jane.doe@example.com)",
+ "versionInfo": "2.11.1"
+ },
+ {
+ "SPDXID": "SPDXRef-fromDoap-1",
+ "copyrightText": "NOASSERTION",
+ "downloadLocation": "NOASSERTION",
+ "filesAnalyzed": false,
+ "homepage": "http://commons.apache.org/proper/commons-lang/",
+ "licenseConcluded": "NOASSERTION",
+ "licenseDeclared": "NOASSERTION",
+ "name": "Apache Commons Lang"
+ },
+ {
+ "SPDXID": "SPDXRef-fromDoap-0",
+ "copyrightText": "NOASSERTION",
+ "downloadLocation": "https://search.maven.org/remotecontent?filepath=org/apache/jena/apache-jena/3.12.0/apache-jena-3.12.0.tar.gz",
+ "externalRefs": [
+ {
+ "referenceCategory": "PACKAGE_MANAGER",
+ "referenceLocator": "pkg:maven/org.apache.jena/apache-jena@3.12.0",
+ "referenceType": "purl"
+ }
+ ],
+ "filesAnalyzed": false,
+ "homepage": "http://www.openjena.org/",
+ "licenseConcluded": "NOASSERTION",
+ "licenseDeclared": "NOASSERTION",
+ "name": "Jena",
+ "versionInfo": "3.12.0"
+ },
+ {
+ "SPDXID": "SPDXRef-Saxon",
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "85ed0817af83a24ad8da68c2b5094de69833983c"
+ }
+ ],
+ "copyrightText": "Copyright Saxonica Ltd",
+ "description": "The Saxon package is a collection of tools for processing XML documents.",
+ "downloadLocation": "https://sourceforge.net/projects/saxon/files/Saxon-B/8.8.0.7/saxonb8-8-0-7j.zip/download",
+ "filesAnalyzed": false,
+ "homepage": "http://saxon.sourceforge.net/",
+ "licenseComments": "Other versions available for a commercial license",
+ "licenseConcluded": "MPL-1.0",
+ "licenseDeclared": "MPL-1.0",
+ "name": "Saxon",
+ "packageFileName": "saxonB-8.8.zip",
+ "versionInfo": "8.8"
+ }
+ ],
+ "files": [
+ {
+ "SPDXID": "SPDXRef-DoapSource",
+ "attributionTexts": [
+ "Protecode Inc.",
+ "SPDX Technical Team Members",
+ "Open Logic Inc.",
+ "Source Auditor Inc.",
+ "Black Duck Software In.c"
+ ],
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
+ }
+ ],
+ "copyrightText": "Copyright 2010, 2011 Source Auditor Inc.",
+ "fileContributors": [
+ "Protecode Inc.",
+ "SPDX Technical Team Members",
+ "Open Logic Inc.",
+ "Source Auditor Inc.",
+ "Black Duck Software In.c"
+ ],
+ "fileName": "./src/org/spdx/parser/DOAPProject.java",
+ "fileTypes": [
+ "SOURCE"
+ ],
+ "licenseConcluded": "Apache-2.0",
+ "licenseInfoInFiles": [
+ "Apache-2.0"
+ ]
+ },
+ {
+ "SPDXID": "SPDXRef-CommonsLangSrc",
+ "attributionTexts": [
+ "Apache Software Foundation"
+ ],
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "c2b4e1c67a2d28fced849ee1bb76e7391b93f125"
+ }
+ ],
+ "comment": "This file is used by Jena",
+ "copyrightText": "Copyright 2001-2011 The Apache Software Foundation",
+ "fileContributors": [
+ "Apache Software Foundation"
+ ],
+ "fileName": "./lib-source/commons-lang3-3.1-sources.jar",
+ "fileTypes": [
+ "ARCHIVE"
+ ],
+ "licenseConcluded": "Apache-2.0",
+ "licenseInfoInFiles": [
+ "Apache-2.0"
+ ],
+ "noticeText": "Apache Commons Lang\nCopyright 2001-2011 The Apache Software Foundation\n\nThis product includes software developed by\nThe Apache Software Foundation (http://www.apache.org/).\n\nThis product includes software from the Spring Framework,\nunder the Apache License 2.0 (see: StringUtils.containsWhitespace())"
+ },
+ {
+ "SPDXID": "SPDXRef-JenaLib",
+ "attributionTexts": [
+ "Apache Software Foundation",
+ "Hewlett Packard Inc."
+ ],
+ "checksums": [
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "3ab4e1c67a2d28fced849ee1bb76e7391b93f125"
+ }
+ ],
+ "comment": "This file belongs to Jena",
+ "copyrightText": "(c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP",
+ "fileContributors": [
+ "Apache Software Foundation",
+ "Hewlett Packard Inc."
+ ],
+ "fileName": "./lib-source/jena-2.6.3-sources.jar",
+ "fileTypes": [
+ "ARCHIVE"
+ ],
+ "licenseComments": "This license is used by Jena",
+ "licenseConcluded": "LicenseRef-1",
+ "licenseInfoInFiles": [
+ "LicenseRef-1"
+ ]
+ },
+ {
+ "SPDXID": "SPDXRef-File",
+ "annotations": [
+ {
+ "annotationDate": "2011-01-29T18:30:22Z",
+ "annotationType": "OTHER",
+ "annotator": "Person: File Commenter",
+ "comment": "File level annotation"
+ }
+ ],
+ "attributionTexts": [
+ "The Regents of the University of California",
+ "Modified by Paul Mundt lethal@linux-sh.org",
+ "IBM Corporation"
+ ],
+ "checksums": [
+ {
+ "algorithm": "MD5",
+ "checksumValue": "624c1abb3664f4b35547e7c73864ad24"
+ },
+ {
+ "algorithm": "SHA1",
+ "checksumValue": "d6a770ba38583ed4bb4525bd96e50461655d2758"
+ }
+ ],
+ "comment": "The concluded license was taken from the package level that the file was included in.\nThis information was found in the COPYING.txt file in the xyz directory.",
+ "copyrightText": "Copyright 2008-2010 John Smith",
+ "fileContributors": [
+ "The Regents of the University of California",
+ "Modified by Paul Mundt lethal@linux-sh.org",
+ "IBM Corporation"
+ ],
+ "fileName": "./package/foo.c",
+ "fileTypes": [
+ "SOURCE"
+ ],
+ "licenseComments": "The concluded license was taken from the package level that the file was included in.",
+ "licenseConcluded": "(LGPL-2.0-only OR LicenseRef-2)",
+ "licenseInfoInFiles": [
+ "GPL-2.0-only",
+ "LicenseRef-2"
+ ],
+ "noticeText": "Copyright (c) 2001 Aaron Lehmann aaroni@vitelus.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the �Software�), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED �AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
+ }
+ ],
+ "snippets": [
+ {
+ "SPDXID": "SPDXRef-Snippet",
+ "comment": "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under GPL-2.0.",
+ "copyrightText": "Copyright 2008-2010 John Smith",
+ "licenseComments": "The concluded license was taken from package xyz, from which the snippet was copied into the current file. The concluded license information was found in the COPYING.txt file in package xyz.",
+ "licenseConcluded": "GPL-2.0-only",
+ "licenseInfoInSnippets": [
+ "GPL-2.0-only"
+ ],
+ "name": "from linux kernel",
+ "ranges": [
+ {
+ "endPointer": {
+ "offset": 420,
+ "reference": "SPDXRef-DoapSource"
+ },
+ "startPointer": {
+ "offset": 310,
+ "reference": "SPDXRef-DoapSource"
+ }
+ },
+ {
+ "endPointer": {
+ "lineNumber": 23,
+ "reference": "SPDXRef-DoapSource"
+ },
+ "startPointer": {
+ "lineNumber": 5,
+ "reference": "SPDXRef-DoapSource"
+ }
+ }
+ ],
+ "snippetFromFile": "SPDXRef-DoapSource"
+ }
+ ],
+ "relationships": [
+ {
+ "relatedSpdxElement": "SPDXRef-Package",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-DOCUMENT"
+ },
+ {
+ "relatedSpdxElement": "DocumentRef-spdx-tool-1.2:SPDXRef-ToolsElement",
+ "relationshipType": "COPY_OF",
+ "spdxElementId": "SPDXRef-DOCUMENT"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-File",
+ "relationshipType": "DESCRIBES",
+ "spdxElementId": "SPDXRef-DOCUMENT"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-Package",
+ "relationshipType": "DESCRIBES",
+ "spdxElementId": "SPDXRef-DOCUMENT"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-JenaLib",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-Package"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-Saxon",
+ "relationshipType": "DYNAMIC_LINK",
+ "spdxElementId": "SPDXRef-Package"
+ },
+ {
+ "relatedSpdxElement": "NOASSERTION",
+ "relationshipType": "GENERATED_FROM",
+ "spdxElementId": "SPDXRef-CommonsLangSrc"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-Package",
+ "relationshipType": "CONTAINS",
+ "spdxElementId": "SPDXRef-JenaLib"
+ },
+ {
+ "relatedSpdxElement": "SPDXRef-fromDoap-0",
+ "relationshipType": "GENERATED_FROM",
+ "spdxElementId": "SPDXRef-File"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/README.md b/examples/README.md
index 134e2ee8..7cd80a06 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -59,7 +59,7 @@ the same identifier in both documents.
## 7-rdfloader
-*rdfloader*,
+*rdfloader*, *spdx*
This example demonstrates loading an SPDX rdf file from disk into memory
and then printing the corresponding spdx struct for the document.
@@ -69,4 +69,4 @@ and then printing the corresponding spdx struct for the document.
*jsonloader*, *tvsaver*
This example demonstrates loading an SPDX json from disk into memory
-and then re-saving it to a different file on disk in tag-value format.
\ No newline at end of file
+and then re-saving it to a different file on disk in tag-value format.
diff --git a/jsonloader/parser2v2/parse_creation_info.go b/jsonloader/parser2v2/parse_creation_info.go
index 074e25e1..9e818e83 100644
--- a/jsonloader/parser2v2/parse_creation_info.go
+++ b/jsonloader/parser2v2/parse_creation_info.go
@@ -79,9 +79,9 @@ func parseCreators(creators interface{}, ci *spdx.CreationInfo2_2) error {
}
switch subkey {
case "Person":
- ci.CreatorPersons = append(ci.CreatorPersons, strings.TrimSuffix(subvalue, " ()"))
+ ci.CreatorPersons = append(ci.CreatorPersons, subvalue)
case "Organization":
- ci.CreatorOrganizations = append(ci.CreatorOrganizations, strings.TrimSuffix(subvalue, " ()"))
+ ci.CreatorOrganizations = append(ci.CreatorOrganizations, subvalue)
case "Tool":
ci.CreatorTools = append(ci.CreatorTools, subvalue)
default:
diff --git a/jsonloader/parser2v2/parse_creation_info_test.go b/jsonloader/parser2v2/parse_creation_info_test.go
index 525bb505..ae62cba1 100644
--- a/jsonloader/parser2v2/parse_creation_info_test.go
+++ b/jsonloader/parser2v2/parse_creation_info_test.go
@@ -115,8 +115,8 @@ func TestJSONSpdxDocument_parseJsonCreationInfo2_2(t *testing.T) {
want: &spdx.CreationInfo2_2{
CreatorComment: "This package has been shipped in source and binary form.\nThe binaries were created with gcc 4.5.1 and expect to link to\ncompatible system run time libraries.",
Created: "2010-01-29T18:30:22Z",
- CreatorPersons: []string{"Jane Doe"},
- CreatorOrganizations: []string{"ExampleCodeInspect"},
+ CreatorPersons: []string{"Jane Doe ()"},
+ CreatorOrganizations: []string{"ExampleCodeInspect ()"},
CreatorTools: []string{"LicenseFind-1.0"},
LicenseListVersion: "3.8",
ExternalDocumentReferences: map[string]spdx.ExternalDocumentRef2_2{},
diff --git a/jsonloader/parser2v2/parse_snippets.go b/jsonloader/parser2v2/parse_snippets.go
index 68a018a9..a49191d7 100644
--- a/jsonloader/parser2v2/parse_snippets.go
+++ b/jsonloader/parser2v2/parse_snippets.go
@@ -70,7 +70,7 @@ func (spec JSONSpdxDocument) parseJsonSnippets2_2(key string, value interface{},
}
}
default:
- return fmt.Errorf("received unknown tag %v in files section", k)
+ return fmt.Errorf("received unknown tag %v in snippet section", k)
}
}
fileID, err2 := extractDocElementID(snippetmap["snippetFromFile"].(string))
diff --git a/jsonloader/parser2v2/parser_test.go b/jsonloader/parser2v2/parser_test.go
index d80e9d51..051ff99f 100644
--- a/jsonloader/parser2v2/parser_test.go
+++ b/jsonloader/parser2v2/parser_test.go
@@ -43,8 +43,8 @@ func TestLoad2_2(t *testing.T) {
DocumentComment: "This document was created using SPDX 2.0 using licenses from the web site.",
LicenseListVersion: "3.8",
Created: "2010-01-29T18:30:22Z",
- CreatorPersons: []string{"Jane Doe"},
- CreatorOrganizations: []string{"ExampleCodeInspect"},
+ CreatorPersons: []string{"Jane Doe ()"},
+ CreatorOrganizations: []string{"ExampleCodeInspect ()"},
CreatorTools: []string{"LicenseFind-1.0"},
DocumentName: "SPDX-Tools-v2.0",
DocumentNamespace: "http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301",
diff --git a/jsonsaver/jsonsaver.go b/jsonsaver/jsonsaver.go
new file mode 100644
index 00000000..35898ad5
--- /dev/null
+++ b/jsonsaver/jsonsaver.go
@@ -0,0 +1,23 @@
+package jsonsaver
+
+import (
+ "bytes"
+ "io"
+
+ "github.com/spdx/tools-golang/jsonsaver/saver2v2"
+ "github.com/spdx/tools-golang/spdx"
+)
+
+// Save2_2 takes an io.Writer and an SPDX Document (version 2.2),
+// and writes it to the writer in json format. It returns error
+// if any error is encountered.
+func Save2_2(doc *spdx.Document2_2, w io.Writer) error {
+ var b []byte
+ buf := bytes.NewBuffer(b)
+ result, err := saver2v2.RenderDocument2_2(doc, buf)
+ if err != nil {
+ return err
+ }
+ w.Write(result.Bytes())
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_annotations.go b/jsonsaver/saver2v2/save_annotations.go
new file mode 100644
index 00000000..0a69c2ca
--- /dev/null
+++ b/jsonsaver/saver2v2/save_annotations.go
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package saver2v2
+
+import (
+ "fmt"
+
+ "github.com/spdx/tools-golang/spdx"
+)
+
+func renderAnnotations2_2(annotations []*spdx.Annotation2_2, eID spdx.DocElementID) ([]interface{}, error) {
+
+ var ann []interface{}
+ for _, v := range annotations {
+ if v.AnnotationSPDXIdentifier == eID {
+ annotation := make(map[string]interface{})
+ annotation["annotationDate"] = v.AnnotationDate
+ annotation["annotationType"] = v.AnnotationType
+ annotation["annotator"] = fmt.Sprintf("%s: %s", v.AnnotatorType, v.Annotator)
+ if v.AnnotationComment != "" {
+ annotation["comment"] = v.AnnotationComment
+ }
+ ann = append(ann, annotation)
+ }
+ }
+ return ann, nil
+}
diff --git a/jsonsaver/saver2v2/save_creation_info.go b/jsonsaver/saver2v2/save_creation_info.go
new file mode 100644
index 00000000..60f4e953
--- /dev/null
+++ b/jsonsaver/saver2v2/save_creation_info.go
@@ -0,0 +1,74 @@
+// 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"
+)
+
+func renderCreationInfo2_2(ci *spdx.CreationInfo2_2, buf *bytes.Buffer) error {
+ if ci.SPDXIdentifier != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "SPDXID", spdx.RenderElementID(ci.SPDXIdentifier))
+ }
+ if ci.SPDXVersion != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "spdxVersion", ci.SPDXVersion)
+ }
+ if ci.CreatorComment != "" || ci.Created != "" || ci.CreatorPersons != nil || ci.CreatorOrganizations != nil || ci.CreatorTools != nil || ci.LicenseListVersion != "" {
+ fmt.Fprintf(buf, "\"%s\": %s", "creationInfo", "{")
+ if ci.CreatorComment != "" {
+ commentjson, _ := json.Marshal(ci.CreatorComment)
+ fmt.Fprintf(buf, "\"%s\": %s,", "comment", commentjson)
+ }
+ if ci.Created != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "created", ci.Created)
+ }
+ if ci.CreatorPersons != nil || ci.CreatorOrganizations != nil || ci.CreatorTools != nil {
+ var creators []string
+ for _, v := range ci.CreatorPersons {
+ creators = append(creators, fmt.Sprintf("Person: %s", v))
+ }
+ for _, v := range ci.CreatorOrganizations {
+ creators = append(creators, fmt.Sprintf("Organization: %s", v))
+ }
+ for _, v := range ci.CreatorTools {
+ creators = append(creators, fmt.Sprintf("Tool: %s", v))
+ }
+ creatorsjson, _ := json.Marshal(creators)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "creators", creatorsjson)
+ }
+ if ci.LicenseListVersion != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "licenseListVersion", ci.LicenseListVersion)
+ }
+ fmt.Fprintf(buf, "%s", "},")
+ }
+ if ci.DocumentName != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "name", ci.DocumentName)
+ }
+ if ci.DataLicense != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "dataLicense", ci.DataLicense)
+ }
+ if ci.DocumentComment != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "comment", ci.DocumentComment)
+ }
+ if ci.ExternalDocumentReferences != nil {
+ var refs []interface{}
+ for _, v := range ci.ExternalDocumentReferences {
+ aa := make(map[string]interface{})
+ aa["externalDocumentId"] = fmt.Sprintf("DocumentRef-%s", v.DocumentRefID)
+ aa["checksum"] = map[string]string{
+ "algorithm": v.Alg,
+ "checksumValue": v.Checksum,
+ }
+ aa["spdxDocument"] = v.URI
+ refs = append(refs, aa)
+ }
+ refsjson, _ := json.Marshal(refs)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "externalDocumentRefs", refsjson)
+ }
+
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_document.go b/jsonsaver/saver2v2/save_document.go
new file mode 100644
index 00000000..7ddb8175
--- /dev/null
+++ b/jsonsaver/saver2v2/save_document.go
@@ -0,0 +1,90 @@
+// 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) (*bytes.Buffer, error) {
+
+ fmt.Fprintln(buf, "{")
+ // start to parse the creationInfo
+ if doc.CreationInfo == nil {
+ return nil, fmt.Errorf("document had nil CreationInfo section")
+ }
+ renderCreationInfo2_2(doc.CreationInfo, buf)
+
+ // parse otherlicenses from sodx struct to json
+ if doc.OtherLicenses != nil {
+ renderOtherLicenses2_2(doc.OtherLicenses, buf)
+ }
+
+ // parse document level annotations
+ if doc.Annotations != nil {
+ ann, _ := renderAnnotations2_2(doc.Annotations, spdx.MakeDocElementID("", string(doc.CreationInfo.SPDXIdentifier)))
+ annotationjson, _ := json.Marshal(ann)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "annotations", annotationjson)
+ }
+
+ // parse document namespace
+ if doc.CreationInfo.DocumentNamespace != "" {
+ fmt.Fprintf(buf, "\"%s\": \"%s\",", "documentNamespace", doc.CreationInfo.DocumentNamespace)
+ }
+
+ // parse document describes
+ describes, _ := spdxlib.GetDescribedPackageIDs2_2(doc)
+ if describes != nil {
+ var describesID []string
+ for _, v := range describes {
+ describesID = append(describesID, spdx.RenderElementID(v))
+ }
+ describesjson, _ := json.Marshal(describesID)
+ fmt.Fprintf(buf, "\"%s\": %s,", "documentDescribes", describesjson)
+ }
+
+ // parse packages from spdx to json
+ if doc.Packages != nil {
+ renderPackage2_2(doc, buf)
+ }
+
+ // parse files and snippets from spdx to json
+ if doc.UnpackagedFiles != nil {
+ renderfiles2_2(doc, buf)
+ renderSnippets2_2(doc, buf)
+ }
+
+ // parse reviews from spdx to json
+ if doc.Reviews != nil {
+ renderReviews2_2(doc.Reviews, buf)
+ }
+
+ // parse relationships from spdx to json
+ if doc.Relationships != nil {
+ renderRelationships2_2(doc.Relationships, buf)
+ }
+
+ // parsing ends
+ buf.WriteRune('}')
+ // remove the pattern ",}" from the json
+ final := bytes.ReplaceAll(buf.Bytes(), []byte(",}"), []byte("}"))
+ // indent the json properly
+ var b []byte
+ newbuf := bytes.NewBuffer(b)
+ err := json.Indent(newbuf, final, "", "\t")
+ if err != nil {
+ return nil, err
+ }
+ return newbuf, nil
+}
diff --git a/jsonsaver/saver2v2/save_document_test.go b/jsonsaver/saver2v2/save_document_test.go
new file mode 100644
index 00000000..1075d757
--- /dev/null
+++ b/jsonsaver/saver2v2/save_document_test.go
@@ -0,0 +1,374 @@
+// 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"
+ "testing"
+
+ "github.com/spdx/tools-golang/spdx"
+)
+
+func TestRenderDocument2_2(t *testing.T) {
+
+ test1 := &spdx.Document2_2{
+ CreationInfo: &spdx.CreationInfo2_2{
+ SPDXVersion: "SPDX-2.2",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ DocumentName: "tools-golang-0.0.1.abcdef",
+ DocumentNamespace: "https://github.com/spdx/spdx-docs/tools-golang/tools-golang-0.0.1.abcdef.whatever",
+ CreatorPersons: []string{
+ "John Doe ()",
+ },
+ CreatorOrganizations: []string{"ExampleCodeInspect"},
+ CreatorTools: []string{"LicenseFind-1.0"},
+ DocumentComment: "This document was created using SPDX 2.0 using licenses from the web site.",
+ LicenseListVersion: "3.8",
+ CreatorComment: "This package has been shipped in source and binary form.\nThe binaries were created with gcc 4.5.1 and expect to link to\ncompatible system run time libraries.",
+ Created: "2018-10-10T06:20:00Z",
+ ExternalDocumentReferences: map[string]spdx.ExternalDocumentRef2_2{
+ "spdx-tool-1.2": {
+ DocumentRefID: "spdx-tool-1.2",
+ URI: "http://spdx.org/spdxdocs/spdx-tools-v1.2-3F2504E0-4F89-41D3-9A0C-0305E82C3301",
+ Alg: "SHA1",
+ Checksum: "d6a770ba38583ed4bb4525bd96e50461655d2759",
+ },
+ },
+ },
+ OtherLicenses: []*spdx.OtherLicense2_2{
+ {
+ ExtractedText: "\"THE BEER-WARE LICENSE\" (Revision 42):\nphk@FreeBSD.ORG wrote this file. As long as you retain this notice you\ncan do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return Poul-Henning Kamp \nLicenseName: Beer-Ware License (Version 42)\nLicenseCrossReference: http://people.freebsd.org/~phk/\nLicenseComment: \nThe beerware license has a couple of other standard variants.",
+ LicenseIdentifier: "LicenseRef-Beerware-4.2",
+ },
+ {
+ ExtractedText: "/*\n * (c) Copyright 2009 University of Bristol\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/",
+ LicenseIdentifier: "LicenseRef-4",
+ },
+ {
+ LicenseComment: "This is tye CyperNeko License",
+ ExtractedText: "The CyberNeko Software License, Version 1.0\n\n \n(C) Copyright 2002-2005, Andy Clark. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer. \n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the\n distribution.\n\n3. The end-user documentation included with the redistribution,\n if any, must include the following acknowledgment: \n \"This product includes software developed by Andy Clark.\"\n Alternately, this acknowledgment may appear in the software itself,\n if and wherever such third-party acknowledgments normally appear.\n\n4. The names \"CyberNeko\" and \"NekoHTML\" must not be used to endorse\n or promote products derived from this software without prior \n written permission. For written permission, please contact \n andyc@cyberneko.net.\n\n5. Products derived from this software may not be called \"CyberNeko\",\n nor may \"CyberNeko\" appear in their name, without prior written\n permission of the author.\n\nTHIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, \nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT \nOF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR \nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \nEVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ LicenseIdentifier: "LicenseRef-3",
+ LicenseName: "CyberNeko License",
+ LicenseCrossReferences: []string{"http://people.apache.org/~andyc/neko/LICENSE", "http://justasample.url.com"},
+ },
+ {
+ ExtractedText: "This package includes the GRDDL parser developed by Hewlett Packard under the following license:\n� Copyright 2007 Hewlett-Packard Development Company, LP\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: \n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. \nThe name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. \nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ LicenseIdentifier: "LicenseRef-2",
+ },
+ {
+ ExtractedText: "/*\n * (c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/",
+ LicenseIdentifier: "LicenseRef-1",
+ },
+ },
+ Annotations: []*spdx.Annotation2_2{
+ {
+ AnnotationSPDXIdentifier: spdx.DocElementID{DocumentRefID: "", ElementRefID: "File"},
+ AnnotationDate: "2011-01-29T18:30:22Z",
+ AnnotationType: "OTHER",
+ AnnotatorType: "Person",
+ Annotator: "File Commenter",
+ AnnotationComment: "File level annotation",
+ },
+ {
+ AnnotationSPDXIdentifier: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ AnnotationDate: "2011-01-29T18:30:22Z",
+ AnnotationType: "OTHER",
+ AnnotatorType: "Person",
+ Annotator: "Package Commenter",
+ AnnotationComment: "Package level annotation",
+ },
+ {
+ AnnotationSPDXIdentifier: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ AnnotationDate: "2010-02-10T00:00:00Z",
+ AnnotationType: "REVIEW",
+ AnnotatorType: "Person",
+ Annotator: "Joe Reviewer",
+ AnnotationComment: "This is just an example. Some of the non-standard licenses look like they are actually BSD 3 clause licenses",
+ },
+ {
+ AnnotationSPDXIdentifier: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ AnnotationDate: "2011-03-13T00:00:00Z",
+ AnnotationType: "REVIEW",
+ AnnotatorType: "Person",
+ Annotator: "Suzanne Reviewer",
+ AnnotationComment: "Another example reviewer.",
+ },
+ {
+ AnnotationSPDXIdentifier: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ AnnotationDate: "2010-01-29T18:30:22Z",
+ AnnotationType: "OTHER",
+ AnnotatorType: "Person",
+ Annotator: "Jane Doe ()",
+ AnnotationComment: "Document level annotation",
+ },
+ },
+ Relationships: []*spdx.Relationship2_2{
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ RefB: spdx.DocElementID{DocumentRefID: "spdx-tool-1.2", ElementRefID: "ToolsElement"},
+ Relationship: "COPY_OF",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ Relationship: "CONTAINS",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "File"},
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "DOCUMENT"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Saxon"},
+ Relationship: "DYNAMIC_LINK",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "JenaLib"},
+ Relationship: "CONTAINS",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "CommonsLangSrc"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "", SpecialID: "NOASSERTION"},
+ Relationship: "GENERATED_FROM",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "JenaLib"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "Package"},
+ Relationship: "CONTAINS",
+ },
+ {
+ RefA: spdx.DocElementID{DocumentRefID: "", ElementRefID: "File"},
+ RefB: spdx.DocElementID{DocumentRefID: "", ElementRefID: "fromDoap-0"},
+ Relationship: "GENERATED_FROM",
+ },
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_2{
+ "Package": {
+ PackageSPDXIdentifier: "Package",
+ PackageAttributionTexts: []string{"The GNU C Library is free software. See the file COPYING.LIB for copying conditions, and LICENSES for notices about a few contributions that require these additional notices to be distributed. License copyright years may be listed using range notation, e.g., 1996-2015, indicating that every year in the range, inclusive, is a copyrightable year that would otherwise be listed individually."},
+ PackageChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA256": {
+ Algorithm: "SHA256",
+ Value: "11b6d3ee554eedf79299905a98f9b9a04e498210b59f15094c916c91d150efcd",
+ },
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "85ed0817af83a24ad8da68c2b5094de69833983c",
+ },
+ "MD5": {
+ Algorithm: "MD5",
+ Value: "624c1abb3664f4b35547e7c73864ad24",
+ },
+ },
+ PackageCopyrightText: "Copyright 2008-2010 John Smith",
+ PackageDescription: "The GNU C Library defines functions that are specified by the ISO C standard, as well as additional features specific to POSIX and other derivatives of the Unix operating system, and extensions specific to GNU systems.",
+ PackageDownloadLocation: "http://ftp.gnu.org/gnu/glibc/glibc-ports-2.15.tar.gz",
+ PackageExternalReferences: []*spdx.PackageExternalReference2_2{
+ {
+ RefType: "http://spdx.org/spdxdocs/spdx-example-444504E0-4F89-41D3-9A0C-0305E82C3301#LocationRef-acmeforge",
+ ExternalRefComment: "This is the external ref for Acme",
+ Category: "OTHER",
+ Locator: "acmecorp/acmenator/4.1.3-alpha",
+ },
+ {
+ RefType: "http://spdx.org/rdf/references/cpe23Type",
+ Category: "SECURITY",
+ Locator: "cpe:2.3:a:pivotal_software:spring_framework:4.1.0:*:*:*:*:*:*:*",
+ },
+ },
+ FilesAnalyzed: true,
+ IsFilesAnalyzedTagPresent: true,
+ Files: map[spdx.ElementID]*spdx.File2_2{
+ "DoapSource": {
+ FileSPDXIdentifier: "DoapSource",
+ FileChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
+ },
+ },
+ Snippets: map[spdx.ElementID]*spdx.Snippet2_2{
+ "Snippet": {
+ SnippetSPDXIdentifier: "Snippet",
+ SnippetFromFileSPDXIdentifier: spdx.DocElementID{ElementRefID: "DoapSource"},
+ SnippetComment: "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under GPL-2.0.",
+ SnippetCopyrightText: "Copyright 2008-2010 John Smith",
+ SnippetLicenseComments: "The concluded license was taken from package xyz, from which the snippet was copied into the current file. The concluded license information was found in the COPYING.txt file in package xyz.",
+ SnippetLicenseConcluded: "GPL-2.0-only",
+ LicenseInfoInSnippet: []string{"GPL-2.0-only"},
+ SnippetName: "from linux kernel",
+ SnippetByteRangeStart: 310,
+ SnippetByteRangeEnd: 420,
+ SnippetLineRangeStart: 5,
+ SnippetLineRangeEnd: 23,
+ },
+ },
+ FileCopyrightText: "Copyright 2010, 2011 Source Auditor Inc.",
+ FileContributor: []string{"Protecode Inc.", "SPDX Technical Team Members", "Open Logic Inc.", "Source Auditor Inc.", "Black Duck Software In.c"},
+ FileDependencies: []string{"SPDXRef-JenaLib", "SPDXRef-CommonsLangSrc"},
+ FileName: "./src/org/spdx/parser/DOAPProject.java",
+ FileType: []string{"SOURCE"},
+ LicenseConcluded: "Apache-2.0",
+ LicenseInfoInFile: []string{"Apache-2.0"},
+ },
+ "CommonsLangSrc": {
+ FileSPDXIdentifier: "CommonsLangSrc",
+ FileChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "c2b4e1c67a2d28fced849ee1bb76e7391b93f125",
+ },
+ },
+ FileComment: "This file is used by Jena",
+ FileCopyrightText: "Copyright 2001-2011 The Apache Software Foundation",
+ FileContributor: []string{"Apache Software Foundation"},
+ FileName: "./lib-source/commons-lang3-3.1-sources.jar",
+ FileType: []string{"ARCHIVE"},
+ LicenseConcluded: "Apache-2.0",
+ LicenseInfoInFile: []string{"Apache-2.0"},
+ FileNotice: "Apache Commons Lang\nCopyright 2001-2011 The Apache Software Foundation\n\nThis product includes software developed by\nThe Apache Software Foundation (http://www.apache.org/).\n\nThis product includes software from the Spring Framework,\nunder the Apache License 2.0 (see: StringUtils.containsWhitespace())",
+ },
+ "JenaLib": {
+ FileSPDXIdentifier: "JenaLib",
+ FileChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "3ab4e1c67a2d28fced849ee1bb76e7391b93f125",
+ },
+ },
+ FileComment: "This file belongs to Jena",
+ FileCopyrightText: "(c) Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP",
+ FileContributor: []string{"Apache Software Foundation", "Hewlett Packard Inc."},
+ FileDependencies: []string{"SPDXRef-CommonsLangSrc"},
+ FileName: "./lib-source/jena-2.6.3-sources.jar",
+ FileType: []string{"ARCHIVE"},
+ LicenseComments: "This license is used by Jena",
+ LicenseConcluded: "LicenseRef-1",
+ LicenseInfoInFile: []string{"LicenseRef-1"},
+ },
+ },
+ PackageHomePage: "http://ftp.gnu.org/gnu/glibc",
+ PackageLicenseComments: "The license for this project changed with the release of version x.y. The version of the project included here post-dates the license change.",
+ PackageLicenseConcluded: "(LGPL-2.0-only OR LicenseRef-3)",
+ PackageLicenseDeclared: "(LGPL-2.0-only AND LicenseRef-3)",
+ PackageLicenseInfoFromFiles: []string{"GPL-2.0-only", "LicenseRef-2", "LicenseRef-1"},
+ PackageName: "glibc",
+ PackageOriginatorOrganization: "ExampleCodeInspect (contact@example.com)",
+ PackageFileName: "glibc-2.11.1.tar.gz",
+ PackageVerificationCodeExcludedFile: "./package.spdx",
+ PackageVerificationCode: "d6a770ba38583ed4bb4525bd96e50461655d2758",
+ PackageSourceInfo: "uses glibc-2_11-branch from git://sourceware.org/git/glibc.git.",
+ PackageSummary: "GNU C library.",
+ PackageSupplierPerson: "Jane Doe (jane.doe@example.com)",
+ PackageVersion: "2.11.1",
+ },
+ "fromDoap-1": {
+ PackageSPDXIdentifier: "fromDoap-1",
+ PackageComment: "This package was converted from a DOAP Project by the same name",
+ PackageCopyrightText: "NOASSERTION",
+ PackageDownloadLocation: "NOASSERTION",
+ FilesAnalyzed: false,
+ IsFilesAnalyzedTagPresent: true,
+ PackageHomePage: "http://commons.apache.org/proper/commons-lang/",
+ PackageLicenseConcluded: "NOASSERTION",
+ PackageLicenseDeclared: "NOASSERTION",
+ PackageName: "Apache Commons Lang",
+ },
+ "fromDoap-0": {
+ PackageSPDXIdentifier: "fromDoap-0",
+ PackageComment: "This package was converted from a DOAP Project by the same name",
+ PackageCopyrightText: "NOASSERTION",
+ PackageDownloadLocation: "NOASSERTION",
+ FilesAnalyzed: false,
+ IsFilesAnalyzedTagPresent: true,
+ PackageHomePage: "http://www.openjena.org/",
+ PackageLicenseConcluded: "NOASSERTION",
+ PackageLicenseDeclared: "NOASSERTION",
+ PackageName: "Jena",
+ },
+
+ "Saxon": {
+ PackageSPDXIdentifier: "Saxon",
+ PackageChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "85ed0817af83a24ad8da68c2b5094de69833983c",
+ },
+ },
+ PackageDescription: "The Saxon package is a collection of tools for processing XML documents.",
+ PackageDownloadLocation: "https://sourceforge.net/projects/saxon/files/Saxon-B/8.8.0.7/saxonb8-8-0-7j.zip/download",
+ FilesAnalyzed: false,
+ IsFilesAnalyzedTagPresent: true,
+ PackageHomePage: "http://saxon.sourceforge.net/",
+ PackageLicenseComments: "Other versions available for a commercial license",
+ PackageLicenseConcluded: "MPL-1.0",
+ PackageLicenseDeclared: "MPL-1.0",
+ PackageName: "Saxon",
+ PackageFileName: "saxonB-8.8.zip",
+ PackageVersion: "8.8",
+ },
+ },
+ UnpackagedFiles: map[spdx.ElementID]*spdx.File2_2{
+ "File": {
+ FileSPDXIdentifier: "File",
+ FileChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ "SHA1": {
+ Algorithm: "SHA1",
+ Value: "d6a770ba38583ed4bb4525bd96e50461655d2758",
+ },
+ "MD5": {
+ Algorithm: "MD5",
+ Value: "624c1abb3664f4b35547e7c73864ad24",
+ },
+ },
+ FileComment: "The concluded license was taken from the package level that the file was included in.\nThis information was found in the COPYING.txt file in the xyz directory.",
+ FileCopyrightText: "Copyright 2008-2010 John Smith",
+ FileContributor: []string{"The Regents of the University of California", "Modified by Paul Mundt lethal@linux-sh.org", "IBM Corporation"},
+ FileName: "./package/foo.c",
+ FileType: []string{"SOURCE"},
+ LicenseComments: "The concluded license was taken from the package level that the file was included in.",
+ LicenseConcluded: "(LGPL-2.0-only OR LicenseRef-2)",
+ LicenseInfoInFile: []string{"GPL-2.0-only", "LicenseRef-2"},
+ FileNotice: "Copyright (c) 2001 Aaron Lehmann aaroni@vitelus.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the �Software�), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED �AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
+ },
+ },
+ }
+ var b []byte
+
+ type args struct {
+ doc *spdx.Document2_2
+ buf *bytes.Buffer
+ }
+ tests := []struct {
+ name string
+ args args
+ wantErr bool
+ }{
+ // TODO: Add test cases.
+ {
+ name: "success test ",
+ args: args{
+ doc: test1,
+ buf: bytes.NewBuffer(b),
+ },
+ wantErr: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if _, err := RenderDocument2_2(tt.args.doc, tt.args.buf); (err != nil) != tt.wantErr {
+ t.Errorf("RenderDocument2_2() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
diff --git a/jsonsaver/saver2v2/save_files.go b/jsonsaver/saver2v2/save_files.go
new file mode 100644
index 00000000..741d4111
--- /dev/null
+++ b/jsonsaver/saver2v2/save_files.go
@@ -0,0 +1,78 @@
+// 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"
+)
+
+func renderfiles2_2(doc *spdx.Document2_2, buf *bytes.Buffer) error {
+
+ var files []interface{}
+ for k, v := range doc.UnpackagedFiles {
+ file := make(map[string]interface{})
+ file["SPDXID"] = spdx.RenderElementID(k)
+ ann, _ := renderAnnotations2_2(doc.Annotations, spdx.MakeDocElementID("", string(v.FileSPDXIdentifier)))
+ if ann != nil {
+ file["annotations"] = ann
+ }
+ if v.FileContributor != nil {
+ file["attributionTexts"] = v.FileContributor
+ }
+ if v.FileComment != "" {
+ file["comment"] = v.FileComment
+ }
+
+ // parse package checksums
+ if v.FileChecksums != nil {
+ var checksums []interface{}
+ for _, value := range v.FileChecksums {
+ checksum := make(map[string]interface{})
+ checksum["algorithm"] = value.Algorithm
+ checksum["checksumValue"] = value.Value
+ checksums = append(checksums, checksum)
+ }
+ file["checksums"] = checksums
+ }
+ if v.FileCopyrightText != "" {
+ file["copyrightText"] = v.FileCopyrightText
+ }
+ if v.FileName != "" {
+ file["fileName"] = v.FileName
+ }
+ if v.FileType != nil {
+ file["fileTypes"] = v.FileType
+ }
+ if v.LicenseComments != "" {
+ file["licenseComments"] = v.LicenseComments
+ }
+ if v.LicenseConcluded != "" {
+ file["licenseConcluded"] = v.LicenseConcluded
+ }
+ if v.LicenseInfoInFile != nil {
+ file["licenseInfoInFiles"] = v.LicenseInfoInFile
+ }
+ if v.FileNotice != "" {
+ file["noticeText"] = v.FileNotice
+ }
+ if v.FileContributor != nil {
+ file["fileContributors"] = v.FileContributor
+ }
+ if v.FileDependencies != nil {
+ file["fileDependencies"] = v.FileDependencies
+ }
+ if v.FileAttributionTexts != nil {
+ file["attributionTexts"] = v.FileAttributionTexts
+ }
+
+ files = append(files, file)
+ }
+ filesjson, _ := json.Marshal(files)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "files", filesjson)
+
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_other_license.go b/jsonsaver/saver2v2/save_other_license.go
new file mode 100644
index 00000000..ef8171ab
--- /dev/null
+++ b/jsonsaver/saver2v2/save_other_license.go
@@ -0,0 +1,35 @@
+// 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"
+)
+
+func renderOtherLicenses2_2(otherlicenses []*spdx.OtherLicense2_2, buf *bytes.Buffer) error {
+
+ var licenses []interface{}
+ for _, v := range otherlicenses {
+ lic := make(map[string]interface{})
+ lic["licenseId"] = v.LicenseIdentifier
+ lic["extractedText"] = v.ExtractedText
+ if v.LicenseComment != "" {
+ lic["comment"] = v.LicenseComment
+ }
+ if v.LicenseName != "" {
+ lic["name"] = v.LicenseName
+ }
+ if v.LicenseCrossReferences != nil {
+ lic["seeAlsos"] = v.LicenseCrossReferences
+ }
+ licenses = append(licenses, lic)
+ }
+ licensesjson, _ := json.Marshal(licenses)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "hasExtractedLicensingInfos", licensesjson)
+
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_package.go b/jsonsaver/saver2v2/save_package.go
new file mode 100644
index 00000000..95d28339
--- /dev/null
+++ b/jsonsaver/saver2v2/save_package.go
@@ -0,0 +1,142 @@
+// 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"
+)
+
+func renderPackage2_2(doc *spdx.Document2_2, buf *bytes.Buffer) error {
+
+ var packages []interface{}
+ for k, v := range doc.Packages {
+ pkg := make(map[string]interface{})
+ pkg["SPDXID"] = spdx.RenderElementID(k)
+ ann, _ := renderAnnotations2_2(doc.Annotations, spdx.MakeDocElementID("", string(v.PackageSPDXIdentifier)))
+ if ann != nil {
+ pkg["annotations"] = ann
+ }
+ if v.PackageAttributionTexts != nil {
+ pkg["attributionTexts"] = v.PackageAttributionTexts
+ }
+ // parse package checksums
+ if v.PackageChecksums != nil {
+ var checksums []interface{}
+ for _, value := range v.PackageChecksums {
+ checksum := make(map[string]interface{})
+ checksum["algorithm"] = value.Algorithm
+ checksum["checksumValue"] = value.Value
+ checksums = append(checksums, checksum)
+ }
+ pkg["checksums"] = checksums
+ }
+ if v.PackageCopyrightText != "" {
+ pkg["copyrightText"] = v.PackageCopyrightText
+ }
+ if v.PackageDescription != "" {
+ pkg["description"] = v.PackageDescription
+ }
+ if v.PackageDownloadLocation != "" {
+ pkg["downloadLocation"] = v.PackageDownloadLocation
+ }
+
+ //parse document external refereneces
+ if v.PackageExternalReferences != nil {
+ var externalrefs []interface{}
+ for _, value := range v.PackageExternalReferences {
+ ref := make(map[string]interface{})
+ ref["referenceCategory"] = value.Category
+ ref["referenceLocator"] = value.Locator
+ ref["referenceType"] = value.RefType
+ if value.ExternalRefComment != "" {
+ ref["comment"] = value.ExternalRefComment
+ }
+ externalrefs = append(externalrefs, ref)
+ }
+ pkg["externalRefs"] = externalrefs
+ }
+
+ pkg["filesAnalyzed"] = v.FilesAnalyzed
+
+ // parse package hass files
+ if v.Files != nil {
+ var fileIds []string
+ for k, v := range v.Files {
+ doc.UnpackagedFiles[k] = v
+ fileIds = append(fileIds, spdx.RenderElementID(k))
+ }
+ pkg["hasFiles"] = fileIds
+ }
+
+ if v.PackageHomePage != "" {
+ pkg["homepage"] = v.PackageHomePage
+ }
+ if v.PackageLicenseComments != "" {
+ pkg["licenseComments"] = v.PackageLicenseComments
+ }
+ if v.PackageLicenseConcluded != "" {
+ pkg["licenseConcluded"] = v.PackageLicenseConcluded
+ }
+ if v.PackageLicenseDeclared != "" {
+ pkg["licenseDeclared"] = v.PackageLicenseDeclared
+ }
+ if v.PackageLicenseInfoFromFiles != nil {
+ pkg["licenseInfoFromFiles"] = v.PackageLicenseInfoFromFiles
+ }
+ if v.PackageName != "" {
+ pkg["name"] = v.PackageName
+ }
+ if v.PackageSourceInfo != "" {
+ pkg["sourceInfo"] = v.PackageSourceInfo
+ }
+ if v.PackageSummary != "" {
+ pkg["summary"] = v.PackageSummary
+ }
+ if v.PackageVersion != "" {
+ pkg["versionInfo"] = v.PackageVersion
+ }
+ if v.PackageFileName != "" {
+ pkg["packageFileName"] = v.PackageFileName
+ }
+
+ //parse package originator
+ if v.PackageOriginatorPerson != "" {
+ pkg["originator"] = fmt.Sprintf("Person: %s", v.PackageOriginatorPerson)
+ }
+ if v.PackageOriginatorOrganization != "" {
+ pkg["originator"] = fmt.Sprintf("Organization: %s", v.PackageOriginatorOrganization)
+ }
+ if v.PackageOriginatorNOASSERTION {
+ pkg["originator"] = "NOASSERTION"
+ }
+
+ //parse package verification code
+ if v.PackageVerificationCode != "" {
+ verification := make(map[string]interface{})
+ verification["packageVerificationCodeExcludedFiles"] = []string{v.PackageVerificationCodeExcludedFile}
+ verification["packageVerificationCodeValue"] = v.PackageVerificationCode
+ pkg["packageVerificationCode"] = verification
+ }
+
+ //parse package supplier
+ if v.PackageSupplierPerson != "" {
+ pkg["supplier"] = fmt.Sprintf("Person: %s", v.PackageSupplierPerson)
+ }
+ if v.PackageSupplierOrganization != "" {
+ pkg["supplier"] = fmt.Sprintf("Organization: %s", v.PackageSupplierOrganization)
+ }
+ if v.PackageSupplierNOASSERTION {
+ pkg["supplier"] = "NOASSERTION"
+ }
+
+ packages = append(packages, pkg)
+ }
+ packagejson, _ := json.Marshal(packages)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "packages", packagejson)
+
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_relationships.go b/jsonsaver/saver2v2/save_relationships.go
new file mode 100644
index 00000000..8bfe9d77
--- /dev/null
+++ b/jsonsaver/saver2v2/save_relationships.go
@@ -0,0 +1,29 @@
+// 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"
+)
+
+func renderRelationships2_2(relationships []*spdx.Relationship2_2, buf *bytes.Buffer) error {
+
+ var rels []interface{}
+ for _, v := range relationships {
+ rel := make(map[string]interface{})
+ rel["spdxElementId"] = spdx.RenderDocElementID(v.RefA)
+ rel["relatedSpdxElement"] = spdx.RenderDocElementID(v.RefB)
+ rel["relationshipType"] = v.Relationship
+ if v.RelationshipComment != "" {
+ rel["comment"] = v.RelationshipComment
+ }
+ rels = append(rels, rel)
+ }
+ relsjson, _ := json.Marshal(rels)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "relationships", relsjson)
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_reviews.go b/jsonsaver/saver2v2/save_reviews.go
new file mode 100644
index 00000000..8ec55410
--- /dev/null
+++ b/jsonsaver/saver2v2/save_reviews.go
@@ -0,0 +1,29 @@
+// 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"
+)
+
+func renderReviews2_2(reviews []*spdx.Review2_2, buf *bytes.Buffer) error {
+
+ var review []interface{}
+ for _, v := range reviews {
+ rev := make(map[string]interface{})
+ rev["reviewDate"] = v.ReviewDate
+ rev["reviewer"] = fmt.Sprintf("%s: %s", v.ReviewerType, v.Reviewer)
+ if v.ReviewComment != "" {
+ rev["comment"] = v.ReviewComment
+ }
+ review = append(review, rev)
+ }
+ reviewjson, _ := json.Marshal(review)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "revieweds", reviewjson)
+
+ return nil
+}
diff --git a/jsonsaver/saver2v2/save_snippets.go b/jsonsaver/saver2v2/save_snippets.go
new file mode 100644
index 00000000..c3826a0e
--- /dev/null
+++ b/jsonsaver/saver2v2/save_snippets.go
@@ -0,0 +1,75 @@
+// 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"
+)
+
+func renderSnippets2_2(doc *spdx.Document2_2, buf *bytes.Buffer) error {
+
+ var snippets []interface{}
+ for _, value := range doc.UnpackagedFiles {
+ snippet := make(map[string]interface{})
+ for _, v := range value.Snippets {
+ snippet["SPDXID"] = spdx.RenderElementID(v.SnippetSPDXIdentifier)
+ if v.SnippetComment != "" {
+ snippet["comment"] = v.SnippetComment
+ }
+ if v.SnippetCopyrightText != "" {
+ snippet["copyrightText"] = v.SnippetCopyrightText
+ }
+ if v.SnippetLicenseComments != "" {
+ snippet["licenseComments"] = v.SnippetLicenseComments
+ }
+ if v.SnippetLicenseConcluded != "" {
+ snippet["licenseConcluded"] = v.SnippetLicenseConcluded
+ }
+ if v.LicenseInfoInSnippet != nil {
+ snippet["licenseInfoInSnippets"] = v.LicenseInfoInSnippet
+ }
+ if v.SnippetName != "" {
+ snippet["name"] = v.SnippetName
+ }
+ if v.SnippetName != "" {
+ snippet["snippetFromFile"] = spdx.RenderDocElementID(v.SnippetFromFileSPDXIdentifier)
+ }
+ if v.SnippetAttributionTexts != nil {
+ snippet["attributionTexts"] = v.SnippetAttributionTexts
+ }
+
+ // parse snippet ranges
+ var ranges []interface{}
+ byterange := map[string]interface{}{
+ "endPointer": map[string]interface{}{
+ "offset": v.SnippetByteRangeEnd,
+ "reference": spdx.RenderDocElementID(v.SnippetFromFileSPDXIdentifier),
+ },
+ "startPointer": map[string]interface{}{
+ "offset": v.SnippetByteRangeStart,
+ "reference": spdx.RenderDocElementID(v.SnippetFromFileSPDXIdentifier),
+ },
+ }
+ linerange := map[string]interface{}{
+ "endPointer": map[string]interface{}{
+ "lineNumber": v.SnippetLineRangeEnd,
+ "reference": spdx.RenderDocElementID(v.SnippetFromFileSPDXIdentifier),
+ },
+ "startPointer": map[string]interface{}{
+ "lineNumber": v.SnippetLineRangeStart,
+ "reference": spdx.RenderDocElementID(v.SnippetFromFileSPDXIdentifier),
+ },
+ }
+ ranges = append(ranges, byterange, linerange)
+ snippet["ranges"] = ranges
+ snippets = append(snippets, snippet)
+ }
+ }
+ snippetjson, _ := json.Marshal(snippets)
+ fmt.Fprintf(buf, "\"%s\": %s ,", "snippets", snippetjson)
+ return nil
+}
diff --git a/spdxlib/described_elements.go b/spdxlib/described_elements.go
index 6158f88f..e8373dac 100644
--- a/spdxlib/described_elements.go
+++ b/spdxlib/described_elements.go
@@ -5,8 +5,6 @@ package spdxlib
import (
"fmt"
- "sort"
-
"github.com/spdx/tools-golang/spdx"
)
@@ -14,8 +12,7 @@ import (
// in this Document that it "describes," according to SPDX rules:
// - If the document has only one Package, its ID is returned.
// - If the document has 2+ Packages, it returns the IDs of those that have
-// a DESCRIBES (or DESCRIBED_BY) relationship to this DOCUMENT. If no
-// -
+// a DESCRIBES (or DESCRIBED_BY) relationship to this DOCUMENT.
func GetDescribedPackageIDs2_1(doc *spdx.Document2_1) ([]spdx.ElementID, error) {
// if nil Packages map or zero packages in it, return empty slice
if doc.Packages == nil {
@@ -37,40 +34,28 @@ func GetDescribedPackageIDs2_1(doc *spdx.Document2_1) ([]spdx.ElementID, error)
if doc.Relationships == nil {
return nil, fmt.Errorf("multiple Packages in Document but Relationships slice is nil")
}
- // collect IDs as strings so we can sort them easily
- eIDStrs := []string{}
- for _, rln := range doc.Relationships {
- if rln.Relationship == "DESCRIBES" && rln.RefA == spdx.MakeDocElementID("", "DOCUMENT") {
- // confirm RefB is actually a package in this document
- if _, ok := doc.Packages[rln.RefB.ElementRefID]; !ok {
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok2 := doc.UnpackagedFiles[rln.RefB.ElementRefID]; !ok2 {
- return nil, fmt.Errorf("Document DESCRIBES %s but no such Package or unpackaged File", string(rln.RefB.ElementRefID))
- }
- }
- eIDStrs = append(eIDStrs, string(rln.RefB.ElementRefID))
- }
- if rln.Relationship == "DESCRIBED_BY" && rln.RefB == spdx.MakeDocElementID("", "DOCUMENT") {
- // confirm RefA is actually a package in this document
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok := doc.Packages[rln.RefA.ElementRefID]; !ok {
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok2 := doc.UnpackagedFiles[rln.RefA.ElementRefID]; !ok2 {
- return nil, fmt.Errorf("%s DESCRIBED_BY Document but no such Package or unpackaged File", string(rln.RefA.ElementRefID))
- }
- }
- eIDStrs = append(eIDStrs, string(rln.RefA.ElementRefID))
+
+ eIDs, err := FilterRelationships2_1(doc, func(relationship *spdx.Relationship2_1) *spdx.ElementID {
+ refDocument := spdx.MakeDocElementID("", "DOCUMENT")
+
+ if relationship.Relationship == "DESCRIBES" && relationship.RefA == refDocument {
+ return &relationship.RefB.ElementRefID
+ } else if relationship.Relationship == "DESCRIBED_BY" && relationship.RefB == refDocument {
+ return &relationship.RefA.ElementRefID
}
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
}
- if len(eIDStrs) == 0 {
+
+ if len(eIDs) == 0 {
return nil, fmt.Errorf("no DESCRIBES or DESCRIBED_BY relationships found for this Document")
}
- // sort them, convert back to ElementIDs and return
- sort.Strings(eIDStrs)
- eIDs := []spdx.ElementID{}
- for _, eIDStr := range eIDStrs {
- eIDs = append(eIDs, spdx.ElementID(eIDStr))
- }
+
+ eIDs = SortElementIDs(eIDs)
+
return eIDs, nil
}
@@ -78,8 +63,7 @@ func GetDescribedPackageIDs2_1(doc *spdx.Document2_1) ([]spdx.ElementID, error)
// in this Document that it "describes," according to SPDX rules:
// - If the document has only one Package, its ID is returned.
// - If the document has 2+ Packages, it returns the IDs of those that have
-// a DESCRIBES (or DESCRIBED_BY) relationship to this DOCUMENT. If no
-// -
+// a DESCRIBES (or DESCRIBED_BY) relationship to this DOCUMENT.
func GetDescribedPackageIDs2_2(doc *spdx.Document2_2) ([]spdx.ElementID, error) {
// if nil Packages map or zero packages in it, return empty slice
if doc.Packages == nil {
@@ -101,39 +85,27 @@ func GetDescribedPackageIDs2_2(doc *spdx.Document2_2) ([]spdx.ElementID, error)
if doc.Relationships == nil {
return nil, fmt.Errorf("multiple Packages in Document but Relationships slice is nil")
}
- // collect IDs as strings so we can sort them easily
- eIDStrs := []string{}
- for _, rln := range doc.Relationships {
- if rln.Relationship == "DESCRIBES" && rln.RefA == spdx.MakeDocElementID("", "DOCUMENT") {
- // confirm RefB is actually a package in this document
- if _, ok := doc.Packages[rln.RefB.ElementRefID]; !ok {
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok2 := doc.UnpackagedFiles[rln.RefB.ElementRefID]; !ok2 {
- return nil, fmt.Errorf("Document DESCRIBES %s but no such Package or unpackaged File", string(rln.RefB.ElementRefID))
- }
- }
- eIDStrs = append(eIDStrs, string(rln.RefB.ElementRefID))
- }
- if rln.Relationship == "DESCRIBED_BY" && rln.RefB == spdx.MakeDocElementID("", "DOCUMENT") {
- // confirm RefA is actually a package in this document
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok := doc.Packages[rln.RefA.ElementRefID]; !ok {
- // if it's an unpackaged file, that's valid (no error) but don't return it
- if _, ok2 := doc.UnpackagedFiles[rln.RefA.ElementRefID]; !ok2 {
- return nil, fmt.Errorf("%s DESCRIBED_BY Document but no such Package or unpackaged File", string(rln.RefA.ElementRefID))
- }
- }
- eIDStrs = append(eIDStrs, string(rln.RefA.ElementRefID))
+
+ eIDs, err := FilterRelationships2_2(doc, func(relationship *spdx.Relationship2_2) *spdx.ElementID {
+ refDocument := spdx.MakeDocElementID("", "DOCUMENT")
+
+ if relationship.Relationship == "DESCRIBES" && relationship.RefA == refDocument {
+ return &relationship.RefB.ElementRefID
+ } else if relationship.Relationship == "DESCRIBED_BY" && relationship.RefB == refDocument {
+ return &relationship.RefA.ElementRefID
}
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
}
- if len(eIDStrs) == 0 {
+
+ if len(eIDs) == 0 {
return nil, fmt.Errorf("no DESCRIBES or DESCRIBED_BY relationships found for this Document")
}
- // sort them, convert back to ElementIDs and return
- sort.Strings(eIDStrs)
- eIDs := []spdx.ElementID{}
- for _, eIDStr := range eIDStrs {
- eIDs = append(eIDs, spdx.ElementID(eIDStr))
- }
+
+ eIDs = SortElementIDs(eIDs)
+
return eIDs, nil
}
diff --git a/spdxlib/described_elements_test.go b/spdxlib/described_elements_test.go
index 4ba99da8..32fa7269 100644
--- a/spdxlib/described_elements_test.go
+++ b/spdxlib/described_elements_test.go
@@ -183,34 +183,6 @@ func Test2_1FailsToGetDescribedPackagesIfNilMap(t *testing.T) {
}
}
-func Test2_1FailsToGetDescribedPackagesIfRelationshipForNonexistantPackageID(t *testing.T) {
- // set up document and multiple packages, but no DESCRIBES relationships
- doc := &spdx.Document2_1{
- CreationInfo: &spdx.CreationInfo2_1{
- SPDXVersion: "SPDX-2.1",
- DataLicense: "CC0-1.0",
- SPDXIdentifier: spdx.ElementID("DOCUMENT"),
- },
- Packages: map[spdx.ElementID]*spdx.Package2_1{
- spdx.ElementID("p1"): &spdx.Package2_1{PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
- spdx.ElementID("p2"): &spdx.Package2_1{PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
- },
- Relationships: []*spdx.Relationship2_1{
- // different relationship
- &spdx.Relationship2_1{
- RefA: spdx.MakeDocElementID("", "DOCUMENT"),
- RefB: spdx.MakeDocElementID("", "p17"),
- Relationship: "DESCRIBES",
- },
- },
- }
-
- _, err := GetDescribedPackageIDs2_1(doc)
- if err == nil {
- t.Fatalf("expected non-nil error, got nil")
- }
-}
-
// ===== 2.2 tests =====
func Test2_2CanGetIDsOfDescribedPackages(t *testing.T) {
@@ -385,31 +357,3 @@ func Test2_2FailsToGetDescribedPackagesIfNilMap(t *testing.T) {
t.Fatalf("expected non-nil error, got nil")
}
}
-
-func Test2_2FailsToGetDescribedPackagesIfRelationshipForNonexistantPackageID(t *testing.T) {
- // set up document and multiple packages, but no DESCRIBES relationships
- doc := &spdx.Document2_2{
- CreationInfo: &spdx.CreationInfo2_2{
- SPDXVersion: "SPDX-2.2",
- DataLicense: "CC0-1.0",
- SPDXIdentifier: spdx.ElementID("DOCUMENT"),
- },
- Packages: map[spdx.ElementID]*spdx.Package2_2{
- spdx.ElementID("p1"): &spdx.Package2_2{PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
- spdx.ElementID("p2"): &spdx.Package2_2{PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
- },
- Relationships: []*spdx.Relationship2_2{
- // different relationship
- &spdx.Relationship2_2{
- RefA: spdx.MakeDocElementID("", "DOCUMENT"),
- RefB: spdx.MakeDocElementID("", "p17"),
- Relationship: "DESCRIBES",
- },
- },
- }
-
- _, err := GetDescribedPackageIDs2_2(doc)
- if err == nil {
- t.Fatalf("expected non-nil error, got nil")
- }
-}
diff --git a/spdxlib/documents.go b/spdxlib/documents.go
new file mode 100644
index 00000000..bd689e71
--- /dev/null
+++ b/spdxlib/documents.go
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+package spdxlib
+
+import (
+ "fmt"
+ "github.com/spdx/tools-golang/spdx"
+)
+
+// ValidateDocument2_1 returns an error if the Document is found to be invalid, or nil if the Document is valid.
+// Currently, this only verifies that all Element IDs mentioned in Relationships exist in the Document as either a
+// Package or an UnpackagedFile.
+func ValidateDocument2_1(doc *spdx.Document2_1) error {
+ // cache a map of valid package IDs for quick lookups
+ validElementIDs := make(map[spdx.ElementID]bool)
+ for _, docPackage := range doc.Packages {
+ validElementIDs[docPackage.PackageSPDXIdentifier] = true
+ }
+
+ for _, unpackagedFile := range doc.UnpackagedFiles {
+ validElementIDs[unpackagedFile.FileSPDXIdentifier] = true
+ }
+
+ // add the Document element ID
+ validElementIDs[spdx.MakeDocElementID("", "DOCUMENT").ElementRefID] = true
+
+ for _, relationship := range doc.Relationships {
+ if !validElementIDs[relationship.RefA.ElementRefID] {
+ return fmt.Errorf("%s used in relationship but no such package exists", string(relationship.RefA.ElementRefID))
+ }
+
+ if !validElementIDs[relationship.RefB.ElementRefID] {
+ return fmt.Errorf("%s used in relationship but no such package exists", string(relationship.RefB.ElementRefID))
+ }
+ }
+
+ return nil
+}
+
+// ValidateDocument2_2 returns an error if the Document is found to be invalid, or nil if the Document is valid.
+// Currently, this only verifies that all Element IDs mentioned in Relationships exist in the Document as either a
+// Package or an UnpackagedFile.
+func ValidateDocument2_2(doc *spdx.Document2_2) error {
+ // cache a map of package IDs for quick lookups
+ validElementIDs := make(map[spdx.ElementID]bool)
+ for _, docPackage := range doc.Packages {
+ validElementIDs[docPackage.PackageSPDXIdentifier] = true
+ }
+
+ for _, unpackagedFile := range doc.UnpackagedFiles {
+ validElementIDs[unpackagedFile.FileSPDXIdentifier] = true
+ }
+
+ // add the Document element ID
+ validElementIDs[spdx.MakeDocElementID("", "DOCUMENT").ElementRefID] = true
+
+ for _, relationship := range doc.Relationships {
+ if !validElementIDs[relationship.RefA.ElementRefID] {
+ return fmt.Errorf("%s used in relationship but no such package exists", string(relationship.RefA.ElementRefID))
+ }
+
+ if !validElementIDs[relationship.RefB.ElementRefID] {
+ return fmt.Errorf("%s used in relationship but no such package exists", string(relationship.RefB.ElementRefID))
+ }
+ }
+
+ return nil
+}
diff --git a/spdxlib/documents_test.go b/spdxlib/documents_test.go
new file mode 100644
index 00000000..60a39b9c
--- /dev/null
+++ b/spdxlib/documents_test.go
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package spdxlib
+
+import (
+ "testing"
+
+ "github.com/spdx/tools-golang/spdx"
+)
+
+// ===== 2.1 tests =====
+
+func Test2_1ValidDocumentPassesValidation(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_1{
+ CreationInfo: &spdx.CreationInfo2_1{
+ SPDXVersion: "SPDX-2.1",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_1{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ spdx.ElementID("p4"): {PackageName: "pkg4", PackageSPDXIdentifier: "p4"},
+ spdx.ElementID("p5"): {PackageName: "pkg5", PackageSPDXIdentifier: "p5"},
+ },
+ Relationships: []*spdx.Relationship2_1{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p5"),
+ Relationship: "DESCRIBES",
+ },
+ // inverse relationship -- should also get detected
+ {
+ RefA: spdx.MakeDocElementID("", "p4"),
+ RefB: spdx.MakeDocElementID("", "DOCUMENT"),
+ Relationship: "DESCRIBED_BY",
+ },
+ // different relationship
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p2"),
+ Relationship: "DEPENDS_ON",
+ },
+ },
+ }
+
+ err := ValidateDocument2_1(doc)
+ if err != nil {
+ t.Fatalf("expected nil error, got: %s", err.Error())
+ }
+}
+
+func Test2_1InvalidDocumentFailsValidation(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_1{
+ CreationInfo: &spdx.CreationInfo2_1{
+ SPDXVersion: "SPDX-2.1",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_1{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ },
+ Relationships: []*spdx.Relationship2_1{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p2"),
+ Relationship: "DESCRIBES",
+ },
+ // invalid ID p99
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p99"),
+ Relationship: "DEPENDS_ON",
+ },
+ },
+ }
+
+ err := ValidateDocument2_1(doc)
+ if err == nil {
+ t.Fatalf("expected non-nil error, got nil")
+ }
+}
+
+// ===== 2.2 tests =====
+
+func Test2_2ValidDocumentPassesValidation(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_2{
+ CreationInfo: &spdx.CreationInfo2_2{
+ SPDXVersion: "SPDX-2.2",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_2{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ spdx.ElementID("p4"): {PackageName: "pkg4", PackageSPDXIdentifier: "p4"},
+ spdx.ElementID("p5"): {PackageName: "pkg5", PackageSPDXIdentifier: "p5"},
+ },
+ Relationships: []*spdx.Relationship2_2{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p5"),
+ Relationship: "DESCRIBES",
+ },
+ // inverse relationship -- should also get detected
+ {
+ RefA: spdx.MakeDocElementID("", "p4"),
+ RefB: spdx.MakeDocElementID("", "DOCUMENT"),
+ Relationship: "DESCRIBED_BY",
+ },
+ // different relationship
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p2"),
+ Relationship: "DEPENDS_ON",
+ },
+ },
+ }
+
+ err := ValidateDocument2_2(doc)
+ if err != nil {
+ t.Fatalf("expected nil error, got: %s", err.Error())
+ }
+}
+
+func Test2_2InvalidDocumentFailsValidation(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_2{
+ CreationInfo: &spdx.CreationInfo2_2{
+ SPDXVersion: "SPDX-2.2",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_2{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ },
+ Relationships: []*spdx.Relationship2_2{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p5"),
+ Relationship: "DESCRIBES",
+ },
+ // invalid ID p99
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p99"),
+ Relationship: "DEPENDS_ON",
+ },
+ },
+ }
+
+ err := ValidateDocument2_2(doc)
+ if err == nil {
+ t.Fatalf("expected non-nil error, got nil")
+ }
+}
diff --git a/spdxlib/element_ids.go b/spdxlib/element_ids.go
new file mode 100644
index 00000000..f0c5ee00
--- /dev/null
+++ b/spdxlib/element_ids.go
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package spdxlib
+
+import (
+ "github.com/spdx/tools-golang/spdx"
+ "sort"
+)
+
+// SortElementIDs sorts and returns the given slice of ElementIDs
+func SortElementIDs(eIDs []spdx.ElementID) []spdx.ElementID {
+ sort.Slice(eIDs, func(i, j int) bool {
+ return eIDs[i] < eIDs[j]
+ })
+
+ return eIDs
+}
diff --git a/spdxlib/element_ids_test.go b/spdxlib/element_ids_test.go
new file mode 100644
index 00000000..3642e165
--- /dev/null
+++ b/spdxlib/element_ids_test.go
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package spdxlib
+
+import (
+ "github.com/spdx/tools-golang/spdx"
+ "reflect"
+ "testing"
+)
+
+func TestSortElementIDs(t *testing.T) {
+ eIDs := []spdx.ElementID{"def", "abc", "123"}
+ eIDs = SortElementIDs(eIDs)
+
+ if !reflect.DeepEqual(eIDs, []spdx.ElementID{"123", "abc", "def"}) {
+ t.Fatalf("expected sorted ElementIDs, got: %v", eIDs)
+ }
+}
diff --git a/spdxlib/relationships.go b/spdxlib/relationships.go
new file mode 100644
index 00000000..ecc5a19c
--- /dev/null
+++ b/spdxlib/relationships.go
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package spdxlib
+
+import "github.com/spdx/tools-golang/spdx"
+
+// FilterRelationships2_1 returns a slice of Element IDs returned by the given filter closure. The closure is passed
+// one relationship at a time, and it can return an ElementID or nil.
+func FilterRelationships2_1(doc *spdx.Document2_1, filter func(*spdx.Relationship2_1) *spdx.ElementID) ([]spdx.ElementID, error) {
+ elementIDs := []spdx.ElementID{}
+
+ for _, relationship := range doc.Relationships {
+ if id := filter(relationship); id != nil {
+ elementIDs = append(elementIDs, *id)
+ }
+ }
+
+ return elementIDs, nil
+}
+
+// FilterRelationships2_2 returns a slice of Element IDs returned by the given filter closure. The closure is passed
+// one relationship at a time, and it can return an ElementID or nil.
+func FilterRelationships2_2(doc *spdx.Document2_2, filter func(*spdx.Relationship2_2) *spdx.ElementID) ([]spdx.ElementID, error) {
+ elementIDs := []spdx.ElementID{}
+
+ for _, relationship := range doc.Relationships {
+ if id := filter(relationship); id != nil {
+ elementIDs = append(elementIDs, *id)
+ }
+ }
+
+ return elementIDs, nil
+}
diff --git a/spdxlib/relationships_test.go b/spdxlib/relationships_test.go
new file mode 100644
index 00000000..3c0ef240
--- /dev/null
+++ b/spdxlib/relationships_test.go
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+
+package spdxlib
+
+import (
+ "testing"
+
+ "github.com/spdx/tools-golang/spdx"
+)
+
+// ===== 2.1 tests =====
+
+func Test2_1FilterForDependencies(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_1{
+ CreationInfo: &spdx.CreationInfo2_1{
+ SPDXVersion: "SPDX-2.1",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_1{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ spdx.ElementID("p4"): {PackageName: "pkg4", PackageSPDXIdentifier: "p4"},
+ spdx.ElementID("p5"): {PackageName: "pkg5", PackageSPDXIdentifier: "p5"},
+ },
+ Relationships: []*spdx.Relationship2_1{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p5"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "p4"),
+ RefB: spdx.MakeDocElementID("", "DOCUMENT"),
+ Relationship: "DESCRIBED_BY",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p2"),
+ Relationship: "DEPENDS_ON",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "p3"),
+ RefB: spdx.MakeDocElementID("", "p4"),
+ Relationship: "DEPENDENCY_OF",
+ },
+ },
+ }
+
+ eIDs, err := FilterRelationships2_1(doc, func(relationship *spdx.Relationship2_1) *spdx.ElementID {
+ p1EID := spdx.MakeDocElementID("", "p1")
+ if relationship.Relationship == "DEPENDS_ON" && relationship.RefA == p1EID {
+ return &relationship.RefB.ElementRefID
+ } else if relationship.Relationship == "DEPENDENCY_OF" && relationship.RefB == p1EID {
+ return &relationship.RefA.ElementRefID
+ }
+
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("expected non-nil err, got: %s", err.Error())
+ }
+
+ if len(eIDs) != 1 {
+ t.Fatalf("expected 1 ElementID, got: %v", eIDs)
+ }
+
+ if eIDs[0] != spdx.MakeDocElementID("", "p2").ElementRefID {
+ t.Fatalf("received unexpected relationship: %v", eIDs[0])
+ }
+}
+
+// ===== 2.2 tests =====
+
+func Test2_2FindsDependsOnRelationships(t *testing.T) {
+ // set up document and some packages and relationships
+ doc := &spdx.Document2_2{
+ CreationInfo: &spdx.CreationInfo2_2{
+ SPDXVersion: "SPDX-2.2",
+ DataLicense: "CC0-1.0",
+ SPDXIdentifier: spdx.ElementID("DOCUMENT"),
+ },
+ Packages: map[spdx.ElementID]*spdx.Package2_2{
+ spdx.ElementID("p1"): {PackageName: "pkg1", PackageSPDXIdentifier: "p1"},
+ spdx.ElementID("p2"): {PackageName: "pkg2", PackageSPDXIdentifier: "p2"},
+ spdx.ElementID("p3"): {PackageName: "pkg3", PackageSPDXIdentifier: "p3"},
+ spdx.ElementID("p4"): {PackageName: "pkg4", PackageSPDXIdentifier: "p4"},
+ spdx.ElementID("p5"): {PackageName: "pkg5", PackageSPDXIdentifier: "p5"},
+ },
+ Relationships: []*spdx.Relationship2_2{
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p1"),
+ Relationship: "DESCRIBES",
+ },
+ {
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "p5"),
+ Relationship: "DESCRIBES",
+ },
+ // inverse relationship -- should also get detected
+ {
+ RefA: spdx.MakeDocElementID("", "p4"),
+ RefB: spdx.MakeDocElementID("", "DOCUMENT"),
+ Relationship: "DESCRIBED_BY",
+ },
+ // different relationship
+ {
+ RefA: spdx.MakeDocElementID("", "p1"),
+ RefB: spdx.MakeDocElementID("", "p2"),
+ Relationship: "DEPENDS_ON",
+ },
+ },
+ }
+
+ eIDs, err := FilterRelationships2_2(doc, func(relationship *spdx.Relationship2_2) *spdx.ElementID {
+ p1EID := spdx.MakeDocElementID("", "p1")
+ if relationship.Relationship == "DEPENDS_ON" && relationship.RefA == p1EID {
+ return &relationship.RefB.ElementRefID
+ } else if relationship.Relationship == "DEPENDENCY_OF" && relationship.RefB == p1EID {
+ return &relationship.RefA.ElementRefID
+ }
+
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("expected non-nil err, got: %s", err.Error())
+ }
+
+ if len(eIDs) != 1 {
+ t.Fatalf("expected 1 ElementID, got: %v", eIDs)
+ }
+
+ if eIDs[0] != spdx.MakeDocElementID("", "p2").ElementRefID {
+ t.Fatalf("received unexpected relationship: %v", eIDs[0])
+ }
+}
diff --git a/tvloader/parser2v1/parse_creation_info.go b/tvloader/parser2v1/parse_creation_info.go
index 05130eec..8742bf2a 100644
--- a/tvloader/parser2v1/parse_creation_info.go
+++ b/tvloader/parser2v1/parse_creation_info.go
@@ -12,7 +12,7 @@ import (
func (parser *tvParser2_1) parsePairFromCreationInfo2_1(tag string, value string) error {
// fail if not in Creation Info parser state
if parser.st != psCreationInfo2_1 {
- return fmt.Errorf("Got invalid state %v in parsePairFromCreationInfo2_1", parser.st)
+ return fmt.Errorf("got invalid state %v in parsePairFromCreationInfo2_1", parser.st)
}
// create an SPDX Creation Info data struct if we don't have one already
@@ -76,6 +76,13 @@ func (parser *tvParser2_1) parsePairFromCreationInfo2_1(tag string, value string
// tag for going on to package section
case "PackageName":
+ // error if last file does not have an identifier
+ // this may be a null case: can we ever have a "last file" in
+ // the "creation info" state? should go on to "file" state
+ // even when parsing unpackaged files.
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_1 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.st = psPackage2_1
parser.pkg = &spdx.Package2_1{
FilesAnalyzed: true,
diff --git a/tvloader/parser2v1/parse_file.go b/tvloader/parser2v1/parse_file.go
index efe31d93..73473849 100644
--- a/tvloader/parser2v1/parse_file.go
+++ b/tvloader/parser2v1/parse_file.go
@@ -18,10 +18,18 @@ func (parser *tvParser2_1) parsePairFromFile2_1(tag string, value string) error
switch tag {
// tag for creating new file section
case "FileName":
+ // check if the previous file contained a spdxId or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_1 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.file = &spdx.File2_1{}
parser.file.FileName = value
// tag for creating new package section and going back to parsing Package
case "PackageName":
+ // check if the previous file contained a spdxId or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_1 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.st = psPackage2_1
parser.file = nil
return parser.parsePairFromPackage2_1(tag, value)
diff --git a/tvloader/parser2v1/parse_file_test.go b/tvloader/parser2v1/parse_file_test.go
index 68efe2b4..9f42b555 100644
--- a/tvloader/parser2v1/parse_file_test.go
+++ b/tvloader/parser2v1/parse_file_test.go
@@ -885,4 +885,47 @@ func TestParser2_1FailsIfArtifactURIBeforeArtifactName(t *testing.T) {
}
}
+func TestParser2_1FilesWithoutSpdxIdThrowError(t *testing.T) {
+ // case 1: The previous file (packaged or unpackaged) does not contain spdxID
+ parser1 := tvParser2_1{
+ doc: &spdx.Document2_1{Packages: map[spdx.ElementID]*spdx.Package2_1{}},
+ st: psFile2_1,
+ file: &spdx.File2_1{FileName: "FileName"},
+ }
+
+ err := parser1.parsePair2_1("FileName", "f2")
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+ // case 2: Invalid file with snippet
+ // Last unpackaged file before a snippet starts
+ sid1 := spdx.ElementID("s1")
+ fileName := "f2.txt"
+ parser2 := tvParser2_1{
+ doc: &spdx.Document2_1{},
+ st: psCreationInfo2_1,
+ file: &spdx.File2_1{FileName: fileName},
+ }
+ err = parser2.parsePair2_1("SnippetSPDXID", string(sid1))
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+
+ // case 3 : Invalid File without snippets
+ // Last unpackaged file before a package starts
+ // Last file of a package and New package starts
+ parser3 := tvParser2_1{
+ doc: &spdx.Document2_1{},
+ st: psCreationInfo2_1,
+ }
+ fileName = "f3.txt"
+ err = parser3.parsePair2_1("FileName", fileName)
+ if err != nil {
+ t.Errorf("%s", err)
+ }
+ err = parser3.parsePair2_1("PackageName", "p2")
+ if err == nil {
+ t.Errorf("files withoutSpdx Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v1/parse_package.go b/tvloader/parser2v1/parse_package.go
index b653d9eb..a8671079 100644
--- a/tvloader/parser2v1/parse_package.go
+++ b/tvloader/parser2v1/parse_package.go
@@ -20,6 +20,10 @@ func (parser *tvParser2_1) parsePairFromPackage2_1(tag string, value string) err
case "PackageName":
// if package already has a name, create and go on to a new package
if parser.pkg == nil || parser.pkg.PackageName != "" {
+ // check if the previous package contained an spdxId or not
+ if parser.pkg != nil && parser.pkg.PackageSPDXIdentifier == nullSpdxElementId2_1 {
+ return fmt.Errorf("package with PackageName %s does not have SPDX identifier", parser.pkg.PackageName)
+ }
parser.pkg = &spdx.Package2_1{
FilesAnalyzed: true,
IsFilesAnalyzedTagPresent: false,
diff --git a/tvloader/parser2v1/parse_package_test.go b/tvloader/parser2v1/parse_package_test.go
index e6dc5e4a..3cda3ce4 100644
--- a/tvloader/parser2v1/parse_package_test.go
+++ b/tvloader/parser2v1/parse_package_test.go
@@ -1069,3 +1069,27 @@ func TestFailsPackageExternalRefWithInvalidFormat(t *testing.T) {
}
}
+func TestParser2_1PackageWithoutSpdxIdentifierThrowsError(t *testing.T) {
+ // More than one package, the previous package doesn't contain the SPDXID
+ pkgOldName := "p1"
+ parser := tvParser2_1{
+ doc: &spdx.Document2_1{Packages: map[spdx.ElementID]*spdx.Package2_1{}},
+ st: psPackage2_1,
+ pkg: &spdx.Package2_1{PackageName: pkgOldName},
+ }
+ pkgOld := parser.pkg
+ parser.doc.Packages["p1"] = pkgOld
+ // the Document's Packages should have this one only
+ if parser.doc.Packages["p1"] != pkgOld {
+ t.Errorf("expected package %v, got %v", pkgOld, parser.doc.Packages["p1"])
+ }
+ if len(parser.doc.Packages) != 1 {
+ t.Errorf("expected 1 package, got %d", len(parser.doc.Packages))
+ }
+
+ pkgName := "p2"
+ err := parser.parsePair2_1("PackageName", pkgName)
+ if err == nil {
+ t.Errorf("package without SPDX Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v1/parse_snippet.go b/tvloader/parser2v1/parse_snippet.go
index f7085a70..d5903833 100644
--- a/tvloader/parser2v1/parse_snippet.go
+++ b/tvloader/parser2v1/parse_snippet.go
@@ -13,6 +13,10 @@ func (parser *tvParser2_1) parsePairFromSnippet2_1(tag string, value string) err
switch tag {
// tag for creating new snippet section
case "SnippetSPDXID":
+ // check here whether the previous file contained an SPDX ID or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_1 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.snippet = &spdx.Snippet2_1{}
eID, err := extractElementID(value)
if err != nil {
diff --git a/tvloader/parser2v1/parse_snippet_test.go b/tvloader/parser2v1/parse_snippet_test.go
index a4412df3..603abc5f 100644
--- a/tvloader/parser2v1/parse_snippet_test.go
+++ b/tvloader/parser2v1/parse_snippet_test.go
@@ -587,3 +587,20 @@ func TestParser2_1FailsForInvalidSnippetLineValues(t *testing.T) {
}
}
+func TestParser2_1FilesWithoutSpdxIdThrowErrorWithSnippets(t *testing.T) {
+ // Invalid file with snippet
+ // Last unpackaged file before the snippet starts
+ // Last file of a package and new snippet starts
+ fileName := "f2.txt"
+ sid1 := spdx.ElementID("s1")
+ parser2 := tvParser2_1{
+ doc: &spdx.Document2_1{},
+ st: psCreationInfo2_1,
+ file: &spdx.File2_1{FileName: fileName},
+ }
+ err := parser2.parsePair2_1("SnippetSPDXID", string(sid1))
+ if err == nil {
+ t.Errorf("files without SPDX Identifiers getting accepted")
+ }
+
+}
diff --git a/tvloader/parser2v1/parser.go b/tvloader/parser2v1/parser.go
index 78f4685f..f4a5ae1e 100644
--- a/tvloader/parser2v1/parser.go
+++ b/tvloader/parser2v1/parser.go
@@ -20,6 +20,12 @@ func ParseTagValues(tvs []reader.TagValuePair) (*spdx.Document2_1, error) {
return nil, err
}
}
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_1 {
+ return nil, fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
+ if parser.pkg != nil && parser.pkg.PackageSPDXIdentifier == nullSpdxElementId2_1 {
+ return nil, fmt.Errorf("package with PackageName %s does not have SPDX identifier", parser.pkg.PackageName)
+ }
return parser.doc, nil
}
@@ -41,14 +47,14 @@ func (parser *tvParser2_1) parsePair2_1(tag string, value string) error {
case psReview2_1:
return parser.parsePairFromReview2_1(tag, value)
default:
- return fmt.Errorf("Parser state %v not recognized when parsing (%s, %s)", parser.st, tag, value)
+ return fmt.Errorf("parser state %v not recognized when parsing (%s, %s)", parser.st, tag, value)
}
}
func (parser *tvParser2_1) parsePairFromStart2_1(tag string, value string) error {
// fail if not in Start parser state
if parser.st != psStart2_1 {
- return fmt.Errorf("Got invalid state %v in parsePairFromStart2_1", parser.st)
+ return fmt.Errorf("got invalid state %v in parsePairFromStart2_1", parser.st)
}
// create an SPDX Document data struct if we don't have one already
diff --git a/tvloader/parser2v1/parser_test.go b/tvloader/parser2v1/parser_test.go
index 4a618286..9fe051ff 100644
--- a/tvloader/parser2v1/parser_test.go
+++ b/tvloader/parser2v1/parser_test.go
@@ -77,3 +77,33 @@ func TestParser2_1StartFailsToParseIfInInvalidState(t *testing.T) {
t.Errorf("expected non-nil error, got nil")
}
}
+
+func TestParser2_1FilesWithoutSpdxIdThrowErrorAtCompleteParse(t *testing.T) {
+ // case: checks the last file
+ // Last unpackaged file no packages in doc
+ // Last file of last package in the doc
+ tvPairs := []reader.TagValuePair{
+ {Tag: "SPDXVersion", Value: "SPDX-2.1"},
+ {Tag: "DataLicense", Value: "CC0-1.0"},
+ {Tag: "SPDXID", Value: "SPDXRef-DOCUMENT"},
+ {Tag: "FileName", Value: "f1"},
+ }
+ _, err := ParseTagValues(tvPairs)
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+}
+
+func TestParser2_1PackageWithoutSpdxIdThrowErrorAtCompleteParse(t *testing.T) {
+ // case: Checks the last package
+ tvPairs := []reader.TagValuePair{
+ {Tag: "SPDXVersion", Value: "SPDX-2.1"},
+ {Tag: "DataLicense", Value: "CC0-1.0"},
+ {Tag: "SPDXID", Value: "SPDXRef-DOCUMENT"},
+ {Tag: "PackageName", Value: "p1"},
+ }
+ _, err := ParseTagValues(tvPairs)
+ if err == nil {
+ t.Errorf("package without SPDX Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v1/types.go b/tvloader/parser2v1/types.go
index 5a738643..164f6a89 100644
--- a/tvloader/parser2v1/types.go
+++ b/tvloader/parser2v1/types.go
@@ -52,3 +52,5 @@ const (
// in review section
psReview2_1
)
+
+const nullSpdxElementId2_1 = spdx.ElementID("")
diff --git a/tvloader/parser2v2/parse_creation_info.go b/tvloader/parser2v2/parse_creation_info.go
index a3c7fbf7..c2bfe40f 100644
--- a/tvloader/parser2v2/parse_creation_info.go
+++ b/tvloader/parser2v2/parse_creation_info.go
@@ -12,7 +12,7 @@ import (
func (parser *tvParser2_2) parsePairFromCreationInfo2_2(tag string, value string) error {
// fail if not in Creation Info parser state
if parser.st != psCreationInfo2_2 {
- return fmt.Errorf("Got invalid state %v in parsePairFromCreationInfo2_2", parser.st)
+ return fmt.Errorf("got invalid state %v in parsePairFromCreationInfo2_2", parser.st)
}
// create an SPDX Creation Info data struct if we don't have one already
@@ -76,6 +76,13 @@ func (parser *tvParser2_2) parsePairFromCreationInfo2_2(tag string, value string
// tag for going on to package section
case "PackageName":
+ // error if last file does not have an identifier
+ // this may be a null case: can we ever have a "last file" in
+ // the "creation info" state? should go on to "file" state
+ // even when parsing unpackaged files.
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_2 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.st = psPackage2_2
parser.pkg = &spdx.Package2_2{
FilesAnalyzed: true,
diff --git a/tvloader/parser2v2/parse_file.go b/tvloader/parser2v2/parse_file.go
index 86886d37..27ec6a40 100644
--- a/tvloader/parser2v2/parse_file.go
+++ b/tvloader/parser2v2/parse_file.go
@@ -18,11 +18,19 @@ func (parser *tvParser2_2) parsePairFromFile2_2(tag string, value string) error
switch tag {
// tag for creating new file section
case "FileName":
+ // check if the previous file contained an spdx Id or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_2 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.file = &spdx.File2_2{}
parser.file.FileName = value
// tag for creating new package section and going back to parsing Package
case "PackageName":
parser.st = psPackage2_2
+ // check if the previous file contained an spdx Id or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_2 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.file = nil
return parser.parsePairFromPackage2_2(tag, value)
// tag for going on to snippet section
diff --git a/tvloader/parser2v2/parse_file_test.go b/tvloader/parser2v2/parse_file_test.go
index 411593fa..689a2df1 100644
--- a/tvloader/parser2v2/parse_file_test.go
+++ b/tvloader/parser2v2/parse_file_test.go
@@ -917,3 +917,48 @@ func TestParser2_2FailsIfArtifactURIBeforeArtifactName(t *testing.T) {
t.Errorf("expected non-nil error, got nil")
}
}
+
+func TestParser2_2FilesWithoutSpdxIdThrowError(t *testing.T) {
+ // case 1: The previous file (packaged or unpackaged) does not contain spdx ID
+ parser1 := tvParser2_2{
+ doc: &spdx.Document2_2{Packages: map[spdx.ElementID]*spdx.Package2_2{}},
+ st: psFile2_2,
+ file: &spdx.File2_2{FileName: "FileName"},
+ }
+
+ err := parser1.parsePair2_2("FileName", "f2")
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+
+ // case 2: Invalid file with snippet
+ // Last unpackaged file before the snippet start
+ fileName := "f2.txt"
+ sid1 := spdx.ElementID("s1")
+ parser2 := tvParser2_2{
+ doc: &spdx.Document2_2{},
+ st: psCreationInfo2_2,
+ file: &spdx.File2_2{FileName: fileName},
+ }
+ err = parser2.parsePair2_2("SnippetSPDXID", string(sid1))
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+
+ // case 3: Invalid File without snippets
+ // Last unpackaged file before the package starts
+ // Last file of a package and New package starts
+ parser3 := tvParser2_2{
+ doc: &spdx.Document2_2{},
+ st: psCreationInfo2_2,
+ }
+ fileName = "f3.txt"
+ err = parser3.parsePair2_2("FileName", fileName)
+ if err != nil {
+ t.Errorf("%s", err)
+ }
+ err = parser3.parsePair2_2("PackageName", "p2")
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v2/parse_package.go b/tvloader/parser2v2/parse_package.go
index 3f5939b0..15f7dc69 100644
--- a/tvloader/parser2v2/parse_package.go
+++ b/tvloader/parser2v2/parse_package.go
@@ -20,6 +20,10 @@ func (parser *tvParser2_2) parsePairFromPackage2_2(tag string, value string) err
case "PackageName":
// if package already has a name, create and go on to a new package
if parser.pkg == nil || parser.pkg.PackageName != "" {
+ // check if the previous package contained an spdx Id or not
+ if parser.pkg != nil && parser.pkg.PackageSPDXIdentifier == nullSpdxElementId2_2 {
+ return fmt.Errorf("package with PackageName %s does not have SPDX identifier", parser.pkg.PackageName)
+ }
parser.pkg = &spdx.Package2_2{
FilesAnalyzed: true,
IsFilesAnalyzedTagPresent: false,
diff --git a/tvloader/parser2v2/parse_package_test.go b/tvloader/parser2v2/parse_package_test.go
index 33b47842..58099314 100644
--- a/tvloader/parser2v2/parse_package_test.go
+++ b/tvloader/parser2v2/parse_package_test.go
@@ -1102,3 +1102,28 @@ func TestFailsPackageExternalRefWithInvalidFormat(t *testing.T) {
t.Errorf("expected non-nil error, got nil")
}
}
+
+func TestParser2_2PackageWithoutSpdxIdentifierThrowsError(t *testing.T) {
+ // More than one package, the previous package doesn't contain an SPDX ID
+ pkgOldName := "p1"
+ parser := tvParser2_2{
+ doc: &spdx.Document2_2{Packages: map[spdx.ElementID]*spdx.Package2_2{}},
+ st: psPackage2_2,
+ pkg: &spdx.Package2_2{PackageName: pkgOldName},
+ }
+ pkgOld := parser.pkg
+ parser.doc.Packages["p1"] = pkgOld
+ // the Document's Packages should have this one only
+ if parser.doc.Packages["p1"] != pkgOld {
+ t.Errorf("expected package %v, got %v", pkgOld, parser.doc.Packages["p1"])
+ }
+ if len(parser.doc.Packages) != 1 {
+ t.Errorf("expected 1 package, got %d", len(parser.doc.Packages))
+ }
+
+ pkgName := "p2"
+ err := parser.parsePair2_2("PackageName", pkgName)
+ if err == nil {
+ t.Errorf("package without SPDX Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v2/parse_snippet.go b/tvloader/parser2v2/parse_snippet.go
index 0d9dc3f8..7f586046 100644
--- a/tvloader/parser2v2/parse_snippet.go
+++ b/tvloader/parser2v2/parse_snippet.go
@@ -13,6 +13,10 @@ func (parser *tvParser2_2) parsePairFromSnippet2_2(tag string, value string) err
switch tag {
// tag for creating new snippet section
case "SnippetSPDXID":
+ // check here whether the file contained an SPDX ID or not
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_2 {
+ return fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
parser.snippet = &spdx.Snippet2_2{}
eID, err := extractElementID(value)
if err != nil {
diff --git a/tvloader/parser2v2/parse_snippet_test.go b/tvloader/parser2v2/parse_snippet_test.go
index 987fe2a5..d019a0c5 100644
--- a/tvloader/parser2v2/parse_snippet_test.go
+++ b/tvloader/parser2v2/parse_snippet_test.go
@@ -614,3 +614,21 @@ func TestParser2_2FailsForInvalidSnippetLineValues(t *testing.T) {
t.Errorf("expected non-nil error, got nil")
}
}
+
+func TestParser2_2FilesWithoutSpdxIdThrowErrorWithSnippets(t *testing.T) {
+ // Invalid file with snippet
+ // Last unpackaged file before the snippet starts
+ // Last file of a package and New package starts
+ fileName := "f2.txt"
+ sid1 := spdx.ElementID("s1")
+ parser2 := tvParser2_2{
+ doc: &spdx.Document2_2{},
+ st: psCreationInfo2_2,
+ file: &spdx.File2_2{FileName: fileName},
+ }
+ err := parser2.parsePair2_2("SnippetSPDXID", string(sid1))
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+
+}
diff --git a/tvloader/parser2v2/parser.go b/tvloader/parser2v2/parser.go
index e89bab12..98868741 100644
--- a/tvloader/parser2v2/parser.go
+++ b/tvloader/parser2v2/parser.go
@@ -20,7 +20,12 @@ func ParseTagValues(tvs []reader.TagValuePair) (*spdx.Document2_2, error) {
return nil, err
}
}
-
+ if parser.file != nil && parser.file.FileSPDXIdentifier == nullSpdxElementId2_2 {
+ return nil, fmt.Errorf("file with FileName %s does not have SPDX identifier", parser.file.FileName)
+ }
+ if parser.pkg != nil && parser.pkg.PackageSPDXIdentifier == nullSpdxElementId2_2 {
+ return nil, fmt.Errorf("package with PackageName %s does not have SPDX identifier", parser.pkg.PackageName)
+ }
return parser.doc, nil
}
@@ -41,14 +46,14 @@ func (parser *tvParser2_2) parsePair2_2(tag string, value string) error {
case psReview2_2:
return parser.parsePairFromReview2_2(tag, value)
default:
- return fmt.Errorf("Parser state %v not recognized when parsing (%s, %s)", parser.st, tag, value)
+ return fmt.Errorf("parser state %v not recognized when parsing (%s, %s)", parser.st, tag, value)
}
}
func (parser *tvParser2_2) parsePairFromStart2_2(tag string, value string) error {
// fail if not in Start parser state
if parser.st != psStart2_2 {
- return fmt.Errorf("Got invalid state %v in parsePairFromStart2_2", parser.st)
+ return fmt.Errorf("got invalid state %v in parsePairFromStart2_2", parser.st)
}
// create an SPDX Document data struct if we don't have one already
diff --git a/tvloader/parser2v2/parser_test.go b/tvloader/parser2v2/parser_test.go
index 7eec49cc..4cd5228f 100644
--- a/tvloader/parser2v2/parser_test.go
+++ b/tvloader/parser2v2/parser_test.go
@@ -77,3 +77,33 @@ func TestParser2_2StartFailsToParseIfInInvalidState(t *testing.T) {
t.Errorf("expected non-nil error, got nil")
}
}
+
+func TestParser2_2FilesWithoutSpdxIdThrowErrorAtCompleteParse(t *testing.T) {
+ // case: Checks the last file
+ // Last unpackaged file with no packages in doc
+ // Last file of last package in the doc
+ tvPairs := []reader.TagValuePair{
+ {Tag: "SPDXVersion", Value: "SPDX-2.2"},
+ {Tag: "DataLicense", Value: "CC0-1.0"},
+ {Tag: "SPDXID", Value: "SPDXRef-DOCUMENT"},
+ {Tag: "FileName", Value: "f1"},
+ }
+ _, err := ParseTagValues(tvPairs)
+ if err == nil {
+ t.Errorf("file without SPDX Identifier getting accepted")
+ }
+}
+
+func TestParser2_2PackageWithoutSpdxIdThrowErrorAtCompleteParse(t *testing.T) {
+ // case: Checks the last package
+ tvPairs := []reader.TagValuePair{
+ {Tag: "SPDXVersion", Value: "SPDX-2.2"},
+ {Tag: "DataLicense", Value: "CC0-1.0"},
+ {Tag: "SPDXID", Value: "SPDXRef-DOCUMENT"},
+ {Tag: "PackageName", Value: "p1"},
+ }
+ _, err := ParseTagValues(tvPairs)
+ if err == nil {
+ t.Errorf("package without SPDX Identifier getting accepted")
+ }
+}
diff --git a/tvloader/parser2v2/types.go b/tvloader/parser2v2/types.go
index 6039a1c2..1cdbcef5 100644
--- a/tvloader/parser2v2/types.go
+++ b/tvloader/parser2v2/types.go
@@ -52,3 +52,5 @@ const (
// in review section
psReview2_2
)
+
+const nullSpdxElementId2_2 = spdx.ElementID("")
diff --git a/tvsaver/saver2v1/save_file.go b/tvsaver/saver2v1/save_file.go
index a9df3ede..d22a012a 100644
--- a/tvsaver/saver2v1/save_file.go
+++ b/tvsaver/saver2v1/save_file.go
@@ -36,7 +36,7 @@ func renderFile2_1(f *spdx.File2_1, w io.Writer) error {
fmt.Fprintf(w, "LicenseInfoInFile: %s\n", s)
}
if f.LicenseComments != "" {
- fmt.Fprintf(w, "LicenseComments: %s\n", f.LicenseComments)
+ fmt.Fprintf(w, "LicenseComments: %s\n", textify(f.LicenseComments))
}
if f.FileCopyrightText != "" {
fmt.Fprintf(w, "FileCopyrightText: %s\n", textify(f.FileCopyrightText))
@@ -51,10 +51,10 @@ func renderFile2_1(f *spdx.File2_1, w io.Writer) error {
}
}
if f.FileComment != "" {
- fmt.Fprintf(w, "FileComment: %s\n", f.FileComment)
+ fmt.Fprintf(w, "FileComment: %s\n", textify(f.FileComment))
}
if f.FileNotice != "" {
- fmt.Fprintf(w, "FileNotice: %s\n", f.FileNotice)
+ fmt.Fprintf(w, "FileNotice: %s\n", textify(f.FileNotice))
}
for _, s := range f.FileContributor {
fmt.Fprintf(w, "FileContributor: %s\n", s)
diff --git a/tvsaver/saver2v1/save_file_test.go b/tvsaver/saver2v1/save_file_test.go
index 9e652b6f..9d6b09be 100644
--- a/tvsaver/saver2v1/save_file_test.go
+++ b/tvsaver/saver2v1/save_file_test.go
@@ -247,3 +247,51 @@ Copyright (c) John Doe
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_1FileWrapsCommentsAndNoticesMultiLine(t *testing.T) {
+ f := &spdx.File2_1{
+ FileName: "/tmp/whatever.txt",
+ FileSPDXIdentifier: spdx.ElementID("File123"),
+ FileChecksumSHA1: "85ed0817af83a24ad8da68c2b5094de69833983c",
+ LicenseComments: `this is a
+multi-line license comment`,
+ LicenseConcluded: "Apache-2.0",
+ LicenseInfoInFile: []string{
+ "Apache-2.0",
+ },
+ FileCopyrightText: "Copyright (c) Jane Doe",
+ FileComment: `this is a
+multi-line file comment`,
+ FileNotice: `This file may be used
+under either Apache-2.0 or Apache-1.1.`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`FileName: /tmp/whatever.txt
+SPDXID: SPDXRef-File123
+FileChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
+LicenseConcluded: Apache-2.0
+LicenseInfoInFile: Apache-2.0
+LicenseComments: this is a
+multi-line license comment
+FileCopyrightText: Copyright (c) Jane Doe
+FileComment: this is a
+multi-line file comment
+FileNotice: This file may be used
+under either Apache-2.0 or Apache-1.1.
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderFile2_1(f, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v1/save_package.go b/tvsaver/saver2v1/save_package.go
index 619fa398..9b19cfa8 100644
--- a/tvsaver/saver2v1/save_package.go
+++ b/tvsaver/saver2v1/save_package.go
@@ -55,7 +55,7 @@ func renderPackage2_1(pkg *spdx.Package2_1, w io.Writer) error {
if pkg.PackageVerificationCodeExcludedFile == "" {
fmt.Fprintf(w, "PackageVerificationCode: %s\n", pkg.PackageVerificationCode)
} else {
- fmt.Fprintf(w, "PackageVerificationCode: %s (excludes %s)\n", pkg.PackageVerificationCode, pkg.PackageVerificationCodeExcludedFile)
+ fmt.Fprintf(w, "PackageVerificationCode: %s (excludes: %s)\n", pkg.PackageVerificationCode, pkg.PackageVerificationCodeExcludedFile)
}
}
if pkg.PackageChecksumSHA1 != "" {
@@ -88,7 +88,7 @@ func renderPackage2_1(pkg *spdx.Package2_1, w io.Writer) error {
fmt.Fprintf(w, "PackageLicenseComments: %s\n", textify(pkg.PackageLicenseComments))
}
if pkg.PackageCopyrightText != "" {
- fmt.Fprintf(w, "PackageCopyrightText: %s\n", pkg.PackageCopyrightText)
+ fmt.Fprintf(w, "PackageCopyrightText: %s\n", textify(pkg.PackageCopyrightText))
}
if pkg.PackageSummary != "" {
fmt.Fprintf(w, "PackageSummary: %s\n", textify(pkg.PackageSummary))
@@ -102,7 +102,7 @@ func renderPackage2_1(pkg *spdx.Package2_1, w io.Writer) error {
for _, s := range pkg.PackageExternalReferences {
fmt.Fprintf(w, "ExternalRef: %s %s %s\n", s.Category, s.RefType, s.Locator)
if s.ExternalRefComment != "" {
- fmt.Fprintf(w, "ExternalRefComment: %s\n", s.ExternalRefComment)
+ fmt.Fprintf(w, "ExternalRefComment: %s\n", textify(s.ExternalRefComment))
}
}
diff --git a/tvsaver/saver2v1/save_package_test.go b/tvsaver/saver2v1/save_package_test.go
index fcde876a..fc6b2a67 100644
--- a/tvsaver/saver2v1/save_package_test.go
+++ b/tvsaver/saver2v1/save_package_test.go
@@ -29,7 +29,8 @@ func TestSaver2_1PackageSavesTextCombo1(t *testing.T) {
Category: "PACKAGE-MANAGER",
RefType: "npm",
Locator: "p1@0.1.0",
- // no ExternalRefComment for this one
+ ExternalRefComment: `this is a
+multi-line external ref comment`,
}
per3 := &spdx.PackageExternalReference2_1{
@@ -84,7 +85,7 @@ PackageSupplier: Organization: John Doe, Inc.
PackageOriginator: Person: John Doe
PackageDownloadLocation: http://example.com/p1/p1-0.1.0-master.tar.gz
FilesAnalyzed: true
-PackageVerificationCode: 0123456789abcdef0123456789abcdef01234567 (excludes p1-0.1.0.spdx)
+PackageVerificationCode: 0123456789abcdef0123456789abcdef01234567 (excludes: p1-0.1.0.spdx)
PackageChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
PackageChecksum: SHA256: 11b6d3ee554eedf79299905a98f9b9a04e498210b59f15094c916c91d150efcd
PackageChecksum: MD5: 624c1abb3664f4b35547e7c73864ad24
@@ -103,6 +104,8 @@ PackageComment: this is a comment comment
ExternalRef: SECURITY cpe22Type cpe:/a:john_doe_inc:p1:0.1.0
ExternalRefComment: this is an external ref comment #1
ExternalRef: PACKAGE-MANAGER npm p1@0.1.0
+ExternalRefComment: this is a
+multi-line external ref comment
ExternalRef: OTHER anything anything-without-spaces-can-go-here
`)
@@ -403,3 +406,47 @@ FileCopyrightText: Copyright (c) John Doe
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_1PackageWrapsCopyrightMultiLine(t *testing.T) {
+ pkg := &spdx.Package2_1{
+ PackageName: "p1",
+ PackageSPDXIdentifier: spdx.ElementID("p1"),
+ PackageDownloadLocation: "http://example.com/p1/p1-0.1.0-master.tar.gz",
+ FilesAnalyzed: false,
+ IsFilesAnalyzedTagPresent: true,
+ PackageLicenseConcluded: "GPL-2.0-or-later",
+ PackageLicenseInfoFromFiles: []string{
+ "Apache-1.1",
+ "Apache-2.0",
+ "GPL-2.0-or-later",
+ },
+ PackageLicenseDeclared: "Apache-2.0 OR GPL-2.0-or-later",
+ PackageCopyrightText: `Copyright (c) John Doe, Inc.
+Copyright Jane Doe`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`PackageName: p1
+SPDXID: SPDXRef-p1
+PackageDownloadLocation: http://example.com/p1/p1-0.1.0-master.tar.gz
+FilesAnalyzed: false
+PackageLicenseConcluded: GPL-2.0-or-later
+PackageLicenseDeclared: Apache-2.0 OR GPL-2.0-or-later
+PackageCopyrightText: Copyright (c) John Doe, Inc.
+Copyright Jane Doe
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderPackage2_1(pkg, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v1/save_relationship.go b/tvsaver/saver2v1/save_relationship.go
index 6bde4b3e..aea48bc3 100644
--- a/tvsaver/saver2v1/save_relationship.go
+++ b/tvsaver/saver2v1/save_relationship.go
@@ -16,7 +16,7 @@ func renderRelationship2_1(rln *spdx.Relationship2_1, w io.Writer) error {
fmt.Fprintf(w, "Relationship: %s %s %s\n", rlnAStr, rln.Relationship, rlnBStr)
}
if rln.RelationshipComment != "" {
- fmt.Fprintf(w, "RelationshipComment: %s\n", rln.RelationshipComment)
+ fmt.Fprintf(w, "RelationshipComment: %s\n", textify(rln.RelationshipComment))
}
return nil
diff --git a/tvsaver/saver2v1/save_relationship_test.go b/tvsaver/saver2v1/save_relationship_test.go
index e8635b1d..6fa03bd7 100644
--- a/tvsaver/saver2v1/save_relationship_test.go
+++ b/tvsaver/saver2v1/save_relationship_test.go
@@ -62,3 +62,33 @@ func TestSaver2_1RelationshipOmitsOptionalFieldsIfEmpty(t *testing.T) {
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_1RelationshipWrapsCommentMultiLine(t *testing.T) {
+ rln := &spdx.Relationship2_1{
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "2"),
+ Relationship: "DESCRIBES",
+ RelationshipComment: `this is a
+multi-line comment`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ // no trailing blank newline
+ want := bytes.NewBufferString(`Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-2
+RelationshipComment: this is a
+multi-line comment
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderRelationship2_1(rln, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v1/save_review.go b/tvsaver/saver2v1/save_review.go
index 8d192ba5..31939631 100644
--- a/tvsaver/saver2v1/save_review.go
+++ b/tvsaver/saver2v1/save_review.go
@@ -17,7 +17,7 @@ func renderReview2_1(rev *spdx.Review2_1, w io.Writer) error {
fmt.Fprintf(w, "ReviewDate: %s\n", rev.ReviewDate)
}
if rev.ReviewComment != "" {
- fmt.Fprintf(w, "ReviewComment: %s\n", rev.ReviewComment)
+ fmt.Fprintf(w, "ReviewComment: %s\n", textify(rev.ReviewComment))
}
fmt.Fprintf(w, "\n")
diff --git a/tvsaver/saver2v1/save_review_test.go b/tvsaver/saver2v1/save_review_test.go
index d7804670..74216815 100644
--- a/tvsaver/saver2v1/save_review_test.go
+++ b/tvsaver/saver2v1/save_review_test.go
@@ -65,3 +65,34 @@ ReviewDate: 2018-10-14T10:28:00Z
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_1ReviewWrapsMultiLine(t *testing.T) {
+ rev := &spdx.Review2_1{
+ Reviewer: "John Doe",
+ ReviewerType: "Person",
+ ReviewDate: "2018-10-14T10:28:00Z",
+ ReviewComment: `this is a
+multi-line review comment`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`Reviewer: Person: John Doe
+ReviewDate: 2018-10-14T10:28:00Z
+ReviewComment: this is a
+multi-line review comment
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderReview2_1(rev, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v2/save_file.go b/tvsaver/saver2v2/save_file.go
index 18e95b0d..ce75f313 100644
--- a/tvsaver/saver2v2/save_file.go
+++ b/tvsaver/saver2v2/save_file.go
@@ -36,7 +36,7 @@ func renderFile2_2(f *spdx.File2_2, w io.Writer) error {
fmt.Fprintf(w, "LicenseInfoInFile: %s\n", s)
}
if f.LicenseComments != "" {
- fmt.Fprintf(w, "LicenseComments: %s\n", f.LicenseComments)
+ fmt.Fprintf(w, "LicenseComments: %s\n", textify(f.LicenseComments))
}
if f.FileCopyrightText != "" {
fmt.Fprintf(w, "FileCopyrightText: %s\n", textify(f.FileCopyrightText))
@@ -51,10 +51,10 @@ func renderFile2_2(f *spdx.File2_2, w io.Writer) error {
}
}
if f.FileComment != "" {
- fmt.Fprintf(w, "FileComment: %s\n", f.FileComment)
+ fmt.Fprintf(w, "FileComment: %s\n", textify(f.FileComment))
}
if f.FileNotice != "" {
- fmt.Fprintf(w, "FileNotice: %s\n", f.FileNotice)
+ fmt.Fprintf(w, "FileNotice: %s\n", textify(f.FileNotice))
}
for _, s := range f.FileContributor {
fmt.Fprintf(w, "FileContributor: %s\n", s)
diff --git a/tvsaver/saver2v2/save_file_test.go b/tvsaver/saver2v2/save_file_test.go
index 159074d8..76ba839a 100644
--- a/tvsaver/saver2v2/save_file_test.go
+++ b/tvsaver/saver2v2/save_file_test.go
@@ -65,6 +65,8 @@ func TestSaver2_2FileSavesText(t *testing.T) {
},
FileAttributionTexts: []string{
"attributions",
+ `multi-line
+attribution`,
},
FileDependencies: []string{
"f-1.txt",
@@ -98,6 +100,8 @@ FileNotice: This file may be used under either Apache-2.0 or Apache-1.1.
FileContributor: John Doe jdoe@example.com
FileContributor: EvilCorp
FileAttributionText: attributions
+FileAttributionText: multi-line
+attribution
FileDependency: f-1.txt
FileDependency: g.txt
@@ -277,3 +281,56 @@ Copyright (c) John Doe
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_2FileWrapsCommentsAndNoticesMultiLine(t *testing.T) {
+ f := &spdx.File2_2{
+ FileName: "/tmp/whatever.txt",
+ FileSPDXIdentifier: spdx.ElementID("File123"),
+ FileChecksums: map[spdx.ChecksumAlgorithm]spdx.Checksum{
+ spdx.SHA1: spdx.Checksum{
+ Algorithm: spdx.SHA1,
+ Value: "85ed0817af83a24ad8da68c2b5094de69833983c",
+ },
+ },
+ LicenseComments: `this is a
+multi-line license comment`,
+ LicenseConcluded: "Apache-2.0",
+ LicenseInfoInFile: []string{
+ "Apache-2.0",
+ },
+ FileCopyrightText: "Copyright (c) Jane Doe",
+ FileComment: `this is a
+multi-line file comment`,
+ FileNotice: `This file may be used
+under either Apache-2.0 or Apache-1.1.`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`FileName: /tmp/whatever.txt
+SPDXID: SPDXRef-File123
+FileChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
+LicenseConcluded: Apache-2.0
+LicenseInfoInFile: Apache-2.0
+LicenseComments: this is a
+multi-line license comment
+FileCopyrightText: Copyright (c) Jane Doe
+FileComment: this is a
+multi-line file comment
+FileNotice: This file may be used
+under either Apache-2.0 or Apache-1.1.
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderFile2_2(f, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v2/save_package.go b/tvsaver/saver2v2/save_package.go
index 518da06b..4929775e 100644
--- a/tvsaver/saver2v2/save_package.go
+++ b/tvsaver/saver2v2/save_package.go
@@ -55,7 +55,7 @@ func renderPackage2_2(pkg *spdx.Package2_2, w io.Writer) error {
if pkg.PackageVerificationCodeExcludedFile == "" {
fmt.Fprintf(w, "PackageVerificationCode: %s\n", pkg.PackageVerificationCode)
} else {
- fmt.Fprintf(w, "PackageVerificationCode: %s (excludes %s)\n", pkg.PackageVerificationCode, pkg.PackageVerificationCodeExcludedFile)
+ fmt.Fprintf(w, "PackageVerificationCode: %s (excludes: %s)\n", pkg.PackageVerificationCode, pkg.PackageVerificationCodeExcludedFile)
}
}
if pkg.PackageChecksums[spdx.SHA1].Value != "" {
@@ -88,7 +88,7 @@ func renderPackage2_2(pkg *spdx.Package2_2, w io.Writer) error {
fmt.Fprintf(w, "PackageLicenseComments: %s\n", textify(pkg.PackageLicenseComments))
}
if pkg.PackageCopyrightText != "" {
- fmt.Fprintf(w, "PackageCopyrightText: %s\n", pkg.PackageCopyrightText)
+ fmt.Fprintf(w, "PackageCopyrightText: %s\n", textify(pkg.PackageCopyrightText))
}
if pkg.PackageSummary != "" {
fmt.Fprintf(w, "PackageSummary: %s\n", textify(pkg.PackageSummary))
@@ -102,7 +102,7 @@ func renderPackage2_2(pkg *spdx.Package2_2, w io.Writer) error {
for _, s := range pkg.PackageExternalReferences {
fmt.Fprintf(w, "ExternalRef: %s %s %s\n", s.Category, s.RefType, s.Locator)
if s.ExternalRefComment != "" {
- fmt.Fprintf(w, "ExternalRefComment: %s\n", s.ExternalRefComment)
+ fmt.Fprintf(w, "ExternalRefComment: %s\n", textify(s.ExternalRefComment))
}
}
for _, s := range pkg.PackageAttributionTexts {
diff --git a/tvsaver/saver2v2/save_package_test.go b/tvsaver/saver2v2/save_package_test.go
index 8221e73f..72d1de2e 100644
--- a/tvsaver/saver2v2/save_package_test.go
+++ b/tvsaver/saver2v2/save_package_test.go
@@ -29,7 +29,8 @@ func TestSaver2_2PackageSavesTextCombo1(t *testing.T) {
Category: "PACKAGE-MANAGER",
RefType: "npm",
Locator: "p1@0.1.0",
- // no ExternalRefComment for this one
+ ExternalRefComment: `this is a
+multi-line external ref comment`,
}
// NOTE, this is an entirely made up SWH persistent ID
@@ -105,7 +106,7 @@ PackageSupplier: Organization: John Doe, Inc.
PackageOriginator: Person: John Doe
PackageDownloadLocation: http://example.com/p1/p1-0.1.0-master.tar.gz
FilesAnalyzed: true
-PackageVerificationCode: 0123456789abcdef0123456789abcdef01234567 (excludes p1-0.1.0.spdx)
+PackageVerificationCode: 0123456789abcdef0123456789abcdef01234567 (excludes: p1-0.1.0.spdx)
PackageChecksum: SHA1: 85ed0817af83a24ad8da68c2b5094de69833983c
PackageChecksum: SHA256: 11b6d3ee554eedf79299905a98f9b9a04e498210b59f15094c916c91d150efcd
PackageChecksum: MD5: 624c1abb3664f4b35547e7c73864ad24
@@ -124,6 +125,8 @@ PackageComment: this is a comment comment
ExternalRef: SECURITY cpe22Type cpe:/a:john_doe_inc:p1:0.1.0
ExternalRefComment: this is an external ref comment #1
ExternalRef: PACKAGE-MANAGER npm p1@0.1.0
+ExternalRefComment: this is a
+multi-line external ref comment
ExternalRef: PERSISTENT-ID swh swh:1:cnt:94a9ed024d3859793618152ea559a168bbcbb5e2
ExternalRef: OTHER anything anything-without-spaces-can-go-here
PackageAttributionText: Include this notice in all advertising materials
@@ -471,3 +474,47 @@ FileCopyrightText: Copyright (c) John Doe
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_2PackageWrapsMultiLine(t *testing.T) {
+ pkg := &spdx.Package2_2{
+ PackageName: "p1",
+ PackageSPDXIdentifier: spdx.ElementID("p1"),
+ PackageDownloadLocation: "http://example.com/p1/p1-0.1.0-master.tar.gz",
+ FilesAnalyzed: false,
+ IsFilesAnalyzedTagPresent: true,
+ PackageLicenseConcluded: "GPL-2.0-or-later",
+ PackageLicenseInfoFromFiles: []string{
+ "Apache-1.1",
+ "Apache-2.0",
+ "GPL-2.0-or-later",
+ },
+ PackageLicenseDeclared: "Apache-2.0 OR GPL-2.0-or-later",
+ PackageCopyrightText: `Copyright (c) John Doe, Inc.
+Copyright Jane Doe`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`PackageName: p1
+SPDXID: SPDXRef-p1
+PackageDownloadLocation: http://example.com/p1/p1-0.1.0-master.tar.gz
+FilesAnalyzed: false
+PackageLicenseConcluded: GPL-2.0-or-later
+PackageLicenseDeclared: Apache-2.0 OR GPL-2.0-or-later
+PackageCopyrightText: Copyright (c) John Doe, Inc.
+Copyright Jane Doe
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderPackage2_2(pkg, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v2/save_relationship.go b/tvsaver/saver2v2/save_relationship.go
index cff5a4a2..4bd12ddb 100644
--- a/tvsaver/saver2v2/save_relationship.go
+++ b/tvsaver/saver2v2/save_relationship.go
@@ -16,7 +16,7 @@ func renderRelationship2_2(rln *spdx.Relationship2_2, w io.Writer) error {
fmt.Fprintf(w, "Relationship: %s %s %s\n", rlnAStr, rln.Relationship, rlnBStr)
}
if rln.RelationshipComment != "" {
- fmt.Fprintf(w, "RelationshipComment: %s\n", rln.RelationshipComment)
+ fmt.Fprintf(w, "RelationshipComment: %s\n", textify(rln.RelationshipComment))
}
return nil
diff --git a/tvsaver/saver2v2/save_relationship_test.go b/tvsaver/saver2v2/save_relationship_test.go
index ab981842..ebb3e378 100644
--- a/tvsaver/saver2v2/save_relationship_test.go
+++ b/tvsaver/saver2v2/save_relationship_test.go
@@ -112,3 +112,33 @@ func TestSaver2_2RelationshipCanHaveNOASSERTIONOnRight(t *testing.T) {
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_2RelationshipWrapsCommentMultiLine(t *testing.T) {
+ rln := &spdx.Relationship2_2{
+ RefA: spdx.MakeDocElementID("", "DOCUMENT"),
+ RefB: spdx.MakeDocElementID("", "2"),
+ Relationship: "DESCRIBES",
+ RelationshipComment: `this is a
+multi-line comment`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ // no trailing blank newline
+ want := bytes.NewBufferString(`Relationship: SPDXRef-DOCUMENT DESCRIBES SPDXRef-2
+RelationshipComment: this is a
+multi-line comment
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderRelationship2_2(rln, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}
diff --git a/tvsaver/saver2v2/save_review.go b/tvsaver/saver2v2/save_review.go
index 5e2da6e3..48004e4d 100644
--- a/tvsaver/saver2v2/save_review.go
+++ b/tvsaver/saver2v2/save_review.go
@@ -17,7 +17,7 @@ func renderReview2_2(rev *spdx.Review2_2, w io.Writer) error {
fmt.Fprintf(w, "ReviewDate: %s\n", rev.ReviewDate)
}
if rev.ReviewComment != "" {
- fmt.Fprintf(w, "ReviewComment: %s\n", rev.ReviewComment)
+ fmt.Fprintf(w, "ReviewComment: %s\n", textify(rev.ReviewComment))
}
fmt.Fprintf(w, "\n")
diff --git a/tvsaver/saver2v2/save_review_test.go b/tvsaver/saver2v2/save_review_test.go
index 15fa28dd..25fe469c 100644
--- a/tvsaver/saver2v2/save_review_test.go
+++ b/tvsaver/saver2v2/save_review_test.go
@@ -65,3 +65,34 @@ ReviewDate: 2018-10-14T10:28:00Z
t.Errorf("Expected %v, got %v", want.String(), got.String())
}
}
+
+func TestSaver2_2ReviewWrapsMultiLine(t *testing.T) {
+ rev := &spdx.Review2_2{
+ Reviewer: "John Doe",
+ ReviewerType: "Person",
+ ReviewDate: "2018-10-14T10:28:00Z",
+ ReviewComment: `this is a
+multi-line review comment`,
+ }
+
+ // what we want to get, as a buffer of bytes
+ want := bytes.NewBufferString(`Reviewer: Person: John Doe
+ReviewDate: 2018-10-14T10:28:00Z
+ReviewComment: this is a
+multi-line review comment
+
+`)
+
+ // render as buffer of bytes
+ var got bytes.Buffer
+ err := renderReview2_2(rev, &got)
+ if err != nil {
+ t.Errorf("Expected nil error, got %v", err)
+ }
+
+ // check that they match
+ c := bytes.Compare(want.Bytes(), got.Bytes())
+ if c != 0 {
+ t.Errorf("Expected %v, got %v", want.String(), got.String())
+ }
+}