In [1]:
import os
import glob

Create Node Hierarchy


In [74]:
root_path = '/Users/rljacobson/Google Drive/Development/Mathematica-IntelliJ-Plugin/src/de/halirutan/mathematica/lang/psi/api/'

In [75]:
lst = glob.glob(root_path + '**/*.java', recursive=True)

In [77]:
# Cut off root_path and extension.
def remove_ends(text, prefix, suffix):
    if prefix:
        if text.startswith(prefix):
            text = text[len(prefix):]
    if suffix:
        if text.endswith(suffix):
            text = text[:-len(suffix)]
    return text

lst = [remove_ends(t, root_path, '.java') for t in lst]

In [79]:
removals = ['MathematicaPsiFile', 
            'OperatorNameProvider', 
            'graph/UndirectedEdge', 
            'StringifiedSymbol']
for t in removals:
    lst.remove(t)

In [81]:
replacements = {'lists/MList': 'lists/List', 'string/MString': 'string/String'}

for i, name in enumerate(lst):
    if name in replacements:
        lst[i] = replacements[name]

In [47]:
dirs = set()
file_list = []
root_path = 'FoxySheep/AST/'

current_dir = root_path

for t in lst:
    parts = t.split('/')
    if len(parts) == 2:
        d, f = parts
        total_path = root_path + d
        if total_path != current_dir:
            dirs.add(d)
            file_list.append((d, total_path + '/__init__.py'))
            current_dir = total_path
        file_list.append((d, '{rp}{f}Node.py'.format(rp=root_path, f=t)))
    else:
        file_list.append((None, '{rp}{f}Node.py'.format(rp=root_path, f=t)))

In [71]:
class_template = """from AST import ASTNode


class {name}(ASTNode):
    pass

"""

AST_init_template = '\nfrom .{module} import {name}'

init_template = 'from .{name} import {name}\n'

AST_init_filename = 'FoxySheep/AST/__init__.py'

current_dir = None
current_py_init_file = AST_init_filename

with open(AST_init_filename, 'a') as init_file:
    current_py_init_file = None
    
    for (d, py_file_path) in file_list:
        # Get the class name without path.
        base_path, py_name = os.path.split(py_file_path)
        py_name = py_name[:-3]
        
        # Create the subdirectory if it does not exist.
        if current_dir != d:
            # Create the sub
            if not os.path.exists(base_path):
                os.makedirs(base_path)
                
            # Close previous init file if exists.
            if current_py_init_file and not current_py_init_file.closed:
                current_py_init_file.close()
                
            # Delete the current init file if exists.
            current_py_init_file_path = base_path + '/__init__.py'
            try:
                os.remove(current_py_init_file_path)
            except OSError:
                pass
            # Create new init file.
            current_py_init_file = open(current_py_init_file_path, 'w')
            current_dir = d
        
        # Create/overwrite the file.
        if py_name != '__init__':
            # Create a new python file
            with open(py_file_path, 'w') as py_file:
                py_file.write(class_template.format(name=py_name))
            # Append to init file.
            if current_py_init_file:
                current_py_init_file.write(init_template.format(name=py_name))
            # Also append to AST init file.
            if d is not None:
                module = '{d}.{name}'.format(d=d, name=py_name)
            else:
                module = py_name
            init_file.write(AST_init_template.format(module=module, name=py_name))
        
    # Close any open init files.
    if current_py_init_file and not current_py_init_file.closed:
        current_py_init_file.close()
        
    # Write a final newline at the end of the file.
    init_file.write('\n')
print('Done!')


Done!

In [54]:
glob.glob('./FoxySheep/AST/**/*.py', recursive=True)


Out[54]:
['./FoxySheep/AST/__init__.py',
 './FoxySheep/AST/ASTNode.py',
 './FoxySheep/AST/Functions.py']

Write init function


In [2]:
txt="""identifier: str,
                 own_values: list = None,
                 down_values: list = None,
                 up_values: list = None,
                 default_values: list = None,
                 options: set = None,
                 attributes: set = None,
                 messages: set = None"""
lst = txt.split('\n')
lst = [t.strip() for t in lst]
lst = [t.split(' =')[0] for t in lst]
lst = [t.split(': ') for t in lst]
lst


Out[2]:
[['identifier', 'str,'],
 ['own_values', 'list'],
 ['down_values', 'list'],
 ['up_values', 'list'],
 ['default_values', 'list'],
 ['options', 'set'],
 ['attributes', 'set'],
 ['messages', 'set']]

In [4]:
init_txt = """self._{name} \t= {name}"""

for name, typename in lst:
    print(init_txt.format(name=name, typename=typename))


self._identifier 	= identifier
self._own_values 	= own_values
self._down_values 	= down_values
self._up_values 	= up_values
self._default_values 	= default_values
self._options 	= options
self._attributes 	= attributes
self._messages 	= messages

In [ ]: