Ejemplo n.º 1
0
def main(*, cli_args: str = None):
    global log
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=__doc__),
        default_loglevel="WARNING",
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)

    bm = bookmarks.Bookmarks(args.file)
    log.info("bookmarks: %s", bm)
    recent = bookmarks.RecentlyUsed(RECENTLY_USED_FILE)

    if args.edit:
        editor = os.environ.get("EDITOR", "vim")
        os.execlp(editor, editor, args.file)
    elif args.add_recent:
        path = pathlib.Path(args.add_recent)
        if not path.is_absolute():
            path = pathlib.Path.home() / path
        if path in bm:
            recent.add(path.as_posix())
        else:
            log.info("%s is not in bookmarks, skip adding to recent paths list", path)
        return

    if not bm:
        raise DirsException("There are no bookmarks yet. --edit opens file in editor.")

    for fmt in bm.sorted_formatted(recent):
        print(fmt)
Ejemplo n.º 2
0
def main(*, cli_args: str = None):
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        default_loglevel="INFO",
        argp_kwargs=dict(description=__doc__),
    )
    global log
    log = logging.getLogger("tool")
    if args.check_clean:
        if not repo_is_clean():
            sys.exit(1)
        return
    settings = toml.load(args.pyproject)
    log.debug_obj(settings, "pyproject settings")

    fail_dirty = False
    if not repo_is_clean() and not args.dryrun:
        fail_dirty = True
        args.dryrun = True

    update_installer(INSTALLER, settings, args)
    meta = get_metadata(settings, args)
    write_package_metadata(meta, args)
    write_readme(meta, settings["tool"]["poetry"]["readme"], args)

    if fail_dirty:
        raise Error(
            "Did not write to any files since repo is dirty. "
            "Stash or commit any changes and try again."
        )
Ejemplo n.º 3
0
def fixup(*, cli_args: str = None, doc: str = None):
    global log
    args = hedgehog.init(
        _init_fixup,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=doc,
                         usage="%(prog)s [opts] [git-commit args]"),
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)
    lines = (common.git_command("log", "--oneline", "--decorate", "-n",
                                args.max_count).strip().splitlines())
    commits = [(line, line.split(maxsplit=1)[0]) for line in lines]
    log.debug_obj(commits, "Commits")
    menu = TerminalMenu(
        ("|".join(c) for c in commits),
        preview_command="git log -1 {}",
        cycle_cursor=False,
        preview_size=0.4,
        show_search_hint=True,
    )
    index = menu.show()
    if index is None:
        return
    log.debug("Selected index: %s, commit: %s", index, commits[index])

    git_args = [
        "commit",
        *args.remainder,
        args.commit_type,
        commits[index][1],
    ]
    common.print_git_command(git_args, f"   # ({commits[index][0]})")
    common.git_command(*git_args)
Ejemplo n.º 4
0
def preview(*, cli_args: str = None, doc: str = ""):
    """Select and print commit, show preview of "git show" in full screen."""
    global log
    args = hedgehog.init(
        _init_preview,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(
            description=doc,
            usage="%(prog)s [opts] [<revision range>] [[--] <path>...]",
        ),
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)
    git_args = [
        "log",
        "--oneline",
        "--decorate",
        "-n",
        args.max_count,
        *args.remainder,
    ]
    lines = common.git_command(*git_args).strip().splitlines()
    commits = [(line, line.split(maxsplit=1)[0]) for line in lines]
    log.debug_obj(commits, "Commits")

    def _preview_command(commit_id):
        if args.log_preview:
            return common.git_command("log", "-1", commit_id)
        return common.git_command(
            "show", "--color={}".format("always" if args.color else "never"),
            commit_id)

    menu = TerminalMenu(
        ("|".join(c) for c in commits),
        preview_command=_preview_command,
        cycle_cursor=False,
        preview_size=0.85,
        clear_screen=not args.print,
        show_search_hint=True,
    )
    index = menu.show()
    if index is None:
        return
    log.debug("Selected index: %s, commit: %s", index, commits[index])
    if args.print:
        print(commits[index][1])
        return
    tempfd, tempname = tempfile.mkstemp()
    subprocess.run(["git", "show", commits[index][1]],
                   text=True,
                   stdout=tempfd,
                   check=True)
    log.debug("'git show %s' written to %s", commits[index][1], tempname)
    subprocess.run(["bat", "--language", "Diff", tempname], text=True)
    os.remove(tempname)
Ejemplo n.º 5
0
def _select_branch(doc, cli_args: str = None):
    global log
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=doc),
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)
    return common.select_branch(include_remotes=args.all, preview=args.preview)
Ejemplo n.º 6
0
def test_init():
    args = hedgehog.init(
        lambda p, v: p.parse_args(v),
        arguments="-vv --no-color",
        logger=True,
        default_loglevel="CRITICAL",
        argp_kwargs=dict(description="test text", prog="test"),
    )
    assert hedgehog.CACHE_DIR.is_dir()
    assert args.verbose == 2
    assert args.color is False
    assert logging.getLogger().getEffectiveLevel() == logging.WARNING
Ejemplo n.º 7
0
def main(*, cli_args: str = None):
    global log
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=__doc__),
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)
    out = common.git_command("ls-files", "-z", *ls_files_args)
    filetree = paths_to_tree(pathlib.Path(f) for f in out.split("\0"))
    print_tree(filetree)
