Ejemplo n.º 1
0
def applyCppAndStripCommentsIntoFile(fileName, definitions, outfile, useCpp):
    stderr = None
    if useCpp:
        args = ''
        for key, value in definitions.iteritems():
            args += "'-D%s=%s' " % (key, value)
        pipe = subprocess.Popen("cpp -traditional-cpp %s '%s'" %
                                (args, fileName),
                                shell=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        source = pipe.stdout
        stderr = pipe.stderr
    else:
        source = io.open(fileName, 'r')

    for line in source.readlines():
        if line != '\n' and not commentFilter.match(line):
            print(line, end='', file=outfile)

    if stderr:
        for line in stderr.readlines():
            print(colored(line, 'red'), end='')
        stderr.close()

    source.close()
Ejemplo n.º 2
0
 def generate(self, searchDirs, projectFiles, outputDir, forceOverwrite = False):
     self.errors = 0
     
     print("-- Generating project %s in directory '%s'" % (self._name, outputDir))
     self.verbose("--- Using template search path '%s'" % ( ":".join(searchDirs)))
     self.createDir(outputDir, '--')
     for projectFile in projectFiles :
         projectFileFullPath = projectFile.getFullPath(outputDir)
         projectFileExists = os.path.exists(projectFileFullPath)
         if (not projectFileExists or forceOverwrite) :
             print("--- %s %s" % ("Overwriting" if projectFileExists else "Creating", projectFileFullPath))
             self.createDir(projectFile.getFullDirPath(outputDir), '---')
             try:
                 content = self.calcContent(searchDirs, projectFile.getFullPath());
                 with open(projectFileFullPath, 'w') as outfile:
                     print (content , file = outfile )
                 self.okay("--> OK")
             except tools.FindError as e:
                 self.error("--> Failed: Could not find template file '%s' in search list %s!" % (e.file, searchDirs))
         else:
             self.error("--- Skipping existing %s (use -f to overwrite)" % (projectFile))
     if self.errors == 0:
         print(colored('-> Successfully created the project {0} in directory {1}'.format(self._name, outputDir), 'green'))
     else:
         self.error("-> Failed: Some errors occurred while created the project {0} in directory '{1}'".format(self._name, outputDir))
Ejemplo n.º 3
0
 def generate(self, searchDirs, projectFiles, outputDir, forceOverwrite = False):
     self.errors = 0
     
     print("-- Generating project %s in directory '%s'" % (self._name, outputDir))
     self.verbose("--- Using template search path '%s'" % ( ":".join(searchDirs)))
     self.createDir(outputDir, '--')
     for projectFile in projectFiles :
         projectFileFullPath = projectFile.getFullPath(outputDir)
         projectFileExists = os.path.exists(projectFileFullPath)
         if (not projectFileExists or forceOverwrite) :
             print("--- %s %s" % ("Overwriting" if projectFileExists else "Creating", projectFileFullPath))
             self.createDir(projectFile.getFullDirPath(outputDir), '---')
             try:
                 content = self.calcContent(searchDirs, projectFile.getFullPath());
                 with open(projectFileFullPath, 'w') as outfile:
                     print (content , file = outfile )
                 self.okay("--> OK")
             except tools.FindError as e:
                 self.error("--> Failed: Could not find template file '%s' in search list %s!" % (e.file, searchDirs))
         else:
             self.error("--- Skipping existing %s (use -f to overwrite)" % (projectFile))
     if self.errors == 0:
         print(colored('-> Successfully created the project {0} in directory {1}'.format(self._name, outputDir), 'green'))
     else:
         self.error("-> Failed: Some errors occurred while created the project {0} in directory '{1}'".format(self._name, outputDir))
Ejemplo n.º 4
0
def build(args):
    if not args.grammar and not args.caramel and not args.all:
        logger.warn('Nothing to build.')
        return

    logger.info('Build started...')
    start_time = time()

    if args.debug and not args.caramel:
        logger.warn('--release ignored because -c / --caramel is absent.')
        args.debug = False

    if args.all:
        args.grammar = True
        args.caramel = True

    if args.grammar:
        build_grammar(args)

    if args.caramel:
        build_caramel(args)

    total_time = time() - start_time
    logger.info('Build finished. Total time: {}.'.format(
        colored(seconds_to_string(total_time), color='yellow')))
Ejemplo n.º 5
0
 def check_build(self):
     if not os.path.isdir('build'):
         logger.critical(
             colored(' '.join([
                 'The build directory is absent! Try to build before',
                 'running tests, or to add --build to the command.'
             ]),
                     color='red'))
         exit(1)
Ejemplo n.º 6
0
 def __repr__(self):
     part = 'n'
     if self.part == 'Front':
         part = 'f'
     elif self.part == 'Middle':
         part = 'm'
     elif self.part == 'Rear':
         part = 'r'
     if self.part:
         return colored(
             colored_background(
                 '{}{}[{}{}]'.format(
                     self.col, self.row, part,
                     colored('x', 'red') if self.hit else colored(
                         'o', 'green')), 'orange'), 'blue')
     return '{}{}[{}{}]'.format(
         self.col, self.row, part,
         colored('x', 'red') if self.hit else colored('o', 'green'))
Ejemplo n.º 7
0
def main():
    try:
        _chef()
    except KeyboardInterrupt:
        logger.warn('Chef was ordered to stop early.')
        exit(1)
    except Exception as e:
        logger.critical(
            colored('An exception occurred:', 'red', None, ['bold']), e)
        raise e
Ejemplo n.º 8
0
 def generate(self, searchDirs, projectFiles, outputDir):
     errors = 0
     print("-- Generating project %s in directory '%s'" % (self._name, outputDir))
     self.verbose("--- Using template search path '%s'" % ( ":".join(searchDirs)))
     self.createDir(outputDir, '--')
     for projectFile in projectFiles :
         print("--- Creating %s" % (projectFile))
         self.createDir(projectFile.getFullDirPath(outputDir), '---')
         try:
             content = self.calcContent(searchDirs, projectFile.getFullPath());
             with open(projectFile.getFullPath(outputDir), 'w') as outfile:
                 print (content , file = outfile )
             print (colored("--> OK", 'green'))
         except tools.FindError as e:
             print (colored("--> Failed: Could not find template file '%s' in search list %s!" % (e.file, searchDirs), 'red'))
             errors += 1;
     if errors == 0:
         print(colored('-> Successfully created the project {0} in directory {1}'.format(self._name, outputDir), 'green'))
     else:
         print(colored("-> Failed: Some errors occurred while created the project {0} in directory '{1}'".format(self._name, outputDir), 'red'))
Ejemplo n.º 9
0
    def discover(self, base_directory, only=None):
        # Check if there are tests
        if not os.path.isdir(base_directory):
            logger.critical(
                'The {} directory is absent!'.format(base_directory))
            exit(1)

        if only is not None and isinstance(only, list):
            only = set(only)

        # Discover the tests
        nb_tests_before = len(self.tests)
        for test_directory in ['.'] + list(sorted(os.listdir(base_directory))):
            logger.debug('Looking for tests in:', test_directory)
            if os.path.isdir(os.path.join(base_directory, test_directory)):
                for test_file in sorted(
                        os.listdir(os.path.join(base_directory,
                                                test_directory))):
                    if only is None or test_file in only:
                        if only is not None:
                            only.remove(test_file)
                        test_path = os.path.join(base_directory,
                                                 test_directory, test_file)
                        if os.path.isfile(test_path):
                            self.add_test(test_file, test_path,
                                          test_directory == 'invalid')

        # Consider remaining test files as relative paths
        if only is not None:
            for test_path in only:
                if not os.path.isfile(test_path):
                    logger.fatal('Could not find test: {}'.format(test_path))
                    exit(1)
                self.add_test(test_path.split('/')[-1], test_path, False)

        logger.info(
            'Discovered',
            colored('{} tests.'.format(len(self.tests) - nb_tests_before),
                    color='yellow'))
Ejemplo n.º 10
0
def applyCppAndStripCommentsIntoFile(fileName, definitions, outfile, useCpp):
    stderr = None
    if useCpp:
        args = ''
        for key, value in definitions.iteritems():
            args += "'-D%s=%s' " % (key, value)
        pipe = subprocess.Popen("cpp -traditional-cpp %s '%s'" % (args, fileName), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        source = pipe.stdout
        stderr = pipe.stderr
    else:
        source = io.open(fileName, 'r')

    for line in source.readlines():
        if line != '\n' and not commentFilter.match(line):
            print(line, end='', file=outfile)

    if stderr:
        for line in stderr.readlines():
            print(colored(line, 'red'), end='')
        stderr.close()

    source.close()
Ejemplo n.º 11
0
 def okay(self, text):
     print (colored(text, 'green'))
Ejemplo n.º 12
0
 def error(self, text):
     print (colored(text, 'red'))
     self.errors += 1
Ejemplo n.º 13
0
 def verbose(self, text):
     if self._verbose : print (colored(text, 'yellow'))
Ejemplo n.º 14
0
    def execute(self,
                open_gui=False,
                open_gui_on_failure=False,
                show_stdout=False,
                show_stderr=False):
        start_time = time()
        grun_mode = '-gui' if open_gui else '-tree'
        command = shlex.split('{} Caramel r {} {}'.format(
            COMMANDS['grun'].format(build_grammar=PATHS['java-grammar']),
            grun_mode, self.full_path))
        logger.trace('Test command:', ' '.join(command))
        if len(self.full_path) == 0:  # Interactive test
            print('Enter grammar test input: (ended by ^D)')
        with subprocess.Popen(
                command,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
        ) as test_process:
            test_process.wait()

            # Get stdout and stderr
            out_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stdout.readlines()))
            error_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stderr.readlines()))

            # Save the test state
            self.state = {
                'stdout': sum(len(line.strip()) for line in out_str),
                'stderr': sum(len(line.strip()) for line in error_str),
                'time': time() - start_time
            }

            # Determine if unexpected errors, or successes, occurred
            errors = self.state['stderr'] > 0
            self.succeeded = errors if self.should_fail else not errors

            # Feed our user
            if self.succeeded:
                logger.info(
                    'Test {}'.format(self.display_name),
                    colored('succeeded.', color='green', attrs=['bold']),
                    colored('[%s]' % seconds_to_string(self.state['time']),
                            color='yellow'))
            else:
                logger.info(
                    'Test {}'.format(self.display_name),
                    colored('failed.', color='red', attrs=['bold']),
                    colored('[%s]' % seconds_to_string(self.state['time']),
                            color='yellow'))
                failed_tests.append(self.display_name)
                if open_gui_on_failure and not open_gui:
                    self.execute(open_gui=True, open_gui_on_failure=False)

            # Show stdout or stderr if asked
            if show_stdout or open_gui:
                if self.state['stdout'] == 0:
                    print(colored('No stdout output.', attrs=['bold']))
                else:
                    print('\n'.join([
                        '#' * 20,
                        colored('stdout output:', attrs=['bold']),
                        ''.join(out_str),
                        '-' * 20,
                    ]))
            if show_stderr or open_gui:
                if self.state['stderr'] == 0:
                    print(colored('No stderr output.', attrs=['bold']))
                else:
                    print('\n'.join([
                        '#' * 20,
                        colored('stderr output:', attrs=['bold']),
                        ''.join(error_str),
                        '-' * 20,
                    ]))
