|
| 1 | +import os |
| 2 | +from typer import Context |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import devcli.framework as cmd |
| 6 | + |
| 7 | +cli = cmd.new("Edit different files using text editor") |
| 8 | + |
| 9 | +logger = cmd.logger() |
| 10 | + |
| 11 | +# closure to create partial func |
| 12 | +def prep_editor(ctx: Context): |
| 13 | + def run_editor(file: Path): |
| 14 | + """Open editor on file""" |
| 15 | + c_editor = ctx.obj["devcli.commands.edit.editor"] |
| 16 | + e_editor = os.getenv("EDITOR", "vim") |
| 17 | + |
| 18 | + # config first, env and last default |
| 19 | + editor = c_editor if c_editor else e_editor |
| 20 | + |
| 21 | + os.execvp(editor, [editor, file]) |
| 22 | + |
| 23 | + def open_editor(file: Path): |
| 24 | + run_editor(file) |
| 25 | + |
| 26 | + return open_editor |
| 27 | + |
| 28 | + |
| 29 | +@cli.command() |
| 30 | +def config(ctx: Context): |
| 31 | + editor = prep_editor(ctx) |
| 32 | + configs = ctx.obj.files() |
| 33 | + if not configs: |
| 34 | + cmd.stop("No configuration files were found.") |
| 35 | + |
| 36 | + # last file is the most specific one |
| 37 | + editor(configs[-1]) |
| 38 | + |
| 39 | + |
| 40 | +@cli.command("command") |
| 41 | +def edit_command(ctx: Context, name: str): |
| 42 | + editor = prep_editor(ctx) |
| 43 | + configs = ctx.obj.files() |
| 44 | + p = Path(configs[-1]).parent |
| 45 | + subcmd = p / f"{name}.py" |
| 46 | + logger.info(f"command search path: {subcmd}") |
| 47 | + if subcmd.exists(): |
| 48 | + logger.info(f"command exists opening editor...") |
| 49 | + editor(subcmd) |
| 50 | + else: |
| 51 | + logger.info(f"command does not exist in {subcmd}, stopping.") |
| 52 | + cmd.stop(f"cmd: {subcmd.name} not found in path: {p}") |
0 commit comments