github.com/google/osv-scalibr@v0.4.1/binary/spdx/spdx.go (about) 1 // Copyright 2025 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package spdx provides utilities for writing SPDX documents to the filesystem. 16 package spdx 17 18 import ( 19 "fmt" 20 "io" 21 "os" 22 23 "github.com/spdx/tools-golang/json" 24 "github.com/spdx/tools-golang/spdx/v2/v2_3" 25 "github.com/spdx/tools-golang/tagvalue" 26 "github.com/spdx/tools-golang/yaml" 27 ) 28 29 type writeFun func(doc *v2_3.Document, w io.Writer) error 30 31 // Writer functions associated with SPDX v2.3 extensions. 32 var spdx23Writers = map[string]writeFun{ 33 "spdx23-tag-value": writeSPDX23TagValue, 34 "spdx23-json": writeSPDX23JSON, 35 "spdx23-yaml": writeSPDX23YAML, 36 } 37 38 // Write23 writes an SPDX v2.3 document into a file in the tag value format. 39 func Write23(doc *v2_3.Document, path string, format string) error { 40 writeFun, ok := spdx23Writers[format] 41 if !ok { 42 return fmt.Errorf("%s has an invalid SPDX format or not supported by SCALIBR", path) 43 } 44 45 f, err := os.Create(path) 46 if err != nil { 47 return err 48 } 49 defer f.Close() 50 if err = writeFun(doc, f); err != nil { 51 return err 52 } 53 return nil 54 } 55 56 func writeSPDX23TagValue(doc *v2_3.Document, w io.Writer) error { 57 return tagvalue.Write(doc, w) 58 } 59 60 func writeSPDX23YAML(doc *v2_3.Document, w io.Writer) error { 61 return yaml.Write(doc, w) 62 } 63 64 func writeSPDX23JSON(doc *v2_3.Document, w io.Writer) error { 65 return json.Write(doc, w, json.Indent(" ")) 66 }