Ejemplo n.º 15
0
 def okay(self, text):
     print (colored(text, 'green'))
Ejemplo n.º 16
0
 def debug(self, *args, **kwargs):
     if self.level >= LoggerLevel.DEBUG:
         print(colored('[debug]', color='cyan', attrs=['bold']), *args,
               **kwargs)
Ejemplo n.º 17
0
 def warn(self, *args, **kwargs):
     if self.level >= LoggerLevel.WARN:
         print(colored('[warn]', color='yellow', attrs=['bold']), *args,
               **kwargs)
Ejemplo n.º 18
0
def _info_completed_in_seconds(seconds: float):
    logger.info('Completed in {}.'.format(
        colored(seconds_to_string(seconds), color='yellow')))
Ejemplo n.º 19
0
 def createDir(self, dirPath, prefix):
     if dir and not os.path.isdir(dirPath) :
         self.verbose(prefix + "- Creating directory '{0}'".format(dirPath))
         tools.mkdir_p(dirPath)
         print (colored(prefix + "> OK", 'green'))
Ejemplo n.º 20
0
 def verbose(self, text):
     if self._verbose : print (colored(text, 'yellow'))
Ejemplo n.º 21
0
    string_types = str
else:
    string_types = basestring

import re
commentFilter = re.compile(r'^\s*#')

