Exemple #1
0
def get_render_callable(engine_name, displays_on, src, filename=None):
    """ Returns a function that takes a template source and kwargs. """

    # See the discussion here re: `displays_on` -- http://bit.ly/JRqbRw

    directory = None
    if filename:

        if SEP not in filename and (not ALTSEP or ALTSEP not in filename):
            filename = _get_dotted_filename(engine_name, filename)

        directory = os.path.dirname(filename)

    if engine_name == 'mako':
        import mako.template
        args = dict(text=src,
                    imports=["from markupsafe import escape_silent"],
                    default_filters=['escape_silent'])

        if filename:
            args['filename'] = relpath(filename, directory)
            from mako.lookup import TemplateLookup
            args['lookup'] = TemplateLookup(directories=[directory])

        tmpl = mako.template.Template(**args)
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name in ('genshi', 'genshi_abs'):
        import genshi.template
        args = dict(source=src, )

        if filename:
            args['loader'] = genshi.template.TemplateLoader([
                genshi.template.loader.directory(directory),
            ])

        tmpl = genshi.template.MarkupTemplate(**args)
        return lambda kwargs: Markup(''.join(
            tmpl.generate(**kwargs).serialize('xhtml')))

    elif engine_name == 'jinja':
        import jinja2
        from jinja_util import htmlbools
        env = jinja2.environment.Environment(autoescape=True)
        env.filters['htmlbools'] = htmlbools
        tmpl = env.from_string(src, template_class=jinja2.Template)
        tmpl.filename = filename
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name == 'kajiki':
        import kajiki
        tmpl = kajiki.XMLTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl(kwargs).render())

    elif engine_name == 'chameleon':
        import chameleon
        tmpl = chameleon.PageTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl.render(**kwargs).strip())

    raise NotImplementedError("Unhandled engine")
Exemple #2
0
def read(*path, headers=None):
	csvpath = util.relpath(*path)

	rows = []

	def nextrow(f):
		line = f.readline()
		if line == '':
			return None
		return line.rstrip('\n').split(',')

	def getrows(f):
		while True:
			row = nextrow(f)
			if row is None: return
			yield row

	with open(csvpath) as f:
		if headers is None:
			headers = nextrow(f)

		for row in getrows(f):
			rows.append(row)

	return headers, rows
Exemple #3
0
def get_render_callable(engine_name, displays_on, src, filename=None):
    """ Returns a function that takes a template source and kwargs. """

    # See the discussion here re: `displays_on` -- http://bit.ly/JRqbRw

    directory = None
    if filename:

        if SEP not in filename and (not ALTSEP or ALTSEP not in filename):
            filename = _get_dotted_filename(engine_name, filename)

        directory = os.path.dirname(filename)

    if engine_name == 'mako':
        import mako.template
        args = dict(text=src)

        if filename:
            args['filename'] = relpath(filename, directory)
            from mako.lookup import TemplateLookup
            args['lookup'] = TemplateLookup(
                directories=[directory])

        tmpl = mako.template.Template(**args)
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name in ('genshi', 'genshi_abs'):
        import genshi.template
        args = dict(
            source=src,
        )

        if filename:
            args['loader'] = genshi.template.TemplateLoader([
                genshi.template.loader.directory(directory),
            ])

        tmpl = genshi.template.MarkupTemplate(**args)
        return lambda kwargs: Markup(
            ''.join(tmpl.generate(**kwargs).serialize('xhtml'))
        )

    elif engine_name == 'jinja':
        import jinja2
        tmpl = jinja2.Template(src)
        tmpl.filename = filename
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name == 'kajiki':
        import kajiki
        tmpl = kajiki.XMLTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl(kwargs).render())

    elif engine_name == 'chameleon':
        import chameleon
        tmpl = chameleon.PageTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl.render(**kwargs).strip())

    raise NotImplementedError("Unhandled engine")
