github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/versioning/versionfile.go (about) 1 package versioning 2 3 import ( 4 "os" 5 "strings" 6 7 "github.com/pkg/errors" 8 ) 9 10 // Versionfile defines an artifact containing the version in a file, e.g. VERSION 11 type Versionfile struct { 12 path string 13 readFile func(string) ([]byte, error) 14 writeFile func(string, []byte, os.FileMode) error 15 versioningScheme string 16 } 17 18 func (v *Versionfile) init() { 19 if len(v.path) == 0 { 20 v.path = "VERSION" 21 } 22 if v.readFile == nil { 23 v.readFile = os.ReadFile 24 } 25 26 if v.writeFile == nil { 27 v.writeFile = os.WriteFile 28 } 29 } 30 31 // VersioningScheme returns the relevant versioning scheme 32 func (v *Versionfile) VersioningScheme() string { 33 if len(v.versioningScheme) == 0 { 34 return "semver2" 35 } 36 return v.versioningScheme 37 } 38 39 // GetVersion returns the current version of the artifact 40 func (v *Versionfile) GetVersion() (string, error) { 41 v.init() 42 43 content, err := v.readFile(v.path) 44 if err != nil { 45 return "", errors.Wrapf(err, "failed to read file '%v'", v.path) 46 } 47 48 return strings.TrimSpace(string(content)), nil 49 } 50 51 // SetVersion updates the version of the artifact 52 func (v *Versionfile) SetVersion(version string) error { 53 v.init() 54 55 err := v.writeFile(v.path, []byte(version), 0700) 56 if err != nil { 57 return errors.Wrapf(err, "failed to write file '%v'", v.path) 58 } 59 60 return nil 61 } 62 63 // GetCoordinates returns the coordinates 64 func (v *Versionfile) GetCoordinates() (Coordinates, error) { 65 result := Coordinates{} 66 return result, nil 67 }