import subprocess
import io
import StringIO

cppAvailable = subprocess.call(["sh", "-c", "echo | cpp > /dev/null 2>&1"]) == 0
if not cppAvailable:
    print(colored("""Warning:
    Unable to run the c pre processor (command cpp).
    Without it eclipsify won't be able to instantiate the templates relying on cpp correctly.
    On Ubuntu or Debian run 'sudo apt-get install cpp' to install it.
    """, 'red'))

def applyCppAndStripCommentsIntoFile(fileName, definitions, outfile, useCpp):
    stderr = None
    if useCpp:
        args = ''
        for key, value in definitions.iteritems():
            args += "'-D%s=%s' " % (key, value)
        pipe = subprocess.Popen("cpp -traditional-cpp %s '%s'" % (args, fileName), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        source = pipe.stdout
        stderr = pipe.stderr
    else:
        source = io.open(fileName, 'r')
Ejemplo n.º 22
0
else:
    string_types = basestring

import re
commentFilter = re.compile(r'^\s*#')

import subprocess
import io
import StringIO


cppAvailable = subprocess.call(["sh", "-c", "echo | cpp > /dev/null 2>&1"]) == 0
if not cppAvailable:
    print(colored("""Warning:
    Unable to run the c pre processor (command cpp).
    Without it eclipsify won't be able to instantiate the templates relying on cpp correctly.
    On Ubuntu or Debian run 'sudo apt-get install cpp' to install it.
    """, 'red'))


def applyCppAndStripCommentsIntoFile(fileName, definitions, outfile, useCpp):
    stderr = None
    if useCpp:
        args = ''
        for key, value in definitions.iteritems():
            args += "'-D%s=%s' " % (key, value)
        pipe = subprocess.Popen("cpp -traditional-cpp %s '%s'" %(args, fileName), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        source = pipe.stdout
        stderr = pipe.stderr
    else:
        source = io.open(fileName, 'r')
Ejemplo n.º 23
0
def _chef():
    start_time = time()

    # create the top-level parser
    parser = argparse.ArgumentParser(
        description='The Caramel Jack of all trades.')
    group_verbosity = parser.add_mutually_exclusive_group()
    group_verbosity.add_argument(
        '--verbose',
        '-v',
        help='increase the verbosity (repeat for even more verbosity)',
        dest='verbosity',
        action='count',
        default=4)
    group_verbosity.add_argument(
        '--quiet',
        '-q',
        help='decrease the verbosity (repeat for less verbosity)',
        action='count',
        default=0)
    subparsers = parser.add_subparsers(title='Available commands',
                                       dest='subcommand_name')

    # create the parser for the "clean" command
    parser_clean = subparsers.add_parser(
        'clean', help='Ask the Chef to clean up his workplace.')
    parser_clean.set_defaults(func=tools.clean.clean)

    # create the parser for the "build" command
    parser_build = subparsers.add_parser(
        'build', help='Make the Chef cook some Caramel.')
    parser_build.add_argument('-g',
                              '--grammar',
                              help='build the grammar',
                              action='store_true')
    parser_build.add_argument('-c',
                              '--caramel',
                              help='build the compiler',
                              action='store_true')
    parser_build.add_argument('-d',
                              '--debug',
                              help='build as debug',
                              action='store_true')
    parser_build.add_argument('-a',
                              '--all',
                              help='build everything',
                              action='store_true')
    parser_build.set_defaults(func=tools.build.build)

    # create the parser for the "test" command
    parser_test = subparsers.add_parser('test',
                                        help='Test the Caramel quality.')

    # create the "test" command common arguments
    def test_common(sub_test_parser: argparse.ArgumentParser):
        sub_test_parser.add_argument('-b',
                                     '--build',
                                     help='build before running tests',
                                     action='store_true')
        sub_test_parser.add_argument('-O',
                                     '--stdout',
                                     help='show the tests stdout output',
                                     action='store_true')
        sub_test_parser.add_argument('-E',
                                     '--stderr',
                                     help='show the tests stderr output',
                                     action='store_true')
        sub_test_parser.add_argument('-i',
                                     '--interactive',
                                     help='run a test in interactive mode',
                                     action='store_true')
        group_test_grammar_gui = sub_test_parser.add_mutually_exclusive_group()
        group_test_grammar_gui.add_argument(
            '-g',
            '--gui',
            help='open a GUI when executing test',
            action='store_true')
        group_test_grammar_gui.add_argument('-G',
                                            '--gui-on-failure',
                                            help='open a GUI on failed tests',
                                            action='store_true')
        sub_test_parser.add_argument('-a',
                                     '--all',
                                     help='run all tests',
                                     action='store_true')
        sub_test_parser.add_argument('test_files',
                                     nargs='*',
                                     help='test files to test')

    # Create the "test" sub-commands
    test_subparsers = parser_test.add_subparsers(
        title='Available sub-commands')

    # Create the parser for the "test grammar" command
    parser_test_grammar = test_subparsers.add_parser(
        'grammar', help='Test the Caramel grammar.')
    parser_test_grammar.set_defaults(func=tools.test.test_grammar)
    test_common(parser_test_grammar)

    # Create the parser for the "test semantic" command
    parser_test_semantic = test_subparsers.add_parser(
        'semantic', help='Test the Caramel semantic analysis.')
    parser_test_semantic.set_defaults(func=tools.test.test_semantic)
    test_common(parser_test_semantic)
    parser_test_semantic.add_argument('-d',
                                      '--debug',
                                      help='run Caramel as debug',
                                      action='store_true')

    # Create the parser for the "test backend" command
    parser_test_backend = test_subparsers.add_parser(
        'backend', help='Test the Caramel back-end.')
    parser_test_backend.set_defaults(func=tools.test.test_backend)
    test_common(parser_test_backend)
    parser_test_backend.add_argument('-d',
                                     '--debug',
                                     help='run Caramel as debug',
                                     action='store_true')

    # Create the parser for the "test programs" command
    parser_test_programs = test_subparsers.add_parser(
        'programs', help='Test the execution of some example programs.')
    parser_test_programs.set_defaults(func=tools.test.test_programs)
    test_common(parser_test_programs)
    parser_test_programs.add_argument('-d',
                                      '--debug',
                                      help='run Caramel as debug',
                                      action='store_true')

    # Create the parser for the "test all" command
    parser_test_all = test_subparsers.add_parser('all', help='Run all tests.')
    parser_test_all.set_defaults(func=tools.test.test_all)
    test_common(parser_test_all)
    parser_test_all.add_argument('-d',
                                 '--debug',
                                 help='run Caramel as debug',
                                 action='store_true')

    # parse the command line and call the appropriate submodule
    args = parser.parse_args()
    logger.level = LoggerLevel(args.verbosity - args.quiet)
    if args.subcommand_name is None:
        logger.warn('You forgot to specify the subcommand. Use -h for help.')
        parser.print_usage()
        exit(1)
    else:
        args.func(args)

    logger.info('Completed in {}.'.format(
        colored(seconds_to_string(time() - start_time), color='yellow')))
Ejemplo n.º 24
0
 def error(self, text):
     print (colored(text, 'red'))
     self.errors += 1
Ejemplo n.º 25
0
 def critical(self, *args, **kwargs):
     if self.level >= LoggerLevel.FATAL:
         print(colored('[critical]', color='red', attrs=['bold']), *args,
               **kwargs)
Ejemplo n.º 26
0
    def execute(self,
                open_gui=False,
                open_gui_on_failure=False,
                show_stdout=False,
                show_stderr=False):
        start_time = time()

        command = './build/cpp-bin/Caramel --good-defaults {}'.format(
            self.full_path)
        logger.trace('Test command:', command)

        if len(self.full_path) == 0:  # Interactive test
            print('Enter semantic test input: (ended by ^D)')
        with subprocess.Popen(shlex.split(command),
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              env={'LD_LIBRARY_PATH': 'lib'}) as test_process:
            test_process.wait()

            # Get stdout and stderr
            out_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stdout.readlines()))
            error_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stderr.readlines()))

            # Save the test state
            self.state = {
                'stdout': sum(len(line.strip()) for line in out_str),
                'stderr': sum(len(line.strip()) for line in error_str),
                'return_code': test_process.returncode,
                'time': time() - start_time
            }

            # Determine if unexpected errors, or successes, occurred
            errors = test_process.returncode != 0
            self.succeeded = errors if self.should_fail else not errors

            # Feed our user
            if self.succeeded:
                logger.info(
                    'Test {}'.format(self.display_name),
                    colored('succeeded.', color='green', attrs=['bold']),
                    colored('[%s]' % seconds_to_string(self.state['time']),
                            color='yellow'))
            else:
                logger.info(
                    'Test {}'.format(self.display_name),
                    colored('failed #{}.'.format(
                        _return_code_to_str(test_process.returncode)),
                            color='red',
                            attrs=['bold']),
                    colored('[%s]' % seconds_to_string(self.state['time']),
                            color='yellow'))
                failed_tests.append(self.display_name)
                if open_gui_on_failure and not open_gui:
                    self.execute(open_gui=True, open_gui_on_failure=False)

            # Show stdout or stderr if asked
            if show_stdout or open_gui:
                if self.state['stdout'] == 0:
                    print(colored('No stdout output.', attrs=['bold']))
                else:
                    print('\n'.join([
                        '#' * 20,
                        colored('stdout output:', attrs=['bold']),
                        ''.join(out_str),
                        '-' * 20,
                    ]))
            if show_stderr or open_gui:
                if self.state['stderr'] == 0:
                    print(colored('No stderr output.', attrs=['bold']))
                else:
                    print('\n'.join([
                        '#' * 20,
                        colored('stderr output:', attrs=['bold']),
                        ''.join(error_str),
                        '-' * 20,
                    ]))
