Skip to content

Commit e67a223

Browse files
authored
Merge pull request #52 from kyuridenamida/feature/code_gen_option
Add code gen configuration
2 parents a2dd3b3 + 8dbb771 commit e67a223

File tree

13 files changed

+138
-35
lines changed

13 files changed

+138
-35
lines changed

MANIFEST.in

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
recursive-include atcodertools/tools/templates/ *
2-
include requirements.txt
2+
include requirements.txt
3+
include atcodertools/tools/atcodertools-default.toml
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import TextIO
2+
3+
import toml
4+
5+
INDENT_TYPE_SPACE = 'space'
6+
INDENT_TYPE_TAB = 'tab'
7+
8+
9+
class ConfigInitError(Exception):
10+
pass
11+
12+
13+
class CodeGenConfig:
14+
def __init__(self,
15+
indent_type: str = INDENT_TYPE_SPACE,
16+
indent_width: int = 4,
17+
):
18+
19+
if indent_type not in [INDENT_TYPE_SPACE, INDENT_TYPE_TAB]:
20+
raise ConfigInitError("indent_type must be 'space' or 'tab'")
21+
22+
if indent_width < 0:
23+
raise ConfigInitError("indent_width must be a positive integer")
24+
25+
self.indent_type = indent_type
26+
self.indent_width = indent_width
27+
28+
def indent(self, depth):
29+
if self.indent_type == INDENT_TYPE_SPACE:
30+
return " " * self.indent_width * depth
31+
return "\t" * self.indent_width * depth
32+
33+
@classmethod
34+
def load(cls, fp: TextIO):
35+
kwargs = toml.load(fp).get("codegen")
36+
return CodeGenConfig(**kwargs)

atcodertools/codegen/cpp_code_generator.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from atcodertools.codegen.code_gen_config import CodeGenConfig
12
from atcodertools.models.analyzer.analyzed_variable import AnalyzedVariable
23
from atcodertools.models.analyzer.simple_format import Pattern, SingularPattern, ParallelPattern, TwoDimensionalPattern
34
from atcodertools.models.predictor.format_prediction_result import FormatPredictionResult
@@ -22,9 +23,10 @@ def _loop_header(var: Variable, for_second_index: bool):
2223

2324
class CppCodeGenerator(CodeGenerator):
2425

25-
def __init__(self, template: str):
26+
def __init__(self, template: str, config: CodeGenConfig = CodeGenConfig()):
2627
self._template = template
2728
self._prediction_result = None
29+
self._config = config
2830

2931
def generate_code(self, prediction_result: FormatPredictionResult):
3032
if prediction_result is None:
@@ -157,7 +159,7 @@ def _render_pattern(self, pattern: Pattern):
157159
return lines
158160

159161
def _indent(self, depth):
160-
return " " * depth
162+
return self._config.indent(depth)
161163

162164

163165
class NoPredictionResultGiven(Exception):

atcodertools/release_management/version_check.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,16 @@ def store_version_cache(version):
4141
f.write("{} {}".format(version, time.time()))
4242

4343

44-
def get_latest_version(user_cache=True):
44+
def get_latest_version(use_cache=True):
4545
try:
46-
if user_cache:
46+
if use_cache:
4747
cached_version = _get_latest_version_cache()
4848
if cached_version:
4949
return cached_version
5050

5151
version = _fetch_latest_version()
5252

53-
if user_cache:
53+
if use_cache:
5454
store_version_cache(version)
5555

5656
return version
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[codegen]
2+
indent_type = 'space' # 'tab' or 'space'
3+
indent_width = 4

atcodertools/tools/envgen.py

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66
from multiprocessing import Pool, cpu_count
77
from os.path import expanduser
88
from time import sleep
9-
from typing import Tuple
9+
from typing import Tuple, Optional
1010

