xref: /aosp_15_r20/external/spdx-tools/spdx/common/creation_info.go (revision ba677afa8f67bb56cbc794f4d0e378e0da058e16)
1// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
2
3package common
4
5import (
6	"encoding/json"
7	"fmt"
8	"strings"
9)
10
11// Creator is a wrapper around the Creator SPDX field. The SPDX field contains two values, which requires special
12// handling in order to marshal/unmarshal it to/from Go data types.
13type Creator struct {
14	Creator string
15	// CreatorType should be one of "Person", "Organization", or "Tool"
16	CreatorType string
17}
18
19// UnmarshalJSON takes an annotator in the typical one-line format and parses it into a Creator struct.
20// This function is also used when unmarshalling YAML
21func (c *Creator) UnmarshalJSON(data []byte) error {
22	str := string(data)
23	str = strings.Trim(str, "\"")
24	fields := strings.SplitN(str, ": ", 2)
25
26	if len(fields) != 2 {
27		return fmt.Errorf("failed to parse Creator '%s'", str)
28	}
29
30	c.CreatorType = fields[0]
31	c.Creator = fields[1]
32
33	return nil
34}
35
36// MarshalJSON converts the receiver into a slice of bytes representing a Creator in string form.
37// This function is also used with marshalling to YAML
38func (c Creator) MarshalJSON() ([]byte, error) {
39	if c.Creator != "" {
40		return json.Marshal(fmt.Sprintf("%s: %s", c.CreatorType, c.Creator))
41	}
42
43	return []byte{}, nil
44}
45