Ejemplo n.º 8
0
def main(*, cli_args: str = None):
    global log
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=__doc__),
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)
    branch = common.select_branch(include_remotes=True,
                                  title="Select branch to delete")
    if not branch:
        return

    for desc, name in branch.all:
        if match := re.match(rf"..remotes/(\S*{branch.branch})\s", desc):
            log.debug("There seems to be a matching remote: %s", match[1])
            remote_branch = match[1].split("/", maxsplit=1)
            break
Ejemplo n.º 9
0
def main(*, cli_args: str = None):
    global log
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=__doc__),
        default_loglevel="WARNING",
    )
    log = logging.getLogger(args.prog_name)
    log.debug(args)

    stack = Dirstack.load()
    if args.add:
        stack.add(args.add)
        stack.save()
        return
    if args.delete:
        stack.delete()
        return
    if args.list:
        for entry in stack.sorted():
            print("{} | {}".format(*entry))
        return

    ordered_entries = stack.sorted()
    menu_entries = [
        f"[{i + 1}] {e.time.isoformat(sep=' ', timespec='seconds')}  {e.path}"
        for i, e in enumerate(ordered_entries)
    ]
    options = [
        "[p] pop an entry",
        "[d] delete an entry",
        "[o] delete entries older than...",
        "[l] last visited directory",
    ]
    menu = functools.partial(TerminalMenu, show_search_hint=True)
    main_menu = menu(menu_entries + options)
    index = main_menu.show()

    if index is None:
        raise DirstackException("Nothing selected", retcode=EXIT_NOOP)

    try:
        entry = ordered_entries[index]
        log.debug("selected: %s", entry)
    except IndexError:  # one of the options after stack entries selected
        opt = index - len(ordered_entries)
        option = options[opt]

        if "last visited directory" in option:
            # Find first entry in list (sorted by visit time desc) that is not CWD
            for entry in ordered_entries:
                if entry.path != pathlib.Path.cwd():
                    stack.add(entry)
                    print(entry.path)
                    stack.save()
                    return
            else:
                raise DirstackException("No entry available", retcode=EXIT_NOOP)

        kwargs = {}
        if "older than" in option:
            kwargs["title"] = "Delete all entries from selected and older:"

        # Show menu of directories again, without the options
        selected_entry = menu(menu_entries, **kwargs).show()
        if selected_entry is None:
            raise DirstackException("Nothing selected", retcode=EXIT_NOOP)

        if "pop an entry" in option:
            entry = stack.pop(ordered_entries[selected_entry].path)
            print(entry.path)
        elif "delete an entry" in option:
            entry = stack.pop(ordered_entries[selected_entry].path)
            stack.save()
            raise DirstackException(f"Deleted: {entry.path}", retcode=EXIT_DELETED)
        elif "older than" in option:
            popped = []
            for entry in ordered_entries[selected_entry:]:
                log.info("delete %s", entry)
                popped.append(stack.pop(entry))
            stack.save()
            raise DirstackException(
                "\n".join((f"Deleted: {e.path}" for e in popped)), retcode=EXIT_DELETED
            )
        stack.save()
        return

    # re-add selected path entry to stack
    stack.add(entry)
    stack.save()

    print(entry.path)
Ejemplo n.º 10
0
def main(*, cli_args: str = None):
    args = hedgehog.init(
        _init,
        arguments=cli_args,
        logger=True,
        argp_kwargs=dict(description=__doc__),
    )
    global log
    log = logging.getLogger(args.prog_name)
    cprint = Print.instance()
    cache_file = hedgehog.CACHE_DIR / "sshansible_last_host"
    hostname = None
    inventory = ansible.get_inventory(
        path=args.inventory or args.local_inventory and ansible.find_inventory()
    )

    config_file = pathlib.Path(args.config).resolve()
    config = yaml.safe_load(config_file.read_bytes())
    append_host_domain_name = config["domain_name"]

    ssh_config = hedgehog.TEMP_DIR / "ssh_config"
    if inventory and (args.ssh_config or not ssh_config.exists()):
        log.info("Write inventory of %d hosts to %s", len(inventory), ssh_config)
        ansible.write_ssh_config(ssh_config, inventory.values())
    if args.ssh_config:
        return

    if args.complete_hosts:
        print("\t".join(inventory.keys()))
        return True
    elif args.last:
        try:
            hostname = cache_file.read_text()
        except OSError:
            raise Error("Cannot use --last because cache file doesn't exist.")
        if not args.sshargs:
            args.sshargs.append(hostname)
    elif args.list:
        list_inventory(inventory, cache_file)
        return
    elif args.hosts_file:
        handle_hosts_file(
            [h for h, online in list_inventory(inventory, cache_file) if online],
            append_host_domain_name,
        )
        return

    if not hostname:
        hostname = args.scp or args.sshargs[-1]

    # Allow empty hostname in scp src/dest specifications
    for i, arg in enumerate(args.sshargs):
        if arg.startswith(":"):
            args.sshargs[i] = f"{hostname}{arg}"

    try:
        host = inventory[hostname]
    except KeyError:
        raise Error("Couldn't find a host with name: %s", hostname)
    cache_file.write_text(hostname)

    command = "scp" if args.scp else "ssh-copy-id" if args.copy_id else "ssh"
    exec_args = [command, "-o", f"Hostname={host.address}", *args.sshargs]

    if args.remote_cmd:
        return run_remote_command(args.remote_cmd, hostname, host.address, exec_args)

    cprint(f"exec: {' '.join(exec_args)}", "yellow", file=sys.stderr)
    sys.stdout.flush()
    if args.dryrun:
        print(host.address)
    else:
        os.execlp(command, *exec_args)