github.com/azunymous/cdx@v0.0.0-20201122180449-fbb46cc4d252/vcs/gogit/increment.go (about) 1 package gogit 2 3 import ( 4 "fmt" 5 "github.com/azunymous/cdx/parse" 6 "github.com/azunymous/cdx/versioned" 7 "strconv" 8 "strings" 9 ) 10 11 // Increment increases the version number tag for a module and creates the new tag. 12 func (r *Repo) IncrementTag(module string, field versioned.Field) error { 13 tagsForHead, err := r.TagsForHead(module) 14 if err != nil { 15 return err 16 } 17 18 if len(tagsForHead) > 0 { 19 r.log.Printf("HEAD already tagged with %s, continuing", tagsForHead[0]) 20 return nil 21 } 22 23 tagsForModule, err := r.TagsForModule(module) 24 if err != nil { 25 return err 26 } 27 if len(tagsForModule) == 0 { 28 tagsForModule = []string{module + "-0.0.0"} 29 } 30 31 latest := tagsForModule[len(tagsForModule)-1] 32 n, err := increase(latest, field) 33 if err != nil { 34 return err 35 } 36 tag := module + "-" + n 37 r.log.Printf("Incrementing latest version %s -> %s", latest, tag) 38 39 revision, err := r.gitRepo.ResolveRevision("HEAD") 40 if err != nil { 41 return err 42 } 43 44 _, err = r.gitRepo.CreateTag(tag, *revision, nil) 45 return err 46 } 47 48 // increase takes a semver tag (see version regex) and bumps the given field returning the incremented X.Y.Z 49 // Note: this can take a semver tag string with a module but only returns the semantic version. 50 func increase(latest string, field versioned.Field) (string, error) { 51 v := parse.Version(latest) 52 if v == "" { 53 return "", fmt.Errorf("could not find version in tag: %s", latest) 54 } 55 56 split := strings.Split(v, ".") 57 num, err := strconv.Atoi(split[field]) 58 if err != nil { 59 return "", err 60 } 61 split[field] = strconv.Itoa(num + 1) 62 if field < versioned.Patch { 63 split[versioned.Patch] = "0" 64 } 65 if field < versioned.Minor { 66 split[versioned.Minor] = "0" 67 } 68 return strings.Join(split, "."), nil 69 }