Exemple #4
0
def time(options, program, *args):
    command = runCommand(program, args)
    log.debug('Running "{}"', ' '.join(command))

    if findSuffix("interact") != "interact":
        iwrapper = util.relpath("bin\\coact.exe")
        if not os.path.exists(iwrapper):
            raise PException(
                'Cannot run unteractive problem without "coact.exe" wrapper')
        command[0:0] = [iwrapper, "2000", "67108864"] + runCommand("interact")

    x64 = platform.machine() == "AMD64"
    wrapper = util.relpath("bin\\run{}.exe".format("64" if x64 else ""))
    if os.path.exists(wrapper):
        command[0:0] = [wrapper] + defaults.runOptions + [
            "" if options.output else "-q"
        ]
    return executeAndLog(*command)
Exemple #5
0
    def queueSrcFile(self, host, path):
        """Queue a file to be sent to the given host.  path should be
        relative to the module of the calling class.  Returns a
        relative path that may be used to refer to the file on the
        remote host once it has been transferred."""

        # Convert the module-relative path into an absolute path
        #
        # XXX This will fall apart if a superclass tries to use
        # queueSrcFile, since we'll see the module of the subclass.
        modBase = os.path.dirname(
            os.path.realpath(sys.modules[self.__module__].__file__))
        abspath = os.path.join(modBase, path)
        # Make sure it exists
        os.stat(abspath)
        # Add it to the queue
        self.__getQueue(host).append(abspath)
        return relpath(abspath)
Exemple #6
0
    def queueSrcFile(self, host, path):
        """Queue a file to be sent to the given host.  path should be
        relative to the module of the calling class.  Returns a
        relative path that may be used to refer to the file on the
        remote host once it has been transferred."""

        # Convert the module-relative path into an absolute path
        #
        # XXX This will fall apart if a superclass tries to use
        # queueSrcFile, since we'll see the module of the subclass.
        modBase = os.path.dirname(
            os.path.realpath(sys.modules[self.__module__].__file__))
        abspath = os.path.join(modBase, path)
        # Make sure it exists
        os.stat(abspath)
        # Add it to the queue
        self.__getQueue(host).append(abspath)
        return relpath(abspath)
Exemple #7
0
def main():
	print("gschichten ausm paulanergarten")

	args = sys.argv

	print("number of args:" + str(len(args)))
	print(str(args))


	#default sftmake config
	sftmake_path = os.path.dirname(os.path.realpath(__file__))
	defaultconf = conf_smfile.smfile_factory(sftmake_path +"/conf_default.py")
	defaultconf.run()
	print("default configuration:")
	print(defaultconf.data)


	smroot = util.get_smroot()
	#filetree = dirscanner.smtree(util.relpath(smroot))
	filetree = dirscanner.smtree(util.relpath(smroot))

	print(str(filetree))

	root_smfile_name = filetree.get_root_smfile()

	#create a smfile handle, may be python or smlang
	root_smfile = conf_smfile.smfile_factory(root_smfile_name)

	#read the root smfile
	root_smfile.run()
	#TODO: add config in root smfile which specifies the directories
	#      to be scanned.

	mainfileconf = root_smfile.data
	print("project main configuration:")
	print(mainfileconf)
from languages_util import *
import defaults
import util


def runTests(run):
    util.removeDirs("tests")
    os.mkdir("tests")
    return run()


