예제 #1
0
def cli():
    parser = argparse.ArgumentParser()
    cli_util.add_debug_args(parser)
    parser.add_argument(
        "-d",
        "--dir",
        help="Path to zettelkasten directory or. Search term for zettelkasten"
        " directory (e.g. part of path).",
        required=False,
    )
    parser.add_argument(
        dest="name",
        help="Name",
    )
    add_action_option(parser)
    args = parser.parse_args()
    cli_util.default_arg_handling(args)
    if args.dir:
        args.dir = guess_zk_dir(args.dir)
        if not args.dir:
            logger.critical("Could not find unique zk directory. Exit.")
            sys.exit(117)
    else:
        args.dir = Path(os.getcwd())
    new_path = args.dir / f"{args.name}_{generate_zid()}.md"
    logger.debug(f"Touching {new_path.resolve()}")
    new_path.touch()
    logger.info(f"Created {new_path.resolve()}.")
    if not args.action:
        pyperclip.copy(str(new_path.resolve()))
        logger.info(f"Path has been copied to clipboard.")
    else:
        handle_action_on_path(args.action, new_path)
        pyperclip.copy(Note.get_nid(new_path))
        logger.info(f"ID has been copied to clipboard.")
예제 #2
0
def get_search_results(search_dirs: List[Path], search_term: str) -> List[Path]:
    sb_params = [
        "find",
    ]
    for d in search_dirs:
        sb_params.append(str(d))
    if "*" not in search_term:
        if not search_term.endswith(".md"):
            search_term = f"*{search_term}*.md"
        else:
            search_term = f"*{search_term}.md"
    else:
        if search_term.endswith("*"):
            search_term += ".md"
    logger.debug(f"Search term: '{search_term}'.")
    sb_params.extend(
        ["-type", "f", "-not", "-wholename", "*/.git*", "-name", search_term]
    )

    opt = subprocess.check_output(sb_params, universal_newlines=True,).strip()

    if not opt.replace("\n", ""):
        return []

    return [Path(path_str) for path_str in opt.split("\n")]
예제 #3
0
def handle_action_on_path(action: str, path: Path) -> None:
    logger.info(f"Running command on {path.name}.")

    if "{file}" not in action:
        action = action + " {file}"

    command = action.format(file=path)
    logger.debug(f"Running in system: '{command}'")
    subprocess.run(command, shell=True)
예제 #4
0
def edit(notespec: str):
    if request.method == 'GET':
        logger.debug(f"Opening in the editor {notespec}")
        content = Path(zk[notespec].path).read_text()
        url = "/edit/" + notespec
        return render_template("edit.html", value = content, id= url)
    elif request.method == 'POST':
        new_version = json.loads(request.json)
        print(new_version)
        logger.debug(f"Save from the editor {notespec}")
예제 #5
0
def open(notespec: str):
    logger.debug(f"Opening {notespec}")
    if notespec.isnumeric():
        note = zk[notespec]
    else:
        note = zk.get_by_path(notespec)
    converted = pandoc_converter.convert(note)
    dot = "".join(dotgraph_html(zk, note))
    return render_template(
        "page.html", pandoc_output=converted, title=note.title, dot=dot,
    )
예제 #6
0
def search_lucky(search):
    search = Path(search).stem
    if search.startswith("."):
        logger.debug(f"Redirecting to {search[1:]}")
        # e.g. allows access the dashboard with .dashboard
        return redirect(f"/{search[1:]}")
    results = zk.search(search)
    if results:
        return redirect(f"/open/{results[0].nid}")
    else:
        return "No results"
예제 #7
0
def guess_zk_dir(inpt: Union[str, PurePath]) -> Optional[Path]:
    if Path(inpt).is_dir():
        return Path(inpt).resolve()
    else:
        dirs = get_zk_base_dirs_from_env()
        results = [d for d in dirs if inpt in str(d)]
        if len(results) == 0:
            logger.warning("Could not guess right zk directory.")
            return None
        elif len(results) == 1:
            logger.debug(f"Guessed zk directory from search term {inpt} to be "
                         f"{results[0]}.")
            return Path(results[0])
        else:
            logger.warning("Too many results for zk directory.")
            return None
예제 #8
0
def default_arg_handling(args: argparse.Namespace) -> None:
    if hasattr(args, "log"):
        # Has to come first!
        abbrev2loglevel = {
            "d": logging.DEBUG,
            "i": logging.INFO,
            "w": logging.WARNING,
            "e": logging.ERROR,
            "c": logging.CRITICAL,
        }
        logger.setLevel(abbrev2loglevel[args.log])
    if hasattr(args, "input"):
        if not args.input:
            args.input = get_zk_base_dirs_from_env()
            dirs = ", ".join(list(map(str, args.input)))
            logger.debug(f"Got zk directories {dirs} from env.")
        if not args.input:
            logger.critical(
                "Zettelkasten input directories were neither specified by "
                "command line, nor set in the ZK_HOME environment variable. "
                "Exit. ")
            sys.exit(111)