github.com/SAP/jenkins-library@v1.362.0/pkg/versioning/jsonfile.go (about)

     1  package versioning
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/iancoleman/orderedmap"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  // JSONfile defines an artifact using a json file for versioning
    13  type JSONfile struct {
    14  	path         string
    15  	content      *orderedmap.OrderedMap
    16  	versionField string
    17  	readFile     func(string) ([]byte, error)
    18  	writeFile    func(string, []byte, os.FileMode) error
    19  }
    20  
    21  func (j *JSONfile) init() {
    22  	if len(j.versionField) == 0 {
    23  		j.versionField = "version"
    24  	}
    25  	if j.readFile == nil {
    26  		j.readFile = os.ReadFile
    27  	}
    28  
    29  	if j.writeFile == nil {
    30  		j.writeFile = os.WriteFile
    31  	}
    32  }
    33  
    34  // VersioningScheme returns the relevant versioning scheme
    35  func (j *JSONfile) VersioningScheme() string {
    36  	return "semver2"
    37  }
    38  
    39  // GetVersion returns the current version of the artifact with a JSON-based build descriptor
    40  func (j *JSONfile) GetVersion() (string, error) {
    41  	j.init()
    42  
    43  	content, err := j.readFile(j.path)
    44  	if err != nil {
    45  		return "", errors.Wrapf(err, "failed to read file '%v'", j.path)
    46  	}
    47  
    48  	err = json.Unmarshal(content, &j.content)
    49  	if err != nil {
    50  		return "", errors.Wrapf(err, "failed to read json content of file '%v'", j.content)
    51  	}
    52  
    53  	version, _ := j.content.Get(j.versionField)
    54  
    55  	return fmt.Sprint(version), nil
    56  }
    57  
    58  // SetVersion updates the version of the artifact with a JSON-based build descriptor
    59  func (j *JSONfile) SetVersion(version string) error {
    60  	j.init()
    61  
    62  	if j.content == nil {
    63  		_, err := j.GetVersion()
    64  		if err != nil {
    65  			return err
    66  		}
    67  	}
    68  	j.content.Set(j.versionField, version)
    69  
    70  	content, err := json.MarshalIndent(j.content, "", "  ")
    71  	if err != nil {
    72  		return errors.Wrapf(err, "failed to create json content for '%v'", j.path)
    73  	}
    74  	err = j.writeFile(j.path, content, 0700)
    75  	if err != nil {
    76  		return errors.Wrapf(err, "failed to write file '%v'", j.path)
    77  	}
    78  
    79  	return nil
    80  }
    81  
    82  // GetCoordinates returns the coordinates
    83  func (j *JSONfile) GetCoordinates() (Coordinates, error) {
    84  	result := Coordinates{}
    85  	projectVersion, err := j.GetVersion()
    86  	if err != nil {
    87  		return result, err
    88  	}
    89  	projectName, _ := j.content.Get("name")
    90  
    91  	result.ArtifactID = fmt.Sprint(projectName)
    92  	result.Version = projectVersion
    93  
    94  	return result, nil
    95  }