Ejemplo n.º 27
0
 def info(self, *args, **kwargs):
     if self.level >= LoggerLevel.INFO:
         print(colored('[info]', color='blue', attrs=['bold']), *args,
               **kwargs)
Ejemplo n.º 28
0
    def execute(self,
                open_gui=False,
                open_gui_on_failure=False,
                show_stdout=False,
                show_stderr=False):
        start_time = time()

        logger.info('Testing {}...'.format(self.display_name))

        # Get the GCC outputs
        gcc_flags = '-O0 -mno-red-zone -Wno-implicit-function-declaration'  # -Wall -Wextra -Wpedantic'
        gcc_build_command = 'gcc {} {} -o ./build/cpp-bin/gcc.out'.format(
            gcc_flags, self.full_path)
        gcc_run_command = './build/cpp-bin/gcc.out'
        logger.trace('GCC build command:', gcc_build_command)
        exec_(gcc_build_command)
        logger.trace('GCC exec command:', gcc_run_command)
        with subprocess.Popen(shlex.split(gcc_run_command),
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE) as test_process:
            test_process.wait()
            # Get stdout and stderr
            gcc_stdout = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stdout.readlines()))
            gcc_stderr = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stderr.readlines()))

        initial_cwd = os.getcwd()
        os.chdir('./build/cpp-bin')

        # Get the Caramel outputs
        compile_command = './Caramel --good-defaults {}'.format(
            os.path.join('../..', self.full_path))
        assemble_command = 'gcc ./assembly.s -no-pie -o ./caramel.out'
        run_command = './caramel.out'

        # Compile with Caramel
        logger.trace('Compile command:', compile_command)
        if len(self.full_path) == 0:  # Interactive test
            print('Enter back-end test input: (ended by ^D)')
        with subprocess.Popen(shlex.split(compile_command),
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              env={'LD_LIBRARY_PATH':
                                   '../../lib'}) as test_process:
            test_process.wait()

            # Get stdout and stderr
            out_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stdout.readlines()))
            error_str = list(
                map(lambda s: s.decode("utf-8"),
                    test_process.stderr.readlines()))

            # Save the test state
            caramel_state = {
                'stderr': error_str,
                'stdout_lines': sum(len(line.strip()) for line in out_str),
                'stderr_lines': sum(len(line.strip()) for line in error_str),
                'return_code': test_process.returncode,
                'time': time() - start_time
            }
            if caramel_state['stdout_lines'] != 0:
                logger.warn('Caramel wrote on stdout!')

        # Assemble with GCC
        logger.trace('Assemble command:', assemble_command)
        exec_(assemble_command)

        # Execute
        try:
            logger.trace('Run command:', run_command)
            with subprocess.Popen(shlex.split(run_command),
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE) as test_process:
                test_process.wait()

                # Get stdout and stderr
                out_str = list(
                    map(lambda s: s.decode("utf-8"),
                        test_process.stdout.readlines()))
                error_str = list(
                    map(lambda s: s.decode("utf-8"),
                        test_process.stderr.readlines()))

                # Save the test state
                self.state = {
                    'stdout_lines':
                    sum(len(line.strip()) for line in out_str),
                    'stderr_lines':
                    sum(len(line.strip()) for line in error_str),
                    'caramel_stderr':
                    caramel_state['stderr'],
                    'caramel_stderr_lines':
                    caramel_state['stderr_lines'],
                    'gcc_stdout_lines':
                    sum(len(line.strip()) for line in gcc_stdout),
                    'gcc_stderr_lines':
                    sum(len(line.strip()) for line in gcc_stderr),
                    'correct_stdout':
                    out_str == gcc_stdout,
                    'return_code':
                    test_process.returncode,
                    'time':
                    time() - start_time
                }
                if self.state['stderr_lines'] != 0:
                    logger.warn(
                        'Unhandled: the test program wrote on stderr. Ignoring.'
                    )

                # Determine if unexpected errors, or successes, occurred
                errors = not self.state['correct_stdout']
                self.succeeded = errors if self.should_fail else not errors

                # Feed our user
                if self.succeeded:
                    logger.info(
                        'Test {}'.format(self.display_name),
                        colored('succeeded.', color='green', attrs=['bold']),
                        colored('[%s]' % seconds_to_string(self.state['time']),
                                color='yellow'))
                else:
                    logger.info(
                        'Test {}'.format(self.display_name),
                        colored('failed #{}.'.format(
                            _return_code_to_str(test_process.returncode)),
                                color='red',
                                attrs=['bold']),
                        colored('[%s]' % seconds_to_string(self.state['time']),
                                color='yellow'))
                    failed_tests.append(self.display_name)
                    if open_gui_on_failure and not open_gui:
                        self.execute(open_gui=True, open_gui_on_failure=False)

                # Show stdout or stderr if asked
                if show_stdout or open_gui:
                    if self.state['stdout_lines'] == 0 and self.state[
                            'gcc_stdout_lines'] == 0:
                        print(colored('No stdout output.', attrs=['bold']))
                    else:
                        print('\n'.join([
                            '#' * 20,
                            colored('GCC stdout:', attrs=['bold']),
                            ''.join(gcc_stdout),
                        ]))
                        print('\n'.join([
                            colored('Caramel-compiled stdout:',
                                    attrs=['bold']),
                            ''.join(out_str),
                            '-' * 20,
                        ]))
                if show_stderr or open_gui:
                    if self.state['caramel_stderr_lines'] == 0 and self.state[
                            'gcc_stderr_lines'] == 0:
                        print(colored('No stderr output.', attrs=['bold']))
                    else:
                        print('\n'.join([
                            '#' * 20,
                            colored('GCC stderr:', attrs=['bold']),
                            colored(''.join(gcc_stderr), color='grey'),
                        ]))
                        print('\n'.join([
                            colored('Caramel stderr:', attrs=['bold']),
                            ''.join(self.state['caramel_stderr']),
                            '-' * 20,
                        ]))
        except FileNotFoundError:
            print("Caramel's stderr:")
            print(''.join(caramel_state['stderr']))
            exit(1)
        os.chdir(initial_cwd)
Ejemplo n.º 29
0
 def trace(self, *message):
     if self.level >= LoggerLevel.TRACE:
         print(colored('[trace]', color='magenta', attrs=['bold']),
               colored(' '.join(map(str, message)), color='magenta'))
Ejemplo n.º 30
0
def fullfilled(config):
    # see end of eclipsify_gen_project.py for how this is called
    if not config.package:
        print(colored("Package name must not be empty", 'red'))
        return False
    return True