github.com/jaylevin/jenkins-library@v1.230.4/pkg/versioning/inifile.go (about) 1 package versioning 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "os" 8 9 "github.com/pkg/errors" 10 "gopkg.in/ini.v1" 11 ) 12 13 // INIfile defines an artifact using a ini file for versioning 14 type INIfile struct { 15 path string 16 content *ini.File 17 versioningScheme string 18 versionSection string 19 versionField string 20 readFile func(string) ([]byte, error) 21 writeFile func(string, []byte, os.FileMode) error 22 } 23 24 func (i *INIfile) init() error { 25 if len(i.versionField) == 0 { 26 i.versionField = "version" 27 } 28 if i.readFile == nil { 29 i.readFile = ioutil.ReadFile 30 } 31 if i.writeFile == nil { 32 i.writeFile = ioutil.WriteFile 33 } 34 if i.content == nil { 35 conf, err := i.readFile(i.path) 36 if err != nil { 37 return errors.Wrapf(err, "failed to read file '%v'", i.path) 38 } 39 i.content, err = ini.Load(conf) 40 if err != nil { 41 return errors.Wrapf(err, "failed to load content from file '%v'", i.path) 42 } 43 } 44 return nil 45 } 46 47 // VersioningScheme returns the relevant versioning scheme 48 func (i *INIfile) VersioningScheme() string { 49 if len(i.versioningScheme) == 0 { 50 return "semver2" 51 } 52 return i.versioningScheme 53 } 54 55 // GetVersion returns the current version of the artifact with a ini-file-based build descriptor 56 func (i *INIfile) GetVersion() (string, error) { 57 if i.content == nil { 58 err := i.init() 59 if err != nil { 60 return "", err 61 } 62 } 63 section := i.content.Section(i.versionSection) 64 if section.HasKey(i.versionField) { 65 return section.Key(i.versionField).String(), nil 66 } 67 return "", fmt.Errorf("field '%v' not found in section '%v'", i.versionField, i.versionSection) 68 } 69 70 // SetVersion updates the version of the artifact with a ini-file-based build descriptor 71 func (i *INIfile) SetVersion(version string) error { 72 if i.content == nil { 73 err := i.init() 74 if err != nil { 75 return err 76 } 77 } 78 section := i.content.Section(i.versionSection) 79 section.Key(i.versionField).SetValue(version) 80 var buf bytes.Buffer 81 i.content.WriteTo(&buf) 82 err := i.writeFile(i.path, buf.Bytes(), 0700) 83 if err != nil { 84 return errors.Wrapf(err, "failed to write file '%v'", i.path) 85 } 86 return nil 87 } 88 89 // GetCoordinates returns the coordinates 90 func (i *INIfile) GetCoordinates() (Coordinates, error) { 91 return Coordinates{}, nil 92 }