Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added IndentedTextImporter, compatible docstrings, & nose tests #155

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

LionKimbro
Copy link

No description provided.

The tests are now shorter, more direct, and do not rely on the presentation system.
@coveralls
Copy link

Coverage Status

Coverage decreased (-0.3%) to 99.43% when pulling 4db02fe on LionKimbro:master into d63289b on c0fec0de:master.

@lverweijen
Copy link

lverweijen commented Jul 4, 2023

I would be interested in this.

Some features I would want:

  • Make indentchar flexible. So not only space, but should also be able to use tab, "." or any other character
  • Provide your own node-class to use
  • Similar functionality to export to an indented tree-file (which does not write the root or this should be made an option)

Here sample implementations:

def from_indented(file, indent=' ', node_factory=anytree.Node):
    """
    node_factory receives one argument and should create a node
    indent should be "    " if exactly 4 spaces are used
    """

    # Each line consists of indent and code
    pattern = re.compile(rf"^(?P<prefix>({re.escape(indent)})*)(?P<code>.*)")

    root = node_factory()
    stack = [root]

    for line in file:
        match = pattern.match(line)
        prefix, code = match['prefix'], match['code']
        depth = len(prefix) // len(indent)
        node = node_factory(code)
        node.parent = stack[depth]

        # Place node as last item on index depth + 1
        del stack[depth + 1:]
        stack.append(node)

    return root


def to_indented(root, file, indent=" ", depth=0, formatter=str):
    """
    formatter is how the node should be displayed, maybe lambda x: x.name is also a good default
    formatter should be the inverse of node_factory in the previous function
    depth is the beginning level, normally 0 meaning no indent for first depth-level
    root is not included in the output
    """
    for child in root.children:
        file.write(indent * depth + formatter(child) + '\n')
        to_indented(child, file, indent=indent, depth=depth + 1, formatter=formatter)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants