Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
5.4 kB
1
Indexable
Never
#! usr/bin/python3

import os
import sys
import subprocess
from argparse import ArgumentParser
from pathlib import Path


target = Path.home() / ".goto.paths"
bad_paths = [target.root, '/', 'c:/', 'C:/']


parser = ArgumentParser(description="Go to and in directories specified v1")

parser.add_argument("--addpath", "-ap", nargs="+",
                    help="add a path to the navigation tree")

parser.add_argument("--verbose", "-v",
                    help="verbose output",
                    action="store_true")

parser.add_argument("directory", nargs="?",
                    help="enter a directory to go to")

args = parser.parse_args()
if args.verbose: print(args)


if args.directory and args.addpath:
    print("goto.py: error: cannot specify both directory and --addpath")
    quit()


class Dir: ... # forward declaration for __init__ typehint 
class Dir:
    def __init__(self, title: str, parent: Dir or None, depth: int):
        self.title   = title
        self.parent  = parent
        self.content = []
        self.depth   = depth

    def add_dir(self, dir: str, depth: int):
        self.content.append(Dir(dir, self, depth))

    def get_dir(self, dir: str): # fix
        return [c for c in self.content if c.title == dir][0]

class NavigationTree:
    def __init__(self, trees):
        self.trees = trees
    
    def traverse_trees(self) -> print:
        print(self.trees)
        for i, root in enumerate(self.trees):
            print(f"{root.title}/")
            self.traverse_dirs(root)
            print()
    
    def traverse_dirs(self, dir: Dir, width=0) -> print:
        padding = (" " * width) + (" " * len(dir.title))
        for d in dir.content:
            if d.content:
                print(f"{padding}{d.title}/")
                self.traverse_dirs(d, width+len(dir.title))
            else:
                print(f"{padding}{d.title}")
                
    def add_path(self, dir: str) -> bool:
        if '/' in dir or '\\' in dir:
            dir = Path(dir)
        else:
            dir = Path(os.getcwd()) / dir
        
        if os.path.exists(dir):
            self.emplace(dir)
            return True

        return False

    def goto(self, dir: str):
        subprocess.run(["cd", self.get_path(dir)])


def parse_f_goto_paths(f_content: str) -> NavigationTree:
    trees   = []; tree = None; current_dir = None;
    sources = []; src  = ""

    start = True
    finding_src = False
    parsing_dir = False; dir = ""; depth = 0

    if args.verbose: s = f = p = False

    for char in f_content:
        if char in ('\n', '\t', '\r', ' '): continue
        #print(char, end='')
        if start:
            if args.verbose and not s: print("Starting parse"); s = not s
            if char != ':': continue
            start, finding_src = finding_src, start
        elif finding_src:
            if args.verbose and not f: print("Finding root"); f = not f
            if char != ':': src += char; continue
            if args.verbose: print(f"Root found: {src}")
            tree = Dir(src, None, depth); current_dir = tree
            finding_src, parsing_dir = parsing_dir, finding_src
        elif parsing_dir:
            if args.verbose and not p: print("Parsing tree"); p = not p
            if char != ';': # match case block
                if char == '/':
                    if args.verbose: print(f"{dir}/")
                    depth += 1
                    current_dir.add_dir(dir, depth); current_dir = current_dir.get_dir(dir)
                    dir = ""
                elif char == '\\':
                    if args.verbose: print(f"{dir}\\")
                    depth -= 1
                    current_dir = current_dir.parent
                    dir = ""
                elif char == ',':
                    if args.verbose: print(f"{dir},")
                    current_dir.add_dir(dir, depth)
                    dir = ""
                else:
                    dir += char
            else:
                if dir: print(f"goto.py: error: bad formatting in file '{target}', missing token after directory name"); quit() # skip tree or quit program?
                if args.verbose: print("Parse complete"); s = f = p = False
                trees.append(tree)
                dir = ""
                src = ""
                parsing_dir, start = start, parsing_dir

    if args.verbose: sentence_context = "tree" if len(trees) == 1 else "trees"; print(f"Found {len(trees)} complete {sentence_context}")
    rieturn NavigationTree(trees)

    print()


def setup() -> NavigationTree:
    if not os.path.exists(target):
        if args.verbose: print("Couldn't find " + str(target) + ", creating..")
        with open(target, "w") as f: ...
        return NavigationTree(None)
    else:
        if args.verbose: print(str(target) + " found")
        with open(target, "r") as f:
            return parse_f_goto_paths(f.read())


def goto(navtree: NavigationTree, dir: str) -> bool:
    dir = Path(dir)

    if not os.path.exists(dir) or dir in bad_paths:
        return False

    #with open(target, 
        
    return True


def main():
    navtree = setup()
    if args.verbose: navtree.traverse_trees()
    
    if args.directory:
        goto(navtree, args.directory)
    elif args.addpath:
        for path in args.addpath: navtree.add_path(path)
        navtree.serialize()

    if args.verbose: print("end\n")


if __name__ == "__main__":
    main()
Leave a Comment