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
|
import os
import platform
import shutil
from enum import Enum
from typing import Callable, List, Optional, Tuple, cast
import click
import yaml
from ._manager import fileextToLanguage, languageToFileext, getSystemCommand
from ._WorkItem import WorkItem, WorkItemType, loadCodeDirectory, initializeCodeDirectory, initializeCodeDirectoryWithTemplate
from ._Runner import runCommands
from . import defaultData
from . import path as ecrpath
from .. import log, ui
from ..types import CommandList, CommandMapping, ExecutorMapping, JudgerMapping, CodeTemplateMapping
CONST_tempFileFilter: str = "tempFileFilter"
CONST_importedCommand: str = "importedCommand"
CONST_defaultShell: str = "defaultShell"
CONST_defaultIO: str = "defaultIO"
CONST_defaultTimeLimit: str = "defaultTimeLimit"
CONST_defaultEditor: str = "defaultEditor"
CONST_defaultJudger: str = "defaultJudger"
CONST_eVersion: str = "eVersion"
def hasInitialized(basepath: str)->bool:
return os.path.exists(ecrpath.getMainPath(basepath))
class WorkManagerState(Enum):
Empty: int = 0
Loaded: int = 1
LoadedFromGlobal: int = 2
LoadFailed: int = 3
class WorkManager:
def __init__(self, path: str):
self.workingDirectory: str = path
self.executorMap: ExecutorMapping = {}
self.judgerMap: JudgerMapping = {}
self.tempFileFilter: List[str] = []
self.currentFile: Optional[WorkItem] = None
self.importedCommand: CommandMapping = {}
self.defaultShell: Optional[str] = None
self.defaultIO: str = defaultData.io
self.defaultTimeLimit: int = defaultData.timeLimit
self.defaultJudger: str = defaultData.judger
self.defaultTemplate: CodeTemplateMapping = defaultData.templates
self.state: WorkManagerState = WorkManagerState.Empty
self.defaultEditor: Optional[str] = None
from . import __version__
self.eVersion: str = __version__
def getConfigPath(self) -> str:
if self.state == WorkManagerState.LoadedFromGlobal:
return ecrpath.getGlobalBasePath()
else:
return self.workingDirectory
def getWorkItem(self, name: str, isdir: bool, renew: bool = False) -> Optional[WorkItem]:
path = os.path.join(self.workingDirectory, name)
if isdir:
if renew or not os.path.isdir(path):
return WorkItem(path, name, WorkItemType.Directory)
else:
return loadCodeDirectory(path, name)
else:
return WorkItem(
self.workingDirectory, name, WorkItemType.File)
def setCurrent(self, item: str, isdir: bool) -> bool:
if item is None:
self.currentFile = None
else:
self.currentFile = self.getWorkItem(item, isdir)
return self.currentFile is not None
return True
def updateCurrent(self)->None:
newCur = None
if self.currentFile:
newCur = self.getWorkItem(
self.currentFile.name, self.currentFile.type == WorkItemType.Directory)
self.currentFile = newCur
def newCode(self, item: Optional[WorkItem] = None, template: Optional[str] = None) -> Optional[WorkItem]:
try:
if not item:
item = self.currentFile
assert item
dstPath = os.path.join(self.workingDirectory, item.name)
tempPath = None
if item.type == WorkItemType.Directory:
if os.path.isdir(dstPath):
shutil.rmtree(dstPath)
if not template:
template = self.defaultTemplate["dir"] if "dir" in self.defaultTemplate else None
if template:
tempPath = os.path.join(ecrpath.getTemplatePath(
self.getConfigPath()), f"{template}")
if tempPath:
if os.path.isdir(tempPath):
from .. import template as tp
tem, exp = tp.load(tempPath)
if exp:
log.warning(
f"Template loading failed: {tempPath}", extra=exp)
shutil.copytree(tempPath, dstPath,
ignore=tp.default_ignore)
else:
initializeCodeDirectoryWithTemplate(
self, tem, tempPath, dstPath)
else:
log.warning(
f"Template directory not found: {tempPath}")
os.mkdir(dstPath)
initializeCodeDirectory(dstPath)
else:
os.mkdir(dstPath)
initializeCodeDirectory(dstPath)
else:
ext = ecrpath.getFileExt(item.name)
lang = fileextToLanguage[ext] if ext in fileextToLanguage else None
tempPath = None
if lang:
if not template:
template = self.defaultTemplate[lang] if lang in self.defaultTemplate else None
if template:
tempPath = os.path.join(ecrpath.getTemplatePath(
self.getConfigPath()), f"{template}.{languageToFileext[lang]}")
if tempPath:
if os.path.isfile(tempPath):
shutil.copyfile(tempPath, dstPath)
else:
log.warning(f"Template file not found: {tempPath}")
open(dstPath, "w").close()
else:
open(dstPath, "w").close()
return item
except:
log.errorWithException(
f"Create workitem({item.type if item else None}) failed: {item.name if item else None}")
return None
def edit(self, item: Optional[WorkItem] = None)->bool:
try:
if not item:
item = self.currentFile
titem: WorkItem = cast(WorkItem, item)
if titem.type == WorkItemType.File:
click.edit(filename=titem.name, editor=self.defaultEditor)
return True
except:
log.errorWithException(
f"Edit workitem({titem.type}) failed: {titem.name}")
return False
def clean(self, rmHandler: Optional[Callable[[str], None]] = None)->None:
for file in os.listdir(self.workingDirectory):
for pat in self.tempFileFilter:
try:
if pat == ecrpath.getFileExt(os.path.split(file)[-1]):
os.remove(os.path.join(self.workingDirectory, file))
if rmHandler:
rmHandler(file)
break
except:
log.warning(f"Clean failed: {pat}", exc_info=True)
def execute(self, io: Optional[str] = None, item: Optional[WorkItem] = None)->bool:
if not io:
io = self.defaultIO
if not item:
item = self.currentFile
titem: WorkItem = cast(WorkItem, item)
cmds: Optional[CommandList] = None
console = ui.getConsole()
if titem.type == WorkItemType.File:
file = titem.name
fileNameWithoutExt, fileext = cast(
Tuple[str, str], os.path.splitext(file))
ext = fileext[1:]
lang = fileextToLanguage[ext] if ext in fileextToLanguage else None
cmds = self.executorMap[lang] if lang else []
formats = {
defaultData.CMDVAR_FileName: file,
defaultData.CMDVAR_FileNameWithoutExt: fileNameWithoutExt,
}
console.info(f"Running {file}")
return runCommands(io=io, commands=cmds, variables=formats, wdir=self.workingDirectory,
getSystemCommand=lambda p: getSystemCommand(
p, self),
inputFile=ecrpath.getFileInputPath(
self.getConfigPath()),
outputFile=ecrpath.getFileOutputPath(
self.getConfigPath()),
defaultTimeLimit=self.defaultTimeLimit)
else: # directory
cmds = titem.run
formats = {
}
console.info(f"Running {titem.name}")
if cmds:
return runCommands(io=io, commands=cmds, variables=formats, wdir=titem.path,
getSystemCommand=lambda p: getSystemCommand(
p, self),
inputFile=ecrpath.getFileInputPath(
self.getConfigPath()),
outputFile=ecrpath.getFileOutputPath(
self.getConfigPath()),
defaultTimeLimit=self.defaultTimeLimit)
else:
return True
return False
def judge(self, item: Optional[WorkItem] = None,
judger: Optional[str] = None) -> bool:
if not item:
item = self.currentFile
if not judger:
judger = self.defaultJudger
console = ui.getConsole()
titem: WorkItem = cast(WorkItem, item)
cmds: Optional[CommandList] = None
if titem.type == WorkItemType.File:
cmds = self.judgerMap[judger]
formats = {
defaultData.CMDVAR_JudgerDir: ecrpath.getJudgerPath(self.getConfigPath()),
defaultData.CMDVAR_ExpectFile: ecrpath.getFileStdPath(self.getConfigPath()),
defaultData.CMDVAR_RealFile: ecrpath.getFileOutputPath(self.getConfigPath()),
}
console.info(f"Judging {titem.name}")
return runCommands(io=defaultData.CIO_SISO, commands=cmds, variables=formats, wdir=self.workingDirectory,
getSystemCommand=lambda p: getSystemCommand(
p, self),
inputFile=ecrpath.getFileInputPath(
self.getConfigPath()),
outputFile=ecrpath.getFileOutputPath(
self.getConfigPath()),
defaultTimeLimit=self.defaultTimeLimit)
else: # directory
cmds = titem.test
formats = {
defaultData.CMDVAR_JudgerDir: ecrpath.getJudgerPath(self.getConfigPath()),
}
console.info(f"Judging {titem.name}")
if cmds:
return runCommands(io=defaultData.CIO_SISO, commands=cmds, variables=formats, wdir=titem.path,
getSystemCommand=lambda p: getSystemCommand(
p, self),
inputFile=ecrpath.getFileInputPath(
self.getConfigPath()),
outputFile=ecrpath.getFileOutputPath(
self.getConfigPath()),
defaultTimeLimit=self.defaultTimeLimit)
else:
return True
def loadFrom(basepath: str) -> Tuple[Optional[WorkManager], Optional[Exception]]:
if not hasInitialized(basepath):
return None, None
ret = WorkManager(basepath)
exp = None
try:
with open(ecrpath.getExecutorPath(basepath), "r", encoding='utf-8') as f:
ret.executorMap = yaml.load(f.read())
with open(ecrpath.getJudgerConfigPath(basepath), "r", encoding='utf-8') as f:
ret.judgerMap = yaml.load(f.read())
with open(ecrpath.getTemplateConfigPath(basepath), "r", encoding='utf-8') as f:
ret.defaultTemplate = yaml.load(f.read())
with open(ecrpath.getConfigPath(basepath), "r", encoding='utf-8') as f:
config = yaml.load(f.read())
ret.tempFileFilter = config[CONST_tempFileFilter]
ret.importedCommand = config[CONST_importedCommand]
ret.defaultShell = config[CONST_defaultShell]
ret.defaultIO = config[CONST_defaultIO]
ret.defaultEditor = config[CONST_defaultEditor]
ret.defaultJudger = config[CONST_defaultJudger]
ret.eVersion = config[CONST_eVersion]
ret.state = WorkManagerState.Loaded
except Exception as e:
log.errorWithException(f"Loading ecr data failed from {basepath}")
ret.state = WorkManagerState.LoadFailed
exp = e
return ret, exp
def load(basepath: str) -> Tuple[Optional[WorkManager], Optional[Exception]]:
if hasInitialized(basepath):
ret, exp = loadFrom(basepath)
else:
log.info("Load from global data")
ret, exp = loadFrom(ecrpath.getGlobalBasePath())
if ret:
if ret.state == WorkManagerState.Loaded:
ret.state = WorkManagerState.LoadedFromGlobal
ret.workingDirectory = basepath
return ret, exp
def clear(basepath: str)->None:
oipath = ecrpath.getMainPath(basepath)
if hasInitialized(basepath):
log.debug(f"Clear ecr data at {basepath}")
shutil.rmtree(oipath)
def initialize(basepath: str)->None:
clear(basepath)
log.debug(f"Initialize ecr data at {basepath}")
oipath = ecrpath.getMainPath(basepath)
os.mkdir(oipath)
# templatePath = ecrpath.getTemplatePath(basepath)
# os.mkdir(templatePath)
# for k, v in defaultData.codeTemplate.items():
# with open(os.path.join(templatePath, f"{TEMPLATE_NAME}.{languageToFileext[k]}"),
# "w", encoding='utf-8') as f:
# f.write(v)
# os.mkdir(ecrpath.getJudgerPath(basepath))
shutil.copytree(ecrpath.getCoreJudgerPath(),
ecrpath.getJudgerPath(basepath))
shutil.copytree(ecrpath.getCoreTemplatePath(),
ecrpath.getTemplatePath(basepath))
executors = defaultData.executors
with open(ecrpath.getExecutorPath(basepath), "w", encoding='utf-8') as f:
f.write(yaml.dump(executors, indent=4,
default_flow_style=False))
judgers = defaultData.judgers
with open(ecrpath.getJudgerConfigPath(basepath), "w", encoding='utf-8') as f:
f.write(yaml.dump(judgers, indent=4,
default_flow_style=False))
templates = defaultData.templates
with open(ecrpath.getTemplateConfigPath(basepath), "w", encoding='utf-8') as f:
f.write(yaml.dump(templates, indent=4,
default_flow_style=False))
open(ecrpath.getFileInputPath(basepath), "w").close()
open(ecrpath.getFileOutputPath(basepath), "w").close()
open(ecrpath.getFileStdPath(basepath), "w").close()
from . import __version__
config = {CONST_tempFileFilter: defaultData.tempFileFilter,
CONST_importedCommand: defaultData.importedCommand,
CONST_defaultShell: "powershell -c" if platform.system() == "Windows" else None,
CONST_defaultIO: defaultData.io,
CONST_defaultTimeLimit: defaultData.timeLimit,
CONST_defaultEditor: defaultData.editor,
CONST_defaultJudger: defaultData.judger,
CONST_eVersion: __version__}
with open(ecrpath.getConfigPath(basepath), "w", encoding='utf-8') as f:
f.write(yaml.dump(config, indent=4,
default_flow_style=False))
|