forked from jenkins-x-plugins/jx-release-version
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
426 lines (372 loc) · 10.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/jenkins-x/jx-release-version/adapters"
"github.com/jenkins-x/jx-release-version/domain"
"github.com/coreos/go-semver/semver"
"github.com/hashicorp/go-version"
"bufio"
"context"
"encoding/json"
"encoding/xml"
"flag"
"os/exec"
"path/filepath"
"regexp"
"sort"
)
// Version is the build version
var Version string
// GitTag is the git tag of the build
var GitTag string
// BuildDate is the date when the build was created
var BuildDate string
type Project struct {
Version string `xml:"version"`
}
type config struct {
dryrun bool
debug bool
dir string
ghOwner string
ghRepository string
samerelease bool
baseVersion string
minor bool
}
func main() {
debug := flag.Bool("debug", false, "prints debug into to console")
dir := flag.String("folder", ".", "the folder to look for files that contain a pom.xml or Makefile with the project version to bump")
owner := flag.String("gh-owner", "", "a github repository owner if not running from within a git project e.g. fabric8io")
repo := flag.String("gh-repository", "", "a git repository if not running from within a git project e.g. fabric8")
baseVersion := flag.String("base-version", "", "use this instead of Makefile, pom.xml, etc, e.g. -base-version=2.0.0-SNAPSHOT")
samerelease := flag.Bool("same-release", false, "for support old releases: for example 7.0.x and tag for new release 7.1.x already exist, with `-same-release` argument next version from 7.0.x will be returned ")
ver := flag.Bool("version", false, "prints the version")
minor := flag.Bool("minor", false, "increase minor version instead of patch")
flag.Parse()
if *ver {
printVersion()
os.Exit(0)
}
c := config{
debug: *debug,
dir: *dir,
ghOwner: *owner,
ghRepository: *repo,
samerelease: *samerelease,
baseVersion: *baseVersion,
minor: *minor,
}
if c.debug {
fmt.Println("available environment:")
for _, e := range os.Environ() {
fmt.Println(e)
}
}
gitHubClient := adapters.NewGitHubClient(c.debug)
v, err := getNewVersionFromTag(c, gitHubClient)
if err != nil {
fmt.Println("failed to get new version", err)
os.Exit(-1)
}
fmt.Printf("%s", v)
}
func printVersion() {
fmt.Printf(`Version: %s
Git Tag: %s
Build Date: %s
`, Version, GitTag, BuildDate)
}
func getVersion(c config) (string, error) {
if c.baseVersion != "" {
return c.baseVersion, nil
}
chart, err := ioutil.ReadFile(filepath.Join(c.dir, "Chart.yaml"))
if err == nil {
if c.debug {
fmt.Println("Found Chart.yaml")
}
scanner := bufio.NewScanner(strings.NewReader(string(chart)))
for scanner.Scan() {
if strings.Contains(scanner.Text(), "version") {
parts := strings.Split(scanner.Text(), ":")
v := strings.TrimSpace(parts[1])
if v != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing Chart version %v", v))
}
return v, nil
}
}
}
}
m, err := ioutil.ReadFile(filepath.Join(c.dir, "Makefile"))
if err == nil {
if c.debug {
fmt.Println("Found Makefile")
}
scanner := bufio.NewScanner(strings.NewReader(string(m)))
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "VERSION") || strings.HasPrefix(scanner.Text(), "VERSION ") || strings.HasPrefix(scanner.Text(), "VERSION:") || strings.HasPrefix(scanner.Text(), "VERSION=") {
parts := strings.Split(scanner.Text(), "=")
v := strings.TrimSpace(parts[1])
if v != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing Makefile version %v", v))
}
return v, nil
}
}
}
}
am, err := ioutil.ReadFile(filepath.Join(c.dir, "configure.ac"))
if err == nil {
if c.debug {
fmt.Println("configure.ac")
}
scanner := bufio.NewScanner(strings.NewReader(string(am)))
for scanner.Scan() {
if strings.Contains(scanner.Text(), "AC_INIT") {
re := regexp.MustCompile("AC_INIT\\s*\\(([^\\s]+),\\s*([.\\d]+(-\\w+)?).*\\)")
matched := re.FindStringSubmatch(scanner.Text())
v := strings.TrimSpace(matched[2])
if v != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing configure.ac version %v", v))
}
return v, nil
}
}
}
}
cm, err := ioutil.ReadFile(filepath.Join(c.dir, "CMakeLists.txt"))
if err == nil {
if c.debug {
fmt.Println("CMakeLists.txt")
}
scanner := bufio.NewScanner(strings.NewReader(string(cm)))
for scanner.Scan() {
if strings.Contains(scanner.Text(), " VERSION ") {
re := regexp.MustCompile("project\\s*(([^\\s]+)\\s+VERSION\\s+([.\\d]+(-\\w+)?).*)")
matched := re.FindStringSubmatch(scanner.Text())
v := strings.TrimSpace(matched[3])
if v != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing CMakeLists.txt version %v", v))
}
return v, nil
}
}
}
}
s, err := ioutil.ReadFile(c.dir + string(filepath.Separator) + "setup.py")
if err == nil {
if c.debug {
fmt.Println("Found setup.py")
}
// Regex to find the call to `setup(..., version='1.2.3', ...)`
re := regexp.MustCompile("setup\\((.|\\n)*version\\s*=\\s*'(\\d|\\.)*'([^\\)]|\\n)*\\)")
setup_call_bytes := re.Find(s)
if len(setup_call_bytes) > 0 {
// Regex to find the argument `version='1.2.3'`
version_re := regexp.MustCompile("version\\s*=\\s*'(\\d*|\\.)*'")
version := string(version_re.Find(setup_call_bytes))
parts := strings.Split(strings.Replace(version, " ", "", -1), "=")
v := strings.TrimPrefix(strings.TrimSuffix(parts[1], "'"), "'")
if v != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing Makefile version %v", v))
}
return v, nil
}
}
}
p, err := ioutil.ReadFile(filepath.Join(c.dir, "pom.xml"))
if err == nil {
if c.debug {
fmt.Println("found pom.xml")
}
var project Project
_ = xml.Unmarshal(p, &project)
if project.Version != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing version %v", project.Version))
}
return project.Version, nil
}
}
pkg, err := ioutil.ReadFile(filepath.Join(c.dir, "package.json"))
if err == nil {
if c.debug {
fmt.Println("found package.json")
}
var project Project
_ = json.Unmarshal(pkg, &project)
if project.Version != "" {
if c.debug {
fmt.Println(fmt.Sprintf("existing version %v", project.Version))
}
return project.Version, nil
}
}
return "0.0.0", errors.New("no recognised file to obtain current version from")
}
func getLatestTag(c config, gitClient domain.GitClient) (string, error) {
// Get base version from file, will fallback to 0.0.0 if not found.
baseVersion, _ := getVersion(c)
// if repo isn't provided by flags fall back to using current repo if run from a git project
var versionsRaw []string
if c.ghOwner != "" && c.ghRepository != "" {
ctx := context.Background()
tags, err := gitClient.ListTags(ctx, c.ghOwner, c.ghRepository)
if err != nil {
return "", err
}
if len(tags) == 0 {
// if no current flags exist then lets start at base version
return baseVersion, errors.New("No existing tags found")
}
// build an array of all the tags
versionsRaw = make([]string, len(tags))
for i, tag := range tags {
if c.debug {
fmt.Println(fmt.Sprintf("found remote tag %s", tag.Name))
}
versionsRaw[i] = tag.Name
}
} else {
_, err := exec.LookPath("git")
if err != nil {
return "", fmt.Errorf("error running git: %v", err)
}
cmd := exec.Command("git", "fetch", "--tags", "-v")
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Dir = c.dir
err = cmd.Run()
if err != nil {
return "", fmt.Errorf("error fetching tags: %v", err)
}
cmd = exec.Command("git", "tag")
cmd.Dir = c.dir
out, err := cmd.Output()
if err != nil {
return "", err
}
str := strings.TrimSuffix(string(out), "\n")
tags := strings.Split(str, "\n")
if len(tags) == 0 {
// if no current flags exist then lets start at base version
return baseVersion, errors.New("No existing tags found")
}
// build an array of all the tags
versionsRaw = make([]string, len(tags))
for i, tag := range tags {
if c.debug {
fmt.Println(fmt.Sprintf("found tag %s", tag))
}
tag = strings.TrimPrefix(tag, "v")
if tag != "" {
versionsRaw[i] = tag
}
}
}
// turn the array into a new collection of versions that we can sort
var versions []*version.Version
for _, raw := range versionsRaw {
// if same-release argument is set work only with versions which Major and Minor versions are the same
if c.samerelease {
same, _ := isMajorMinorTheSame(baseVersion, raw)
if same {
v, _ := version.NewVersion(raw)
if v != nil {
versions = append(versions, v)
}
}
} else {
v, _ := version.NewVersion(raw)
if v != nil {
versions = append(versions, v)
}
}
}
if len(versions) == 0 {
// if no current flags exist then lets start at base version
return baseVersion, errors.New("No existing tags found")
}
// return the latest tag
col := version.Collection(versions)
if c.debug {
fmt.Printf("version collection %v \n", col)
}
sort.Sort(col)
latest := len(versions)
if versions[latest-1] == nil {
return baseVersion, errors.New("No existing tags found")
}
return versions[latest-1].String(), nil
}
func getNewVersionFromTag(c config, gitClient domain.GitClient) (string, error) {
// get the latest github tag
tag, err := getLatestTag(c, gitClient)
if err != nil && tag == "" {
return "", err
}
sv, err := semver.NewVersion(tag)
if err != nil {
return "", err
}
if c.minor {
sv.BumpMinor()
} else {
sv.BumpPatch()
}
majorVersion := sv.Major
minorVersion := sv.Minor
patchVersion := sv.Patch
// check if major or minor version has been changed
baseVersion, err := getVersion(c)
if err != nil {
return fmt.Sprintf("%d.%d.%d", majorVersion, minorVersion, patchVersion), nil
}
// first use go-version to turn into a proper version, this handles 1.0-SNAPSHOT which semver doesn't
tmpVersion, err := version.NewVersion(baseVersion)
if err != nil {
return fmt.Sprintf("%d.%d.%d", majorVersion, minorVersion, patchVersion), nil
}
bsv, err := semver.NewVersion(tmpVersion.String())
if err != nil {
return "", err
}
baseMajorVersion := bsv.Major
baseMinorVersion := bsv.Minor
basePatchVersion := bsv.Patch
if baseMajorVersion > majorVersion ||
(baseMajorVersion == majorVersion &&
(baseMinorVersion > minorVersion) || (baseMinorVersion == minorVersion && basePatchVersion > patchVersion)) {
majorVersion = baseMajorVersion
minorVersion = baseMinorVersion
patchVersion = basePatchVersion
}
return fmt.Sprintf("%d.%d.%d", majorVersion, minorVersion, patchVersion), nil
}
func isMajorMinorTheSame(v1 string, v2 string) (bool, error) {
sv1, err1 := semver.NewVersion(v1)
if err1 != nil {
return false, err1
}
sv2, err2 := semver.NewVersion(v2)
if err2 != nil {
return false, err2
}
if sv1.Major != sv2.Major {
return false, nil
}
if sv1.Minor != sv2.Minor {
return false, nil
}
return true, nil
}