languages = [
    javaSpecial("tests", "Java-based test generator", run=runTests),
    javaSpecial(
        "validator", "Java-based test validator",
        [util.relpath("testlib\\testlib4j.jar"),
         util.relpath("testlib")]),
    javaSpecial("check",
                "Java-based checker", [util.relpath("testlib\\testlib4j.jar")],
                addArgs=["ru.ifmo.testlib.CheckerFramework"]),
    javaSpecial("check", "Java-based checker"),
    compiled(".java", "Java", comments_c, ["javac", "-cp", ".", "{program}"],
             addArgs(lambda program: java(util.deleteSuffix(program), ["."]))),
    compiled(
        ".dpr", "Borland Delphi", comments_pascal,
        ["dcc32", "-m", "-cc", "-U" + util.relpath("testlib"), "{program}"]),
    compiled(".c",
             "C",
             comments_c,
             ["cl", "/O2", "-I" + util.relpath("testlib"), "{program}"],
             tempSuffixes=[".obj"]),
Exemple #9
0
 def relative_path(self, dir):
     if not os.path.isabs(dir): return dir
     dir = os.path.abspath(dir)
     project_dir = self.directory
     return util.relpath(dir, project_dir)
Exemple #10
0
parser_time_parent = argparse.ArgumentParser(add_help=False)
parser_time_parent.add_argument("-o",
                                "--output",
                                action="store_true",
                                help='show output of run/run64 wrapper')

parser_time = subparsers.add_parser('time',
                                    aliases='t',
                                    help='Runs program using "run.exe"',
                                    description="""
        Works like run subcommand, but execution is wrapped into
        "run.exe" or "run64.exe", if the corresponding wrapper file exists
        in "{}" directory), otherwise
        run is performed directly. It will wrap the run into coact/interact
        pair for interactive problems.
    """.format(util.relpath("")),
                                    parents=[parser_time_parent])
parser_time.add_argument('program', metavar='PROGRAM', help='program to run')
parser_time.add_argument('args',
                         metavar='ARG',
                         nargs='*',
                         help='program arguments')
parser_time.set_defaults(
    func=lambda options: time(options, options.program, *options.args))


def problem_check(options):
    return runAction(options, "check", checkTest)


parser_check_parent = argparse.ArgumentParser(add_help=False,
Exemple #11
0
 def relative_path(self, dir):
     if not os.path.isabs(dir): return dir
     dir = os.path.abspath(dir)
     project_dir = self.directory
     return util.relpath(dir, project_dir)
def get_render_callable(engine_name, displays_on, src, filename=None, inline=False):
    """ Returns a function that takes a template source and kwargs. """

    # See the discussion here re: `displays_on` -- http://bit.ly/JRqbRw

    directory = None
    if filename and not inline:
        if SEP not in filename and (not ALTSEP or ALTSEP not in filename):
            filename = _get_dotted_filename(engine_name, filename)

        directory = os.path.dirname(filename)

    if engine_name == 'mako':
        import mako.template
        args = dict(text=src, imports=["from markupsafe import escape_silent"],
                    default_filters=['escape_silent'])

        if directory:
            args['filename'] = relpath(filename, directory)
            from mako.lookup import TemplateLookup
            args['lookup'] = TemplateLookup(
                directories=[directory])

        tmpl = mako.template.Template(**args)
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name in ('genshi', 'genshi_abs'):
        import genshi.template
        args = dict(
            source=src,
        )

        if directory:
            args['loader'] = genshi.template.TemplateLoader([
                genshi.template.loader.directory(directory),
            ])

        tmpl = genshi.template.MarkupTemplate(**args)
        return lambda kwargs: Markup(
            ''.join(tmpl.generate(**kwargs).serialize('xhtml'))
        )

    elif engine_name == 'jinja':
        import jinja2
        from jinja_util import htmlbools
        env = jinja2.environment.Environment(autoescape=True)
        env.filters['htmlbools'] = htmlbools
        tmpl = env.from_string(src, template_class=jinja2.Template)
        tmpl.filename = filename
        return lambda kwargs: Markup(tmpl.render(**kwargs))

    elif engine_name == 'kajiki':
        import kajiki
        tmpl = kajiki.XMLTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl(kwargs).render())

    elif engine_name == 'chameleon':
        import chameleon
        tmpl = chameleon.PageTemplate(src, filename=filename)
        return lambda kwargs: Markup(tmpl.render(**kwargs).strip())

    raise NotImplementedError("Unhandled engine")