This repository was archived by the owner on Apr 20, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathgit-versioner.gradle
More file actions
226 lines (187 loc) · 7.94 KB
/
git-versioner.gradle
File metadata and controls
226 lines (187 loc) · 7.94 KB
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
/*
* Copyright (C) 2016 Pascal Welsch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* DON'T USE THIS SCRIPT! It contains bugs and can't be updated (due to the fact hundreds of projects pull it directly from master).
* Please use
* - the gradle plugin https://github.com/passsy/gradle-gitVersioner-plugin or
* - the git extension CLI tool https://github.com/passsy/git-revision
*/
ext {
GitVersion version = this.generateVersionName()
gitVersion = version
gitVersionName = version.name
}
public class GitVersion {
public String name;
public int version = 0;
public String branchName;
public String shortBranch = "";
public int branchVersion = 0;
public int localChanges = 0;
public String commit;
@Override
public String toString() {
if (name == null || name.isEmpty()) {
return "${super.toString()}{" +
"name='" + name + '\'' +
", version=" + version +
", branchName='" + branchName + '\'' +
", shortBranch='" + shortBranch + '\'' +
", branchVersion=" + branchVersion +
'}';
}
return name
}
}
def GitVersion generateVersionName() {
// check if git project
def status = 'git status'.execute([], rootDir)
status.waitFor()
def isGitProject = status.exitValue()
if (isGitProject == 69) {
println("git returned with error 69\n" +
"If you are a mac user that message is telling you is that you need to open the " +
"application XCode on your Mac OS X/macOS and since it hasn’t run since the last " +
"update, you need to accept the new license EULA agreement that’s part of the " +
"updated XCode.")
}
if (isGitProject > 0) {
println("ERROR: can't generate a git version, this is not a git project")
println(" -> Not a git repository (or any of the parent directories): .git")
return new GitVersion()
}
// read ext properties
Map configuration = getPropertyOrDefault(rootProject, "gitVersioner", [:]) as Map
def String[] stableBranches = configuration.get("stableBranches") ?: []
def defaultBranch = configuration.get("defaultBranch") ?: "master"
float yearFactor = (configuration.get("yearFactor") ?: "1000").toString().toFloat()
boolean snapshotEnabled = configuration.get("snapshotEnabled") != false
boolean localChangesCountEnabled = configuration.get("localChangesCountEnabled") != false
def shortNameClosure = configuration.get("shortName")
// get information from git
def currentBranch = 'git symbolic-ref --short -q HEAD'.execute([], rootDir).text.trim()
// use a defined stable branch when on such a branch
if (stableBranches.contains(currentBranch)) {
defaultBranch = currentBranch
}
def currentCommit = 'git rev-parse HEAD'.execute([], rootDir).text.trim()
def log = "git log --pretty=format:'%at' --reverse".execute([], rootDir)
.text.trim().readLines()
long initialCommitDate = log.size() > 0 ? log.first().trim().replaceAll('\'', '').toLong() : 0
def localChangesCount = 'git diff-index HEAD'.execute([], rootDir).text.trim().readLines().
size()
boolean hasLocalChanges = localChangesCount > 0
def diffToDefault = "git rev-list $defaultBranch..".execute([], rootDir)
diffToDefault.waitFor()
if (diffToDefault.exitValue() != 0) {
diffToDefault = "git rev-list origin/$defaultBranch..".execute([], rootDir)
}
def featurelines = diffToDefault.text.trim().readLines()
def commitsInFeatureBranch = featurelines.size();
def defaultAndFeatureLines = "git rev-list $currentCommit"
.execute([], rootDir).text.trim().readLines()
// the sha1 of the latest commit in the default branch
def lastestDefaultBranchCommitSha1 = defaultAndFeatureLines.size() == 1 ?
defaultAndFeatureLines.first() : {
try {
return defaultAndFeatureLines.findAll { !featurelines.contains(it) }.first()
} catch (NoSuchElementException e) {
// no commits found
return currentCommit
}
}()
// get additional information
def defaultBranchDatesLog = "git log $lastestDefaultBranchCommitSha1 --pretty=format:'%at' -n 1"
.execute([], rootDir).text.trim().replaceAll('\'', '')
long latestCommitDate = defaultBranchDatesLog.isLong() ? defaultBranchDatesLog.toLong() :
initialCommitDate
// commit count is the first part of the version
def defautBranchCommitCount = "git rev-list $lastestDefaultBranchCommitSha1 --count"
.execute([], rootDir).text.trim()
def commitCount = defautBranchCommitCount.isInteger() ? defautBranchCommitCount.toInteger() : 0
// calculate the time part of the version. 2500 == 2 years, 6 months; 300 == 0.3 year
def long YEAR_IN_SECONDS = 60 * 60 * 24 * 365
def diff = latestCommitDate - initialCommitDate
long time = {
if (yearFactor <= 0) {
return 0;
} else {
return (diff * yearFactor / YEAR_IN_SECONDS + 0.5).intValue()
}
}();
// this is the version
def combinedVersion = commitCount + time
def snapshot = {
def result = ""
if (localChangesCountEnabled && localChangesCount > 0) {
result += "($localChangesCount)"
}
if (snapshotEnabled && hasLocalChanges) {
result += "-SNAPSHOT"
}
return result
}()
def holder = new GitVersion()
holder.version = combinedVersion
holder.branchName = currentBranch
holder.commit = currentCommit
holder.branchVersion = commitsInFeatureBranch
holder.localChanges = localChangesCount
String featureBranchCommits = commitsInFeatureBranch == 0 ? "" : commitsInFeatureBranch
if (featureBranchCommits.isEmpty()) {
// return only the version when on the default branch
holder.name = "$combinedVersion$snapshot"
return holder
}
// on feature branches, add a branch identifier and the commit count
def shortBranch = (shortNameClosure ?: {
if (currentBranch.isEmpty()) {
return "${currentCommit.subSequence(0, 7)}-"
} else {
return getTinyBranchName(currentBranch, 2)
}
})(holder)
holder.shortBranch = shortBranch
holder.name = "$combinedVersion-${shortBranch}$featureBranchCommits$snapshot"
return holder
}
def Object getPropertyOrDefault(Object root, String name, Object fallback) {
return root.hasProperty(name) ? root.property(name) : fallback
}
def String getTinyBranchName(String originalName, int length) {
String nameBase64 = originalName.bytes.encodeBase64().toString()
if (nameBase64.length() < length) {
int charPos = originalName.size() % 26 + 65
String lowerCase = Character.toChars(charPos).toString().toLowerCase()
return "".padRight(2, lowerCase)
}
def outChars = new Integer[length]
def chars = nameBase64.toCharArray()
for (int i = 0; chars.size() > i; i++) {
int c = chars[i]
int pos = i % length
if (outChars[pos] == null) {
outChars[pos] = 0
}
int next = (c as int) + outChars[pos]
outChars[pos] = next % 26
}
def result = ""
for (int i = 0; outChars.size() > i; i++) {
result += Character.toChars(outChars[i] + 65).toString().toLowerCase()
}
return result
}