11+
from atcodertools.codegen.code_gen_config import CodeGenConfig
1112
from atcodertools.codegen.cpp_code_generator import CppCodeGenerator
1213
from atcodertools.codegen.java_code_generator import JavaCodeGenerator
1314
from atcodertools.fileutils.create_contest_file import create_examples, create_code_from_prediction_result
@@ -43,7 +44,9 @@ def prepare_procedure(atcoder_client: AtCoderClient,
4344
workspace_root_path: str,
4445
template_code_path: str,
4546
replacement_code_path: str,
46-
lang: str):
47+
lang: str,
48+
config: CodeGenConfig,
49+
):
4750
pid = problem.get_alphabet()
4851
workspace_dir_path = os.path.join(
4952
workspace_root_path,
@@ -112,7 +115,7 @@ def emit_info(text):
112115

113116
create_code_from_prediction_result(
114117
result,
115-
gen_class(template),
118+
gen_class(template, config),
116119
code_file_path)
117120
emit_info(
118121
"Prediction succeeded -- Saved auto-generated code to '{}'".format(code_file_path))
@@ -141,11 +144,11 @@ def emit_info(text):
141144
emit_info("Saved metadata to {}".format(metadata_path))
142145

143146

144-
def func(argv: Tuple[AtCoderClient, Problem, str, str, str, str]):
145-
atcoder_client, problem, workspace_root_path, template_code_path, replacement_code_path, lang = argv
147+
def func(argv: Tuple[AtCoderClient, Problem, str, str, str, str, CodeGenConfig]):
148+
atcoder_client, problem, workspace_root_path, template_code_path, replacement_code_path, lang, config = argv
146149
prepare_procedure(
147150
atcoder_client, problem, workspace_root_path, template_code_path,
148-
replacement_code_path, lang)
151+
replacement_code_path, lang, config)
149152

150153

151154
def prepare_workspace(atcoder_client: AtCoderClient,
@@ -154,7 +157,9 @@ def prepare_workspace(atcoder_client: AtCoderClient,
154157
template_code_path: str,
155158
replacement_code_path: str,
156159
lang: str,
157-
parallel: bool):
160+
parallel: bool,
161+
config: CodeGenConfig,
162+
):
158163
retry_duration = 1.5
159164
while True:
160165
problem_list = atcoder_client.download_problem_list(
@@ -165,7 +170,7 @@ def prepare_workspace(atcoder_client: AtCoderClient,
165170
logging.warning(
166171
"Failed to fetch. Will retry in {} seconds".format(retry_duration))
167172

168-
tasks = [(atcoder_client, problem, workspace_root_path, template_code_path, replacement_code_path, lang) for
173+
tasks = [(atcoder_client, problem, workspace_root_path, template_code_path, replacement_code_path, lang, config) for
169174
problem in problem_list]
170175
if parallel:
171176
thread_pool = Pool(processes=cpu_count())
@@ -202,41 +207,61 @@ def check_lang(lang: str):
202207
return lang
203208

204209

210+
USER_CONFIG_PATH = os.path.join(
211+
expanduser("~"), ".atcodertools.toml")
212+
DEFAULT_CONFIG_PATH = os.path.abspath(
213+
os.path.join(script_dir_path, "./atcodertools-default.toml"))
214+
215+
216+
def get_code_gen_config(config_path: Optional[str] = None):
217+
def _load(path: str):
218+
logging.info("Going to load {} as config".format(path))
219+
with open(path, 'r') as f:
220+
return CodeGenConfig.load(f)
221+
222+
if config_path:
223+
return _load(config_path)
224+
225+
if os.path.exists(USER_CONFIG_PATH):
226+
return _load(USER_CONFIG_PATH)
227+
228+
return _load(DEFAULT_CONFIG_PATH)
229+
230+
205231
def main(prog, args):
206232
parser = argparse.ArgumentParser(
207233
prog=prog,
208234
formatter_class=argparse.RawTextHelpFormatter)
209235

210236
parser.add_argument("contest_id",
211-
help="contest ID (e.g. arc001)")
237+
help="Contest ID (e.g. arc001)")
212238

213239
parser.add_argument("--without-login",
214240
action="store_true",
215-
help="download data without login")
241+
help="Download data without login")
216242

217243
parser.add_argument("--workspace",
218-
help="path to workspace's root directory. This script will create files"
244+
help="Path to workspace's root directory. This script will create files"
219245
" in {{WORKSPACE}}/{{contest_name}}/{{alphabet}}/ e.g. ./your-workspace/arc001/A/\n"
220246
"[Default] {}".format(DEFAULT_WORKSPACE_DIR_PATH),
221247
default=DEFAULT_WORKSPACE_DIR_PATH)
222248

223249
parser.add_argument("--lang",
224-
help="programming language of your template code, {}.\n"
250+
help="Programming language of your template code, {}.\n"
225251
.format(" or ".join(SUPPORTED_LANGUAGES)) + "[Default] {}".format(DEFAULT_LANG),
226252
default=DEFAULT_LANG,
227253
type=check_lang)
228254

229255
parser.add_argument("--template",
230-
help="{0}{1}".format("file path to your template code\n"
231-
"[Default (C++)] {}\n".format(
232-
get_default_template_path('cpp')),
233-
"[Default (Java)] {}".format(
234-
get_default_template_path('java')))
256+
help="File path to your template code\n{0}{1}".format(
257+
"[Default (C++)] {}\n".format(
258+
get_default_template_path('cpp')),
259+
"[Default (Java)] {}".format(
260+
get_default_template_path('java')))
235261
)
236262

237263
parser.add_argument("--replacement",
238-
help="{0}{1}".format(
239-
"file path to the replacement code created when template generation is failed.\n"
264+
help="File path to your config file\n{0}{1}".format(
240265
"[Default (C++)] {}\n".format(get_default_replacement_path('cpp')),
241266
"[Default (Java)] {}".format(
242267
get_default_replacement_path('java')))
@@ -252,6 +277,13 @@ def main(prog, args):
252277
help="Save no session cache to avoid security risk",
253278
default=False)
254279

280+
parser.add_argument("--config",
281+
help="File path to your config file\n{0}{1}".format("[Default (Primary)] {}\n".format(
282+
USER_CONFIG_PATH),
283+
"[Default (Secondary)] {}\n".format(
284+
DEFAULT_CONFIG_PATH))
285+
)
286+
255287
args = parser.parse_args(args)
256288

257289
try:
@@ -281,7 +313,9 @@ def main(prog, args):
281313
args.replacement if args.replacement is not None else get_default_replacement_path(
282314
args.lang),
283315
args.lang,
284-
args.parallel)
316+
args.parallel,
317+
get_code_gen_config(args.config)
318+
)
285319

