How to port existing code ?ΒΆ

You can use a simple directory walking script like this to generate a single cog file for the entire source tree. Better still just port important files first.

Todo

  • Split comments

Here is a sample ruby script,

from PyInquirer import prompt, Separator, print_json
import sys
import os
import glob

def preamble():
  cog =  """
@<
import cog
import os
import re
from jinja2 import Environment, BaseLoader

Template = Environment(loader=BaseLoader, block_start_string="%%{", block_end_string="%%}",variable_start_string="%%", variable_end_string="%%")

def write_file(name, fn):
    global _
    code = Template.from_string(_[name]).render(_=_)
    os.makedirs(os.path.dirname(fn), exist_ok=True)
    os.system("safe-rm " + fn)
    f = open(fn, "w")
    f.write(code)
    f.close()

_ = {}
@>
@@
"""

  return cog


confirm = [
    {
        'type': 'confirm',
        'message': 'Do you want to import ?',
        'name': 'continue',
        'default': True,
    }
]

questions = [
    {
        'type': 'input',
        'name': 'import_path',
        'message': 'Path of file or directory to import',
    },
    {
        'type': 'input',
        'name': 'to_path',
        'message': 'Destination path',
    }
]

def is_binary(path):
    textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
    is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
    return is_binary_string(open(path, 'rb').read(1024))

def import_file(source_filename, to):
    base = os.path.basename(source_filename)
    split_tup = os.path.splitext(base)
    lang = split_tup[1][1:len(split_tup[1])]
    with open(source_filename) as f:
        file_data = f.read()

        cog =  """
## {base}

```{{code-block}} {lang}
---
force: true
---
@<

_["{base}"] = cog.previous
cog.out(_["{base}"])
write_file("{base}", "{to}/{base}")
@>
{file_data}
@@
```
    """
    return cog.format(base=base, lang=lang, file_data=file_data, to=to)

imported_code = ""

while(1):
    if prompt(confirm)["continue"]:
        answers = prompt(questions)
        path = answers["import_path"]
        to = answers["to_path"]
        if "*" in path:
            for file_path in glob.glob(path):
                print("Importing file " + file_path)
                imported_code += import_file(file_path, to)
        elif os.path.exists(path):
            print("Found path")
            isFile = os.path.isfile(path)
            if isFile:
                print("Importing file " + path)
                imported_code += import_file(path, to)
            else:
                isDirectory = os.path.isdir(path)
                if isDirectory:
                    print("Importing directory " + path)
                    for root, subdirs, files in os.walk(path):
                        for filename in files:
                            file_path = os.path.join(root, filename)
                            if filename in [".", "..", ".git", ".DS_Store"]:
                                continue
                            if is_binary(file_path):
                                continue
                            print("Importing file " + file_path)
                            imported_code += import_file(file_path, to)
                else:
                    print("Invalid path")
    else:
        print("Writing import.cog")
        with open("import.cog", "w") as f:
            f.write(preamble())
            f.write(imported_code)
        sys.exit(1)