-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathUtils.kt
More file actions
194 lines (164 loc) · 5.77 KB
/
Utils.kt
File metadata and controls
194 lines (164 loc) · 5.77 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
@file:JvmName("Utils")
package ftl.util
import ftl.config.FtlConstants
import ftl.json.SavedMatrix
import ftl.run.cancelMatrices
import kotlinx.coroutines.runBlocking
import java.io.InputStream
import java.io.Reader
import java.io.StringWriter
import java.io.Writer
import java.nio.file.Files
import java.nio.file.Paths
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Random
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlin.system.exitProcess
fun String.trimStartLine(): String {
return this.split("\n").drop(1).joinToString("\n")
}
fun StringWriter.println(msg: String = "") {
this.append(msg + "\n")
}
fun String.write(data: String) {
Files.write(Paths.get(this), data.toByteArray())
}
fun join(first: String, vararg more: String): String {
// Note: Paths.get(...) does not work for joining because the path separator
// will be '\' on Windows which is invalid for a URI
return listOf(first, *more)
.joinToString("/")
.replace("\\", "/")
.replace(regex = Regex("/+"), replacement = "/")
}
fun assertNotEmpty(str: String, e: String) {
if (str.isEmpty()) {
throw FlankFatalError(e)
}
}
// Match _GenerateUniqueGcsObjectName from api_lib/firebase/test/arg_validate.py
//
// Example: 2017-05-31_17:19:36.431540_hRJD
//
// https://cloud.google.com/storage/docs/naming
fun uniqueObjectName(): String {
val bucketName = StringBuilder()
val instant = Instant.now()
bucketName.append(
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss.")
.withZone(ZoneOffset.UTC)
.format(instant)
)
val nanoseconds = instant.nano.toString()
if (nanoseconds.length >= 6) {
bucketName.append(nanoseconds.substring(0, 6))
} else {
bucketName.append(nanoseconds.substring(0, nanoseconds.length - 1))
}
bucketName.append("_")
val random = Random()
// a-z: 97 - 122
// A-Z: 65 - 90
repeat(4) {
val ascii = random.nextInt(26)
var letter = (ascii + 'a'.toInt()).toChar()
if (ascii % 2 == 0) {
letter -= 32 // upcase
}
bucketName.append(letter)
}
bucketName.append("/")
return bucketName.toString()
}
private val classLoader = Thread.currentThread().contextClassLoader
private fun getResource(name: String): InputStream {
return classLoader.getResourceAsStream(name)
?: throw RuntimeException("Unable to find resource: $name")
}
// app version: flank_snapshot
fun readVersion(): String {
return readTextResource("version.txt").trim()
}
// git commit name: 5b0d23215e3bd90e5f9c1c57149320634aad8008
fun readRevision(): String {
return readTextResource("revision.txt").trim()
}
fun readTextResource(name: String): String {
return getResource(name).bufferedReader().use { it.readText() }
}
private val userHome = System.getProperty("user.home")
fun copyBinaryResource(name: String) {
val destinationPath = Paths.get(userHome, ".flank", name)
val destinationFile = destinationPath.toFile()
if (destinationFile.exists()) return
destinationPath.parent.toFile().mkdirs()
// "binaries/" folder prefix is required for Linux to find the resource.
copyAndClose(
from = getResource("binaries/$name").bufferedReader(),
to = Files.newBufferedWriter(destinationPath)
)
destinationFile.setExecutable(true)
}
fun copyAndClose(from: Reader, to: Writer) {
from.use { reader -> to.use { writer -> reader.copyTo(writer) } }
}
fun withGlobalExceptionHandling(block: () -> Int) {
try {
exitProcess(block())
} catch (t: Throwable) {
when (t) {
is FlankCommonException -> {
println("\n${t.message}")
exitProcess(1)
}
is FailedMatrix -> {
t.matrices.forEach { it.logError("failed") }
if (t.ignoreFailed) exitProcess(0)
else exitProcess(1)
}
is YmlValidationError -> exitProcess(1)
is FlankTimeoutError -> {
println("\nCanceling flank due to timeout")
runBlocking {
t.map?.run {
cancelMatrices(t.map, t.projectId)
}
}
exitProcess(1)
}
is FTLError -> {
t.matrix.logError("not finished")
exitProcess(3)
}
is FlankFatalError -> {
System.err.println(t.message)
exitProcess(2)
}
// We need to cover the case where some component in the call stack starts a non-daemon
// thread, and then throws an Error that kills the main thread. This is extra safe implementation
else -> {
// this is workaround for Bugsnag initialization bug, should be removed when resolved
// https://github.com/Flank/flank/issues/699
if (FtlConstants.useMock.not()) {
FtlConstants.bugsnag?.notify(t)
}
t.printStackTrace()
exitProcess(3)
}
}
}
}
private fun SavedMatrix.logError(message: String) {
println("Error: Matrix $message: ${this.matrixId} ${this.state} ${this.outcome} ${this.outcomeDetails} ${this.webLink}")
}
fun <R : MutableMap<String, Any>, T> mutableMapProperty(
name: String? = null,
defaultValue: () -> T
) = object : ReadWriteProperty<R, T> {
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: R, property: KProperty<*>): T = thisRef.getOrElse(name ?: property.name, defaultValue) as T
override fun setValue(thisRef: R, property: KProperty<*>, value: T) = thisRef.set(name ?: property.name, value as Any)
}