Пример #1
0
def preprocess(file_contents, dappfile):
    cog = cogapp.Cog()
    cog.options.defines = dappfile.get('preprocessor_vars', {})

    try:
        return cog.processString(file_contents)

    except cogapp.cogapp.CogError:
        print(file_contents, file=sys.stderr)
        raise
Пример #2
0
def _runcog(options, uncog=False):
    """Common function for the cog and runcog tasks."""

    #options.order('cog', 'sphinx', add_rest=True)
    cog = cogapp.Cog()
    if uncog:
        cog.options.bNoGenerate = True
    cog.options.bReplace = True
    cog.options.bDeleteCode = options["cog"].get("delete_code", False)
    includedir = options["cog"].get('includedir', None)
    if includedir:
        markers = options["cog"].get("include_markers")

        include = Includer(
            includedir,
            cog=cog,
            include_markers=options["cog"].get("include_markers"))
        # load cog's namespace with our convenience functions.
        cog.options.defines['include'] = include
        cog.options.defines['sh'] = _cogsh(cog)

        cli_includer = CliExample(includedir, cog=cog, include_markers=markers)
        cog.options.defines["cli_example"] = cli_includer

    cog.options.defines.update(options["sphinx"].get("defines", {}))

    cog.options.sBeginSpec = options["cog"].get('beginspec', r'{{{cog')
    cog.options.sEndSpec = options["cog"].get('endspec', r'}}}')
    cog.options.sEndOutput = options["cog"].get('endoutput', r'{{{end}}}')

    basedir = options["sphinx"].get('basedir', None)
    if basedir is None:
        basedir = Path(options["sphinx"].get('docroot', "docs")) / \
                  options["sphinx"].get('sourcedir', "")
    basedir = Path(basedir)

    pattern = options["sphinx"].get("pattern", "**/*.rst")
    if pattern:
        files = basedir.glob(pattern)
    else:
        # FIXME: This cannot happen since pattern is never None
        files = basedir.glob("**/*")

    for f in sorted(files):
        cog.processOneFile(str(f))
Пример #3
0
def _runcog(options, uncog=False):
    """Common function for the cog and runcog tasks."""

    eyed3_info()

    import cogapp
    options.order('cog', 'sphinx', add_rest=True)
    c = cogapp.Cog()
    if uncog:
        c.options.bNoGenerate = True
    c.options.bReplace = True
    c.options.bDeleteCode = options.get("delete_code", False)
    includedir = options.get('includedir', None)
    if includedir:
        markers = options.get("include_markers")

        include = Includer(includedir, cog=c,
                           include_markers=options.get("include_markers"))
        # load cog's namespace with our convenience functions.
        c.options.defines['include'] = include
        c.options.defines['sh'] = _cogsh(c)

        cli_includer = CliExample(includedir, cog=c, include_markers=markers)
        c.options.defines["cli_example"] = cli_includer

    c.options.defines.update(options.get("defines", {}))

    c.sBeginSpec = options.get('beginspec', '[[[cog')
    c.sEndSpec = options.get('endspec', ']]]')
    c.sEndOutput = options.get('endoutput', '[[[end]]]')

    basedir = options.get('basedir', None)
    if basedir is None:
        basedir = path(options.get('docroot', "docs")) / \
                  options.get('sourcedir', "")
    basedir = path(basedir)

    pattern = options.get("pattern", "*.rst")
    if pattern:
        files = basedir.walkfiles(pattern)
    else:
        files = basedir.walkfiles()
    for f in files:
        dry("cog %s" % f, c.processOneFile, f)
Пример #4
0
    def update_file(self,
                    template,
                    targetFile,
                    options=[],
                    commentsPrefix="//"):
        print("Creating file %s %s" % (self.gendir, targetFile))
        cog_file = os.path.join(self.gendir, targetFile)
        #		cog_file = os.path.join('.', targetFile)
        if not os.path.exists(cog_file):
            print("Creating file %s" % cog_file)
            if not os.path.exists(os.path.dirname(cog_file)):
                os.makedirs(os.path.dirname(cog_file))
            template_abs = os.path.join(self.template_dir, self.profile,
                                        template)
            shutil.copyfile(template_abs, cog_file)

        backup_cog_file = "%s/.cog/%s" % (self.gendir, targetFile)
        if self.erase_cog:
            if os.path.exists(backup_cog_file):
                print(
                    "Will not erase cog code, backup file (%s) for source already exists."
                    % backup_cog_file)
                sys.exit(1)
            else:
                if not os.path.exists(os.path.dirname(backup_cog_file)):
                    os.makedirs(os.path.dirname(backup_cog_file))
                shutil.copy(cog_file, backup_cog_file)

        cog = cogapp.Cog()
        cog_options = ["cog", "--markers=%s" % self.markers] + options
        if self.erase_cog:
            cog_options += ["-d", "-o", cog_file, backup_cog_file]
        else:
            cog_options += ["-r", "-e"]
            if commentsPrefix is not None:
                cog_options += [
                    "-s",
                    " %s%s" % (commentsPrefix, self.gen_code_suffix)
                ]
            cog_options += [cog_file]

        cog.main(cog_options)
Пример #5
0
    print(f"ERROR: failed to compile with faust2teensy (status code {err})", file=sys.stderr)
    sys.exit(1)

# Copy to now location
os.system("unzip FaustInstrument.zip")
with ZipFile('FaustInstrument.zip', 'r') as FaustZip:
    FaustZip.extractall()

for faustFile in glob.glob(f"FaustInstrument{os.sep}FaustInstrument.*"):
    shutil.copy(faustFile, "src")

# Generating JSON
err = os.system("faust -json FaustInstrument.dsp")
if err:
    print(f"ERROR: failed to generate json with faust -json (status code {err})", file=sys.stderr)
    sys.exit(1)

shutil.copy("FaustInstrument.dsp.json", "src")

# Running COG Code Genraten
cog = cogapp.Cog()
cog.processFile(f"src{os.sep}main.cpp", f"src{os.sep}main_cog.cpp")

os.remove(f"src{os.sep}main.cpp")
shutil.move(f"src{os.sep}main_cog.cpp", f"src{os.sep}main.cpp")

# Cleanup
os.remove("FaustInstrument.zip")
shutil.rmtree("FaustInstrument")
os.remove("FaustInstrument.dsp.json")
Пример #6
0
 def __init__(self, schema, config):
     self.schema = schema
     self.cfg = config
     self.genApp = cogapp.Cog()
     self.genApp.options.bDeleteCode = True
Пример #7
0
def main():
    global guid, projects, local

    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
    parser.add_argument("--solution-name", metavar="NAME")
    parser.add_argument("--last-problem",
                        type=problem_number,
                        metavar="ALNUM",
                        help="""
        can be either alphabetical letter or number
    """)
    parser.add_argument("--cog",
                        nargs=argparse.REMAINDER,
                        default=[],
                        help="""
        custom arguments that are passed to Cog
    """)
    parser.add_argument("solution", type=ensure_existence)
    parser.add_argument("vcxproj", type=ensure_existence)
    parser.add_argument("vcxproj_filters",
                        type=ensure_existence,
                        metavar="vcxproj-filters")
    parser.add_argument("source", type=ensure_existence)
    parser.add_argument("project_name", metavar="project-name")
    parser.add_argument("source_name", metavar="source-name")
    parser.add_argument("input_name", metavar="input-name")
    parser.add_argument("local",
                        help="""
        local project definition
    """)
    parser.add_argument("definitions", type=ensure_existence)

    args = parser.parse_args()

    if args.solution_name is None:
        args.solution_name = input("Solution name: ")
    if args.last_problem is None:
        args.last_problem = problem_number(input("Last problem: "))

    local = args.local
    custom = ' '.join(map(shlex.quote, args.cog))

    try:
        os.mkdir(args.solution_name)
    except FileExistsError:
        for e in os.listdir(args.solution_name):
            entry = os.path.join(args.solution_name, e)
            if os.path.isdir(entry):
                shutil.rmtree(entry)
            elif os.path.isfile(entry):
                os.remove(entry)

    definitions = []
    with open(args.definitions) as f:
        for line in f:
            line = line.strip()
            if not line.startswith((';', '#', "//")) and '=' in line:
                definitions.append(line)

    projects = []
    with temp_file() as (cog_cmd, cog_cmd_name):
        for i in range(args.last_problem + 1):
            d = {
                "upper": chr(ord('A') + i),
                "lower": chr(ord('a') + i),
                "number": str(i + 1),
                "number0": str(i),
                "local": local,
            }
            name = args.project_name.format_map(d)
            g = generate_guid()
            path = os.path.join(args.solution_name, name)
            with contextlib.suppress(FileExistsError):
                os.mkdir(path)
            input_name = args.input_name.format_map(d)
            with open(os.path.join(path, input_name), "w") as f:
                print(file=f)
            source_name = args.source_name.format_map(d)
            s = io.StringIO()
            for kv in definitions:
                s.write(" -D")
                s.write(kv.format_map(d))
            print("%s %s%s -o'%s'" % (args.source, custom, s.getvalue(),
                                      os.path.join(path, source_name)),
                  file=cog_cmd)
            s = os.path.join(path, name + ".vcxproj")
            print(
                "%s %s -Dname=%s -Dguid=%s -Dsource_file='%s' -Dinput_file='%s' -o'%s'"
                % (args.vcxproj, custom, name, g, source_name, input_name, s),
                file=cog_cmd)
            s = os.path.join(path, name + ".vcxproj.filters")
            print("%s %s -Dsource_file='%s' -Dinput_file='%s' -o'%s'" %
                  (args.vcxproj_filters, custom, source_name, input_name, s),
                  file=cog_cmd)
            projects.append(dict(name=name, guid=g))

        guid = generate_guid()
        print("%s %s -o'%s'" %
              (args.solution, custom,
               os.path.join(args.solution_name, args.solution_name + ".sln")),
              file=cog_cmd)

        cog_cmd.flush()
        cogapp.Cog().main(sys.argv[:1] + shlex.split(custom) +
                          ["-de", '@' + cog_cmd_name])
Пример #8
0
prevwd = ''
cwd = os.getcwd()
while cwd != prevwd:
    if os.path.isdir('.git'):
        break
    prevwd = cwd
    os.chdir('..')
    cwd = os.getcwd()
if cwd == prevwd:
    print 'Cannot find aqsis source root directory.  You must run the codgen from somewhere inside the tree.'
    sys.exit(1)

print 'Searching for source files...'
forceSelected = None
if len(sys.argv) > 1:
    forceSelected = sys.argv[1:]
filesToCog = findFilesToCog(searchDirs, forceSelected)

for fileName in filesToCog:
    argv = ['run_codegen.py',
            '-r',                              # run in place
            '-I', cogUtilsPath,                # location of utilities
            '-D', 'riXmlPath=%s'%(riXmlPath,), # location of ri.xml
            fileName]                          # file to cog
    # Run cog directly via the cogapp module rather than through the cog.py
    # wrapper.
    cogapp.Cog().main(argv)


# vi: set et: