Creating a .dot text file from list of libraries and their depths

16 views Asked by At

I have the following python code to create a text/dot file from a list of libraries in a format specified at the bottom.

def generate_dot(tree_list):
    stack = []
    last_base_library = None
    
    for item in tree_list:
        depth = item.count('-')
        library_name = item.strip('-').strip()

        while stack and stack[-1][0] >= depth:
            stack.pop()

        if not stack:
            # If it's a new base library, create a new file
            if last_base_library:
                with open(f"{last_base_library.replace(' ', '_')}.txt", "a") as dot_file:
                    dot_file.write("}\n")
            filename = f"{library_name.replace(' ', '_')}.txt"
            with open(filename, "w") as dot_file:
                dot_file.write("digraph Tree {\n")
                dot_file.write(f' {library_name};\n')
            last_base_library = library_name
        
        if stack:
            parent_depth, parent_name = stack[-1]
            dot_code = f' {" " * parent_depth}{parent_name} -> {" " * depth}{library_name};\n'
            filename = f"{stack[0][1].replace(' ', '_')}.txt"
            with open(filename, "a") as dot_file:
                dot_file.write(dot_code)

        stack.append((depth, library_name))
    
    # Close the last opened file
    if last_base_library:
        with open(f"{last_base_library.replace(' ', '_')}.txt", "a") as dot_file:
            dot_file.write("}\n")

# Example usage:
tree_list = ["-Library1", "--SubLibrary1", "---SubSubLibrary1", "-Library2", "--SubLibrary2", "-Library3"]
generate_dot(tree_list)

If it isn't clear, I'm taking the dashes as the "depth" value for each of the libraries and using that to create the (properly formatted) dot/text file. Then when there is a new "base" library, a new text file will be created for that library. I'm getting pretty close, but having issues with adding the closing brackets. No matter where I try to add the line to write the last closing bracket, too many brackets are being added or in the wrong place.

Any tips to fix this code so it gives me the expected output?

Example output:

digraph Tree{
Library2;
}
Library2 -> SubLibrary2;
}
}

Desired output:

digraph Tree{
Library2;
Library2 -> SubLibrary2;
}

Any help is appreciated, thank you

0

There are 0 answers