|
| 1 | +import glob |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from talon import Context, Module, actions, settings |
| 5 | + |
| 6 | +from ..targets.target_types import CursorlessExplicitTarget |
| 7 | + |
| 8 | +mod = Module() |
| 9 | + |
| 10 | +ctx = Context() |
| 11 | +ctx.matches = r""" |
| 12 | +tag: user.cursorless_use_community_snippets |
| 13 | +""" |
| 14 | + |
| 15 | + |
| 16 | +@mod.action_class |
| 17 | +class Actions: |
| 18 | + def private_cursorless_generate_snippet_action(target: CursorlessExplicitTarget): # pyright: ignore [reportGeneralTypeIssues] |
| 19 | + """Generate a snippet from the given target""" |
| 20 | + actions.user.private_cursorless_command_no_wait( |
| 21 | + { |
| 22 | + "name": "generateSnippet", |
| 23 | + "target": target, |
| 24 | + } |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +@ctx.action_class("user") |
| 29 | +class UserActions: |
| 30 | + def private_cursorless_generate_snippet_action(target: CursorlessExplicitTarget): # pyright: ignore [reportGeneralTypeIssues] |
| 31 | + actions.user.private_cursorless_command_no_wait( |
| 32 | + { |
| 33 | + "name": "generateSnippet", |
| 34 | + "target": target, |
| 35 | + "directory": str(get_directory_path()), |
| 36 | + } |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +def get_directory_path() -> Path: |
| 41 | + settings_dir = get_setting_dir() |
| 42 | + if settings_dir is not None: |
| 43 | + return settings_dir |
| 44 | + return get_community_snippets_dir() |
| 45 | + |
| 46 | + |
| 47 | +def get_setting_dir() -> Path | None: |
| 48 | + try: |
| 49 | + setting_dir = settings.get("user.snippets_dir") |
| 50 | + if not setting_dir: |
| 51 | + return None |
| 52 | + |
| 53 | + dir = Path(str(setting_dir)) |
| 54 | + |
| 55 | + if not dir.is_absolute(): |
| 56 | + user_dir = Path(actions.path.talon_user()) |
| 57 | + dir = user_dir / dir |
| 58 | + |
| 59 | + return dir.resolve() |
| 60 | + except Exception: |
| 61 | + return None |
| 62 | + |
| 63 | + |
| 64 | +def get_community_snippets_dir() -> Path: |
| 65 | + files = glob.iglob( |
| 66 | + f"{actions.path.talon_user()}/**/snippets/snippets/*.snippet", |
| 67 | + recursive=True, |
| 68 | + ) |
| 69 | + for file in files: |
| 70 | + return Path(file).parent |
| 71 | + raise ValueError("Could not find community snippets directory") |
0 commit comments