Пример #1
0
def generate_code(result: QualityResult):
    if result.prediction_result is not None:
        result.codes["cpp"] = apply_clang(
            CPP.default_code_generator(
                CodeGenArgs(CPP_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
        result.codes["java"] = apply_clang(
            JAVA.default_code_generator(
                CodeGenArgs(JAVA_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
        result.codes["rust"] = apply_clang(
            RUST.default_code_generator(
                CodeGenArgs(RUST_TEMPLATE, result.prediction_result.format,
                            result.constant_set, CodeStyleConfig())))
Пример #2
0
 def __init__(self,
              code_style_config: CodeStyleConfig = CodeStyleConfig(),
              postprocess_config: PostprocessConfig = PostprocessConfig(),
              etc_config: EtcConfig = EtcConfig()):
     self.code_style_config = code_style_config
     self.postprocess_config = postprocess_config
     self.etc_config = etc_config
Пример #3
0
    def load(cls, fp: TextIO, args: Optional[Namespace] = None):
        """
        :param fp: .toml file's file pointer
        :param args: command line arguments
        :return: Config instance
        """
        config_dic = toml.load(fp)

        code_style_config_dic = config_dic.get('codestyle', {})
        postprocess_config_dic = config_dic.get('postprocess', {})
        etc_config_dic = config_dic.get('etc', {})

        if args:
            code_style_config_dic = _update_config_dict(code_style_config_dic,
                                                        dict(template_file=args.template,
                                                             workspace_dir=args.workspace,
                                                             lang=args.lang))
            etc_config_dic = _update_config_dict(etc_config_dic,
                                                 dict(download_without_login=args.without_login,
                                                      parallel_download=args.parallel,
                                                      save_no_session_cache=args.save_no_session_cache))

        return Config(
            code_style_config=CodeStyleConfig(**code_style_config_dic),
            postprocess_config=PostprocessConfig(**postprocess_config_dic),
            etc_config=EtcConfig(**etc_config_dic)
        )
Пример #4
0
    def _compile_and_run(self, lang, format, template_file,
                         expected_generated_code_file, input_file):
        code_file = os.path.join(self.temp_dir, lang.source_code_name("main"))
        exec_file, exec_args = self._exec_file_and_args(lang)
        compile_cmd = self._compile_command(lang, code_file)
        args = CodeGenArgs(template=load_text_file(template_file),
                           format_=format,
                           constants=ProblemConstantSet(123, "yes", "NO"),
                           config=CodeStyleConfig(lang=lang.name))
        code = lang.default_code_generator(args)
        # to remove version strings from test resources
        code = re.sub(r'Generated by \d+.\d+.\d+', 'Generated by x.y.z', code)
        self.compare_two_texts_ignoring_trailing_spaces(
            load_text_file(expected_generated_code_file), code)
        create_code(code, code_file)
        try:
            print("Executing:", compile_cmd)
            print(run_command(compile_cmd, self.temp_dir))

            print("Run program:", [exec_file] + exec_args)
            exec_result = run_program(exec_file, input_file, 2, exec_args,
                                      self.temp_dir)
        finally:
            self._clean_up(lang)

        print("== stdout ==")
        print(exec_result.output)
        print("== stderr ==")
        print(exec_result.stderr)

        self.assertEqual(exec_result.status.NORMAL, exec_result.status)
        return exec_result
Пример #5
0
 def test_prepare_contest_aborts_after_max_retry_attempts(self, mock_sleep):
     mock_client = mock.Mock(spec=AtCoderClient)
     mock_client.download_problem_list.return_value = []
     self.assertRaises(
         EnvironmentInitializationError,
         prepare_contest,
         mock_client,
         "agc029",
         Config(
             code_style_config=CodeStyleConfig(
                 workspace_dir=self.temp_dir,
                 template_file=TEMPLATE_PATH,
                 lang="cpp",
             ),
             etc_config=EtcConfig(
                 in_example_format="input_{}.txt",
                 out_example_format="output_{}.txt"
             ))
     )
     self.assertEqual(mock_sleep.call_count, 10)
     mock_sleep.assert_has_calls([mock.call(1.5),
                                  mock.call(3.0),
                                  mock.call(6.0),
                                  mock.call(12.0),
                                  mock.call(24.0),
                                  mock.call(48.0),
                                  mock.call(60.0),
                                  mock.call(60.0),
                                  mock.call(60.0),
                                  mock.call(60.0)])
Пример #6
0
    def _compile_and_run(self, lang, format, template_file,
                         expected_generated_code_file, input_file):
        code_file = os.path.join(self.temp_dir, lang.source_code_name("main"))
        exec_file, exec_args = self._exec_file_and_args(lang)
        compile_cmd = self._compile_command(lang, code_file)

        args = CodeGenArgs(template=load_text_file(template_file),
                           format_=format,
                           constants=ProblemConstantSet(123, "yes", "NO"),
                           config=CodeStyleConfig())

        code = lang.default_code_generator(args)
        self.compare_two_texts_ignoring_trailing_spaces(
            load_text_file(expected_generated_code_file), code)
        create_code(code, code_file)
        print(run_command(compile_cmd, self.temp_dir))
        exec_result = run_program(exec_file, input_file, 2, exec_args,
                                  self.temp_dir)
        print("== stdout ==")
        print(exec_result.output)
        print("== stderr ==")
        print(exec_result.stderr)

        self.assertEqual(exec_result.status.NORMAL, exec_result.status)
        return exec_result
Пример #7
0
def generate_code(result: QualityResult):
    if result.prediction_result is None:
        result_format = None
    else:
        result_format = result.prediction_result.format

    result.codes["cpp"] = apply_clang(
        CPP.default_code_generator(
            CodeGenArgs(CPP_TEMPLATE, result_format, result.constant_set,
                        CodeStyleConfig(lang=CPP.name))))
    result.codes["java"] = JAVA.default_code_generator(
        CodeGenArgs(JAVA_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=JAVA.name)))
    result.codes["rust"] = RUST.default_code_generator(
        CodeGenArgs(RUST_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=RUST.name)))
    result.codes["python"] = PYTHON.default_code_generator(
        CodeGenArgs(PYTHON_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=PYTHON.name)))
    result.codes["d"] = DLANG.default_code_generator(
        CodeGenArgs(D_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=DLANG.name)))
    result.codes["nim"] = NIM.default_code_generator(
        CodeGenArgs(NIM_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=NIM.name)))
    result.codes["csharp"] = CSHARP.default_code_generator(
        CodeGenArgs(CSHARP_TEMPLATE, result_format, result.constant_set,
                    CodeStyleConfig(lang=CSHARP.name)))
Пример #8
0
 def test_backup(self):
     answer_data_dir_path = os.path.join(RESOURCE_DIR, "test_backup")
     # Prepare workspace twice
     for _ in range(2):
         prepare_contest(
             AtCoderClient(), "agc029",
             Config(code_style_config=CodeStyleConfig(
                 workspace_dir=self.temp_dir,
                 template_file=TEMPLATE_PATH,
                 lang="cpp",
             )))
     self.assertDirectoriesEqual(answer_data_dir_path, self.temp_dir)
Пример #9
0
 def verify(self,
            response: Response,
            py_test_name: str,
            lang: Language,
            template_type: str = "old",
            constants: ProblemConstantSet = ProblemConstantSet()):
     self.assertEqual(load_intermediate_format(py_test_name),
                      str(response.simple_format))
     self.assertEqual(load_intermediate_types(py_test_name),
                      str(response.types))
     self.assertEqual(
         load_generated_code(py_test_name, lang),
         self.lang_to_code_generator_func[lang](CodeGenArgs(
             self.get_template(lang, template_type),
             response.original_result.format, constants,
             CodeStyleConfig(lang=lang.name))))
Пример #10
0
    def load(cls, fp: TextIO, args: Optional[Namespace] = None):
        """
        :param fp: .toml file's file pointer
        :param args: command line arguments
        :return: Config instance
        """
        config_dic = toml.load(fp)

        code_style_config_dic = config_dic.get('codestyle', {})
        postprocess_config_dic = config_dic.get('postprocess', {})
        etc_config_dic = config_dic.get('etc', {})

        if args:
            d = dict()
            if hasattr(args, 'template'):
                d['template_file'] = args.template
            if hasattr(args, 'workspace'):
                d['workspace_dir'] = args.workspace
            if hasattr(args, 'lang'):
                d['lang'] = args.lang
            code_style_config_dic = _update_config_dict(
                code_style_config_dic, d)

            lang = code_style_config_dic['lang']
            if lang in config_dic:
                code_style_config_dic = _update_config_dict(
                    code_style_config_dic, config_dic[lang])

            d = dict()
            if hasattr(args, 'without_login'):
                d['download_without_login'] = args.without_login
            if hasattr(args, 'parallel'):
                d['parallel_download'] = args.parallel
            if hasattr(args, 'save_no_session_cache'):
                d['save_no_session_cache'] = args.save_no_session_cache

            etc_config_dic = _update_config_dict(etc_config_dic, d)
        print(code_style_config_dic)
        return Config(
            code_style_config=CodeStyleConfig(**code_style_config_dic),
            postprocess_config=PostprocessConfig(**postprocess_config_dic),
            etc_config=EtcConfig(**etc_config_dic))
Пример #11
0
    def load(cls, fp: TextIO, args: Optional[ProgramArgs] = None):
        """
        :param fp: .toml file's file pointer
        :param args: command line arguments
        :return: Config instance
        """
        config_dic = toml.load(fp)
        # Root 'codestyle' is common code style
        common_code_style_config_dic = config_dic.get(
            _CODE_STYLE_CONFIG_KEY, {})

        postprocess_config_dic = config_dic.get(_POST_PROCESS_CONFIG_KEY, {})
        etc_config_dic = config_dic.get('etc', {})
        run_config_dic = config_dic.get(_RUN_CONFIG_KEY, {})
        code_style_config_dic = {**common_code_style_config_dic}

        # Handle config override strategy in the following code
        # (Most preferred) program arguments > lang-specific > common config (Least preferred)
        lang = (args and args.lang) or common_code_style_config_dic.get(
            "lang", DEFAULT_LANGUAGE)
        code_style_config_dic = _update_config_dict(
            code_style_config_dic, dict(lang=lang))

        if lang in config_dic:
            lang_specific_config_dic = config_dic[lang]  # e.g. [cpp.codestyle]
            if _CODE_STYLE_CONFIG_KEY in lang_specific_config_dic:
                lang_code_style = lang_specific_config_dic[_CODE_STYLE_CONFIG_KEY]
                if "lang" in lang_code_style:
                    logger.warn(
                        with_color("'lang' is only valid in common code style config, "
                                   "but detected in language-specific code style config. It will be ignored.",
                                   Fore.RED))
                    del lang_code_style["lang"]

                code_style_config_dic = _update_config_dict(code_style_config_dic,
                                                            lang_code_style)

            # e.g. [cpp.postprocess]
            if _POST_PROCESS_CONFIG_KEY in lang_specific_config_dic:
                postprocess_config_dic = _update_config_dict(postprocess_config_dic,
                                                             lang_specific_config_dic[_POST_PROCESS_CONFIG_KEY])

            if _RUN_CONFIG_KEY in lang_specific_config_dic:  # e.g. [cpp.run]
                run_config_dic = _update_config_dict(run_config_dic,
                                                     lang_specific_config_dic[_RUN_CONFIG_KEY])

        if args:
            code_style_config_dic = _update_config_dict(
                code_style_config_dic,
                dict(template_file=args.template,
                     workspace_dir=args.workspace)
            )
            etc_config_dic = _update_config_dict(
                etc_config_dic,
                dict(
                    download_without_login=args.without_login,
                    parallel_download=args.parallel,
                    save_no_session_cache=args.save_no_session_cache,
                    compile_before_testing=args.compile_before_testing,
                    compile_only_when_diff_detected=args.compile_only_when_diff_detected
                )
            )

        return Config(
            code_style_config=CodeStyleConfig(**code_style_config_dic),
            postprocess_config=PostprocessConfig(**postprocess_config_dic),
            etc_config=EtcConfig(**etc_config_dic),
            run_config=RunConfig(**run_config_dic)
        )
Пример #12
0
 def _expect_error_when_init_config(self, **kwargs):
     try:
         CodeStyleConfig(**kwargs)
         self.fail("Must not reach here")
     except CodeStyleConfigInitError:
         pass