-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWurstProjectConfig.kt
More file actions
233 lines (198 loc) · 8.43 KB
/
Copy pathWurstProjectConfig.kt
File metadata and controls
233 lines (198 loc) · 8.43 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
227
228
229
230
231
232
233
package config
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.json.JsonReadFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.cfg.MapperBuilder
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import file.*
import global.InstallationManager
import global.Log
import logging.KotlinLogging
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
/**
* Created by Frotty on 10.07.2017.
*/
object WurstProjectConfig {
private val MAPPER = JsonMapper.builder().enable(JsonReadFeature.ALLOW_TRAILING_COMMA).build()
private val schema by lazy { javaClass.classLoader.getResource("wbschema.json") }
private val log = KotlinLogging.logger {}
fun handleCreate(projectRoot: Path, gameRoot: Path?, projectConfig: WurstProjectConfigData, templateBranch: String = "master") {
try {
createProject(projectRoot, gameRoot, projectConfig, templateBranch)
} catch (e: Exception) {
if (DependencyManager.debug) {
e.printStackTrace()
}
log.error("❌ Project creation failed.")
log.info("Reason: ${e.message ?: e.javaClass.simpleName}")
log.info("Try: rerun with --debug for the full stack trace.")
ExitHandler.exit(1)
}
}
@Throws(IOException::class)
fun loadProject(buildFile: Path): WurstProjectConfigData? {
Log.println("Loading project..")
if (Files.exists(buildFile) && buildFile.fileName.toString().equals(CONFIG_FILE_NAME, ignoreCase = true)) {
val config = YamlHelper.loadProjectConfig(buildFile)
val projectRoot = buildFile.parent
if (config.projectName.isBlank()) {
val namedConfig = config.withProjectName(projectRoot?.fileName?.toString() ?: "unnamed")
saveProjectConfig(projectRoot, namedConfig)
Log.print("done\n")
return namedConfig
}
Log.print("done\n")
return config
}
return null
}
@Throws(Exception::class)
private fun createProject(projectRoot: Path, gameRoot: Path?, projectConfig: WurstProjectConfigData, templateBranch: String) {
Log.print("Creating project root..")
if (Files.exists(projectRoot) && Files.list(projectRoot).filter { !Files.isDirectory(it) }.findAny().isPresent) {
log.error("❌ Project root already exists and contains files.")
ExitHandler.exit(1)
} else {
Files.createDirectories(projectRoot)
Log.print("done\n")
Log.print("Download template..")
log.info("⏬ Downloading template..")
Download.downloadBareboneProject(templateBranch) {
extractDownload(it, projectRoot, gameRoot, projectConfig, templateBranch)
}
}
}
private fun extractDownload(it: Path, projectRoot: Path, gameRoot: Path?, projectConfig: WurstProjectConfigData, templateBranch: String) {
Log.println(" done.")
Log.print("Extracting template..")
val extractSuccess = ZipArchiveExtractor.extractArchive(it, projectRoot)
Files.delete(it)
if (extractSuccess) {
Log.print("done\n")
cleanupDownload(projectRoot, templateBranch)
normalizeGeneratedTemplate(projectRoot)
} else {
Log.print("error\n")
log.error("❌ Cannot extract template files. Close any Wurst, VSCode or Eclipse instances and try again.")
ExitHandler.exit(1)
}
setupEnvironment(projectRoot, gameRoot, projectConfig)
log.info("✔ Project generated.")
}
private fun cleanupDownload(projectRoot: Path, templateBranch: String) {
Log.print("Clean up..")
val folder = projectRoot.resolve("wurst-project-template-$templateBranch")
copyFolder(folder, projectRoot)
Files.walk(folder).sorted { a, b -> b.compareTo(a) }.forEach { p ->
try {
Files.delete(p)
} catch (e: IOException) {
}
}
}
private fun normalizeGeneratedTemplate(projectRoot: Path) {
val runArgs = projectRoot.resolve("wurst_run.args")
if (Files.exists(runArgs)) {
val normalizedArgs = Files.readString(runArgs)
.lineSequence()
.filterNot { it.trim().equals("lua", ignoreCase = true) || it.trim().equals("-lua", ignoreCase = true) }
.joinToString(System.lineSeparator())
.trimEnd() + System.lineSeparator()
Files.writeString(runArgs, normalizedArgs)
}
}
private fun setupEnvironment(projectRoot: Path, gameRoot: Path?, projectConfig: WurstProjectConfigData) {
Log.print("done\n")
setupVSCode(projectRoot, gameRoot)
saveProjectConfig(projectRoot, projectConfig)
DependencyManager.updateDependencies(projectRoot, projectConfig)
Log.print("---\n\n")
if (gameRoot == null || !Files.exists(gameRoot)) {
Log.print("Warning: Your game path has not been set.\n")
}
Log.print("Your project has been successfully created!\n" + "You can now open your project folder in VSCode.\nOpen the wurst/Hello.wurst package to continue.\n")
}
@Throws(IOException::class)
fun saveProjectConfig(projectRoot: Path, projectConfig: WurstProjectConfigData) {
val projectYaml = YamlHelper.dumpProjectConfig(projectConfig)
Files.write(projectRoot.resolve(CONFIG_FILE_NAME), projectYaml.toByteArray())
}
@Throws(IOException::class)
private fun setupVSCode(projectRoot: Path?, gamePath: Path?) {
Log.print("Updating vsconfig..")
if (projectRoot == null || !Files.exists(projectRoot)) {
throw IOException("Project root does not exist!")
}
val vsCode = projectRoot.resolve(".vscode/settings.json")
createConfigFile(vsCode)
val wbschema = projectRoot.resolve(".vscode/wbschema.json")
wbschema.let {
Files.write(it, schema!!.readBytes())
}
setConfigValues(vsCode, gamePath?.toAbsolutePath()?.toString() ?: "")
Log.print("done.\n")
}
private fun setConfigValues(vsCode: Path, gamePath: String) {
val json = modifySettingsJson(vsCode, gamePath)
Files.write(vsCode, json.toByteArray(), StandardOpenOption.TRUNCATE_EXISTING)
}
private fun createConfigFile(vsCode: Path) {
if (!Files.exists(vsCode)) {
Files.createDirectories(vsCode.parent)
Files.write(vsCode, VSCODE_MIN_CONFIG.toByteArray(), StandardOpenOption.CREATE_NEW)
}
}
private fun modifySettingsJson(vsCode: Path, gamePath: String): String {
val json = String(Files.readAllBytes(vsCode))
val absolutePath = InstallationManager.getCompilerPath()
val jsonNode = MAPPER.readTree(json) as ObjectNode
jsonNode.put("wurst.wurstJar", absolutePath)
if (isValidGamePath(gamePath)) {
jsonNode.put("wurst.wc3path", gamePath)
}
val schemaNode = MAPPER.createObjectNode()
schemaNode.put("./.vscode/wbschema.json", "/wurst.build")
jsonNode.replace("yaml.schemas", schemaNode)
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode)
}
private fun isValidGamePath(gamePath: String): Boolean {
if (gamePath.isBlank()) {
return false
}
return try {
val path = Paths.get(gamePath)
Files.exists(path) && Files.isDirectory(path)
} catch (_: Exception) {
false
}
}
fun handleUpdate(projectRoot: Path, gamePath: Path?, config: WurstProjectConfigData) {
Log.print("Updating project...\n")
try {
setupVSCode(projectRoot, gamePath)
saveProjectConfig(projectRoot, config)
DependencyManager.updateDependencies(projectRoot, config)
Log.print("Project successfully updated!\nReload vscode to apply the changed dependencies.\n")
} catch (e: Exception) {
if (DependencyManager.debug) {
e.printStackTrace()
}
log.error("❌ Project update failed.")
log.info("Reason: ${e.message ?: e.javaClass.simpleName}")
log.info("Try: rerun with --debug for the full stack trace.")
ExitHandler.exit(1)
}
}
private const val VSCODE_MIN_CONFIG =
"{\"wurst.javaOpts\": [\"-XX:+UseStringDeduplication\", \"-Xmx1G\"],\n" +
"\t\"files.associations\": {\n" +
" \"$CONFIG_FILE_NAME\": \"yaml\"\n" +
" },\n" +
"\t\"search.useIgnoreFiles\": false }"
}