forked from Swoffa/SublimeKickAssemblerC64
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kickass_build.py
254 lines (207 loc) · 11.7 KB
/
kickass_build.py
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
import sublime, sublime_plugin
import os
import platform
import glob
import shutil
import json
# This file is based on work from:
# https://github.com/STealthy-and-haSTy/SublimeScraps/blob/master/build_enhancements/custom_build_variables.py
#
# Huge thanks to OdatNurd!!
# List of variable names we want to support
custom_var_list = [ "kickass_compile_args",
"kickass_compile_debug_additional_args",
"kickass_run_command_c64debugger",
"kickass_debug_command_c64debugger",
"kickass_run_command_x64",
"kickass_debug_command_x64",
"kickass_run_path",
"kickass_debug_path",
"kickass_jar_path",
"kickass_args",
"kickass_run_args",
"kickass_debug_args",
"kickass_startup_file_path",
"kickass_breakpoint_filename",
"kickass_compiled_filename",
"kickass_output_path",
"default_prebuild_path",
"default_postbuild_path"]
vars_to_expand_list = [
"kickass_compiled_filename",
"kickass_args",
"kickass_run_args",
"kickass_debug_args",
"kickass_compile_args",
"kickass_run_command_x64",
"kickass_debug_command_x64",
"kickass_run_command_c64debugger",
"kickass_debug_command_c64debugger",
]
class KickassBuildCommand(sublime_plugin.WindowCommand):
"""
Provide custom build variables to a build system, such as a value that needs
to be specific to a current project.
"""
def createExecDict(self, sourceDict, buildMode, settings):
global custom_var_list, vars_to_expand_list
try:
# Save path variable from expansion
tmpPath = sourceDict.pop('path', None)
# Variables to expand; start with defaults, then add ours.
variables = self.window.extract_variables()
variables.update(self.getFilenameVariables(buildMode, settings, variables))
# Create the command
kickAssCommand = KickAssCommandFactory(settings).createCommand(variables, buildMode)
sourceDict['shell_cmd'] = kickAssCommand.CommandText
# Add pre and post variables
extendedDict = kickAssCommand.updateEnvVars(sourceDict)
for custom_var in custom_var_list:
variables[custom_var] = settings.getSetting(custom_var)
# Expand variables (mutiple times to support variables in Variables)
for x in range(2):
variables_to_expand = {k: v for k, v in variables.items() if k in vars_to_expand_list}
variables = self.mergeDictionaries(variables, sublime.expand_variables (variables_to_expand, variables))
# Create arguments to return by expanding variables in the
# arguments given.
args = sublime.expand_variables (extendedDict, variables)
# Reset path to unexpanded and add path addition from settings
args['path'] = self.getPathDelimiter().join(filter(None, [settings.getSetting("kickass_path"), tmpPath]))
envSetting = settings.getSetting("kickass_env")
if envSetting:
args['env'].update(envSetting)
except Exception as ex:
sourceDict['shell_cmd'] = "echo %s" % ex
return sourceDict
return args
def getFilenameVariables(self, buildMode, settings, variables):
useStartup = 'startup' in buildMode
fileToBuild = settings.getSetting("kickass_startup_file_path") if useStartup else variables["file_base_name"]
fileToBuildPath = "%s/%s.%s" % (variables["file_path"], fileToBuild, variables["file_extension"])
buildAnnotations = self.parseAnnotations(fileToBuildPath)
fileToRunAnnotation = buildAnnotations.get("file-to-run") if buildAnnotations else None
return {
"build_file_base_name": fileToBuild,
"start_filename" : fileToRunAnnotation if fileToRunAnnotation else settings.getSetting("kickass_compiled_filename")
}
def parseAnnotations (self, filename):
with open(filename, 'r') as handle:
firstline = handle.readline().strip()
try:
return (json.loads("{%s}" % firstline[2:].strip().split("@kickass-build", 1)[1])
if firstline.startswith("//") and "@kickass-build" in firstline
else {})
except ValueError as err:
raise ValueError("Could not parse build annotations: %s" % err)
def getPathDelimiter(self):
return ";" if platform.system()=='Windows' else ":"
def emptyFolder(self, path):
for root, dirs, files in os.walk(path):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
def mergeDictionaries(self, x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z
def run(self, **kwargs):
settings = SublimeSettings(self)
if not settings.isLoaded():
errorMessage = "Settings could not be loaded, please restart Sublime Text."
sublime.error_message(errorMessage)
print(errorMessage)
return
outputFolder = settings.getSetting("kickass_output_path")
# os.makedirs() caused trouble with Python versions < 3.4.1 (see https://docs.python.org/3/library/os.html#os.makedirs);
# to avoid abortion (on UNIX-systems) here, we simply wrap the call with a try-except
# (the output-directory will be generated anyway via the output-parameter in the compile-command)
try:
os.makedirs(outputFolder, exist_ok=True)
except:
pass
if settings.getSettingAsBool("kickass_empty_bin_folder_before_build") and os.path.isdir(outputFolder):
self.emptyFolder(outputFolder)
self.window.run_command('exec', self.createExecDict(kwargs, kwargs.pop('buildmode'), settings))
class SublimeSettings():
def __init__(self, parentCommand):
# Get the project specific settings
project_data = parentCommand.window.project_data()
self.__project_settings = (project_data or {}).get('settings', {})
# Get the view specific settings
self.__view_settings = parentCommand.window.active_view().settings()
def isLoaded(self):
return self.__getSetting("kickass_output_path") != None
def getSetting(self, settingKey):
setting = self.__getSetting(settingKey)
return setting if setting else ""
def __getSetting(self, settingKey):
return self.__view_settings.get(settingKey, self.__project_settings.get(settingKey, None))
def getSettingAsBool(self, settingKey):
return self.getSetting(settingKey).lower() == "true"
class KickAssCommand():
def __init__(self, commandText, hasPreCommand, hasPostCommand, buildMode):
self.__commandText = commandText
self.__hasPreCommand = hasPreCommand
self.__hasPostCommand = hasPostCommand
self.__buildMode = buildMode
@property
def CommandText(self):
return self.__commandText
def updateEnvVars(self, sourceDict):
if not self.__hasPreCommand and not self.__hasPostCommand: return sourceDict
prePostEnvVars = {
"kickass_buildmode": self.__buildMode,
"kickass_file": "${build_file_base_name}.${file_extension}",
"kickass_file_path": "${file_path}",
"kickass_prg_file": "${file_path}/${kickass_output_path}/${kickass_compiled_filename}",
"kickass_bin_folder": "${file_path}/${kickass_output_path}",
}
sourceDict.get('env').update(prePostEnvVars)
return sourceDict
class KickAssCommandFactory():
def __init__(self, settings):
self.__settings = settings
def createCommand(self, variables, buildMode):
return self.createMakeCommand(variables, buildMode) if buildMode=="make" else self.createKickassCommand(variables, buildMode)
def createMakeCommand(self, variables, buildMode):
makeCommand = self.getRunScriptStatement("make", "default_make_path")
makeCommand = makeCommand if makeCommand else "echo Make file not found. Place a file named make.%s in ${file_path}%s" % (self.getExt(), " or %s." % (self.__settings.getSetting("default_make_path")) if self.__settings.getSetting("default_make_path") else ".")
return KickAssCommand(makeCommand, True, False, buildMode)
def createKickassCommand(self, variables, buildMode):
javaCommand = "java -cp \"${kickass_jar_path}\"" if self.__settings.getSetting("kickass_jar_path") else "java"
compileCommand = javaCommand+" cml.kickass.KickAssembler ${kickass_compile_args} "
compileDebugCommandAdd = "${kickass_compile_debug_additional_args}"
runCommand = "${kickass_run_command_x64}"
if "c64debugger" in self.__settings.getSetting("kickass_run_path").lower():
runCommand = "${kickass_run_command_c64debugger}"
debugCommand = "${kickass_debug_command_x64}"
if "c64debugger" in self.__settings.getSetting("kickass_debug_path").lower():
debugCommand = "${kickass_debug_command_c64debugger}"
useRun = 'run' in buildMode
useDebug = 'debug' in buildMode
command = " ".join([compileCommand, compileDebugCommandAdd, "&&", self.createMonCommandsStatement()]) if useDebug else compileCommand
preBuildScript = self.getRunScriptStatement("prebuild", "default_prebuild_path")
postBuildScript = self.getRunScriptStatement("postbuild", "default_postbuild_path")
if preBuildScript:
command = " ".join([preBuildScript, "&&", command])
if postBuildScript:
command = " ".join([command, "&&", postBuildScript])
if useDebug:
command = " ".join([command, "&&", debugCommand])
elif useRun:
command = " ".join([command, "&&", runCommand])
return KickAssCommand(command.strip(), preBuildScript != None, postBuildScript != None, buildMode)
def getExt(self):
return "bat" if platform.system()=='Windows' else "sh"
def getRunScriptStatement(self, scriptFilename, defaultScriptPathSetting):
defaultScriptCommand = "%s/%s.%s" % (self.__settings.getSetting(defaultScriptPathSetting), scriptFilename, self.getExt())
hasDefaultScriptCommand = glob.glob(defaultScriptCommand)
scriptCommand = "%s.%s" % (scriptFilename, self.getExt())
hasScriptCommand = glob.glob(scriptCommand)
return "%s \"%s\"" % ("call" if platform.system()=='Windows' else ".", (scriptCommand if hasScriptCommand else defaultScriptCommand)) if hasScriptCommand or hasDefaultScriptCommand else None
def createMonCommandsStatement(self):
if platform.system()=='Windows':
return "copy /Y \"${kickass_output_path}\\\\${build_file_base_name}.vs\" + \"${kickass_output_path}\\\\${kickass_breakpoint_filename}\" \"${kickass_output_path}\\\\${build_file_base_name}_MonCommands.mon\""
else:
return "[ -f \"${kickass_output_path}/${kickass_breakpoint_filename}\" ] && cat \"${kickass_output_path}/${build_file_base_name}.vs\" \"${kickass_output_path}/${kickass_breakpoint_filename}\" > \"${kickass_output_path}/${build_file_base_name}_MonCommands.mon\" || cat \"${kickass_output_path}/${build_file_base_name}.vs\" > \"${kickass_output_path}/${build_file_base_name}_MonCommands.mon\""