286320

287321
if __name__ == "__main__":

atcodertools/tools/submit.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ def main(prog, args, credential_supplier=None, use_local_session_cache=True) ->
2424
formatter_class=argparse.RawTextHelpFormatter)
2525

2626
parser.add_argument("--exec", '-e',
27-
help="file path to the execution target. [Default] Automatically detected exec file",
27+
help="File path to the execution target. [Default] Automatically detected exec file",
2828
default=None)
2929

3030
parser.add_argument("--dir", '-d',
31-
help="target directory to test. [Default] Current directory",
31+
help="Target directory to test. [Default] Current directory",
3232
default=".")
3333

3434
parser.add_argument("--timeout", '-t',
@@ -37,7 +37,7 @@ def main(prog, args, credential_supplier=None, use_local_session_cache=True) ->
3737
default=1)
3838

3939
parser.add_argument("--code", '-c',
40-
help="path to the source code to submit [Default] Code path written in metadata.json",
40+
help="Path to the source code to submit [Default] Code path written in metadata.json",
4141
type=str,
4242
default=None)
4343

atcodertools/tools/tester.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,16 +230,16 @@ def main(prog, args) -> bool:
230230
formatter_class=argparse.RawTextHelpFormatter)
231231

232232
parser.add_argument("--exec", '-e',
233-
help="file path to the execution target. [Default] Automatically detected exec file",
233+
help="File path to the execution target. [Default] Automatically detected exec file",
234234
default=None)
235235

236236
parser.add_argument("--num", '-n',
237-
help="the case number to test (1-origin). All cases are tested if not specified.",
237+
help="The case number to test (1-origin). All cases are tested if not specified.",
238238
type=int,
239239
default=None)
240240

241241
parser.add_argument("--dir", '-d',
242-
help="target directory to test. [Default] Current directory",
242+
help="Target directory to test. [Default] Current directory",
243243
default=".")
244244

245245
parser.add_argument("--timeout", '-t',

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
beautifulsoup4
22
requests
3-
colorama
3+
colorama
4+
toml
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[codegen]
2+
indent_width = 8

0 commit comments

Comments
 (0)