### Initialize SQLite Database Connection Source: https://context7.com/bossflap/flow-command-vault/llms.txt Establishes a connection to the SQLite database with Write-Ahead Logging (WAL) mode enabled and Row factory configured for dictionary-like access. ```python import sqlite3 import os DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vault.db") def _db(): con = sqlite3.connect(DB_PATH) con.row_factory = sqlite3.Row con.execute("PRAGMA journal_mode=WAL") return con ``` -------------------------------- ### Flow Launcher Query Interface (Python) Source: https://context7.com/bossflap/flow-command-vault/llms.txt Handles all search queries for the Flow Launcher plugin. It supports special commands like ':init' to initialize the database and ':manage' to open the GUI manager. Additionally, it processes operator filters such as 'cat:', 'sub:', 'tag:', and 'fav:' to refine search results, alongside full-text search across all command fields. ```python # main.py - CommandVault Flow Launcher plugin class CommandVault(FlowLauncher): def query(self, query: str) -> list[dict[str, Any]]: """Process Flow Launcher queries and return matching results. Special commands: :init, :setup, :initialize - Initialize the database :manage, :manager, :edit - Open GUI manager Search operators: cat:cisco - Filter by category sub:vlan - Filter by subcategory tag:ccna - Filter by tag fav: - Show favorites only Returns: List of Flow Launcher result dictionaries """ q = query.strip() # Special command: initialize database if q in (":init", ":setup", ":initialize"): return [{ "Title": "Initialize Command Vault", "SubTitle": "Press Enter to create database and load 150+ built-in commands", "IcoPath": ICON, "JsonRPCAction": { "method": "run_init", "parameters": [], }, }] # Special command: open GUI manager if q in (":manage", ":manager", ":edit", ":gui"): return [{ "Title": "Open Command Vault Manager", "SubTitle": "Add, edit, delete and organize your commands in a GUI", "IcoPath": ICON, "JsonRPCAction": { "method": "open_manager", "parameters": [], }, }] # Search commands rows = _search(query) results = [] for r in rows: results.append({ "Title": _format_title(r), "SubTitle": _format_subtitle(r), "IcoPath": _icon(r), "JsonRPCAction": { "method": "copy_command", "parameters": [r["id"], r["title"]], }, "ContextData": r["id"], }) return results # Flow Launcher usage examples: # cv - Shows all favorites first # cv vlan - All VLAN-related commands # cv cisco trunk - Cisco trunk commands # cv cat:linux - All Linux commands # cv fav: ssh - Favorite SSH commands # cv :manage - Open GUI manager ``` -------------------------------- ### Copy and Expand Command to Clipboard Source: https://context7.com/bossflap/flow-command-vault/llms.txt Retrieves a command from the database, expands template placeholders like {variable} using a tkinter dialog, and copies the final string to the Windows clipboard. ```python def _set_clipboard(text: str) -> None: p = subprocess.Popen(["clip"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) p.communicate(text.encode("utf-16-le")) def _expand_template(command: str, title: str) -> str: if not VAR_PATTERN.search(command): return command dialog = os.path.join(PLUGIN_DIR, "template_dialog.py") payload = json.dumps({"command": command, "title": title}) try: result = subprocess.run([sys.executable, dialog, payload], capture_output=True, text=True, timeout=120) if result.returncode == 0 and result.stdout: return result.stdout except (subprocess.TimeoutExpired, FileNotFoundError): pass return command ``` -------------------------------- ### Fetch and Filter Commands Source: https://context7.com/bossflap/flow-command-vault/llms.txt Retrieves commands from the database with support for optional search queries, category filtering, and favorite status. Returns a list of rows ordered by priority. ```python def fetch_commands(search="", category=None, favorites_only=False): with _db() as con: conditions, params = [], [] if search: like = f"%{search}%" conditions.append("(title LIKE ? OR command LIKE ? OR description LIKE ? OR tags LIKE ?)") params += [like, like, like, like] if category: conditions.append("category = ?") params.append(category) if favorites_only: conditions.append("is_favorite = 1") where = ("WHERE " + " AND ".join(conditions)) if conditions else "" return con.execute(f"SELECT * FROM commands {where} ORDER BY is_favorite DESC, category, subcategory, title", params).fetchall() ``` -------------------------------- ### Initialize Command Vault Database (Python) Source: https://context7.com/bossflap/flow-command-vault/llms.txt Initializes or resets the Command Vault SQLite database. It creates the necessary tables, sets up FTS5 full-text indexing, and populates the database with over 150 built-in commands for Cisco IOS, Linux, Proxmox, and Ansible. The function supports dropping an existing database if the `drop_existing` flag is set to True. ```python # db_init.py - Initialize or reset the command database import os import sqlite3 DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vault.db") def init_db(drop_existing: bool = False) -> None: """Initialize the vault database with schema and seed commands. Args: drop_existing: If True, removes existing database before creating new one """ if drop_existing and os.path.exists(DB_PATH): os.remove(DB_PATH) print(f"Removed existing DB: {DB_PATH}") con = sqlite3.connect(DB_PATH) con.executescript(SCHEMA) # Creates tables, FTS5 index, and triggers con.commit() # Insert seed data (156+ commands) cur = con.cursor() cur.executemany( "INSERT INTO commands(category, subcategory, title, command, description, tags, is_favorite) " "VALUES (?,?,?,?,?,?,?)", SEED_DATA, ) con.commit() count = con.execute("SELECT COUNT(*) FROM commands").fetchone()[0] con.close() print(f"DB ready: {DB_PATH}") print(f"Commands loaded: {count}") # Command line usage: # python db_init.py # Initialize database # python db_init.py --reset # Reset to defaults ``` -------------------------------- ### Search Commands with Filters - Python Source: https://context7.com/bossflap/flow-command-vault/llms.txt Searches commands in the database using FTS5 for full-text search when no filters are applied, or falls back to LIKE for broader matching with filters. It prioritizes favorite commands and sorts results alphabetically by category, subcategory, and title. ```Python def _search(query: str) -> list: """Search commands using FTS5 full-text search with operator filters. Returns up to 50 matching commands, ordered by: 1. Favorites first (is_favorite DESC) 2. Category, subcategory, title alphabetically """ raw = (query or "").strip() plain, filters = _parse_query(raw) with _db() as con: conditions: list[str] = [] params: list = [] # Apply operator filters if filters.get("favorites"): conditions.append("is_favorite = 1") if cat := filters.get("category"): conditions.append("category LIKE ?") params.append(f"%{cat}%") if sub := filters.get("subcategory"): conditions.append("subcategory LIKE ?") params.append(f"%{sub}%") if tag := filters.get("tag"): conditions.append("tags LIKE ?") params.append(f"%{tag}%") # FTS5 full-text search when no filters if plain and _fts_ok(con) and not filters: fts_q = " OR ".join(f'"{t}"' for t in plain.split() if t) rows = con.execute( "SELECT c.* FROM commands_fts f " "JOIN commands c ON c.id = f.rowid " "WHERE commands_fts MATCH ? " "ORDER BY c.is_favorite DESC, rank LIMIT 50", [fts_q], ).fetchall() if rows: return rows # LIKE fallback for broader matching if plain: like = f"%{plain}%" conditions.append( "(title LIKE ? OR command LIKE ? OR description LIKE ? " "OR tags LIKE ? OR category LIKE ? OR subcategory LIKE ?)" ) params += [like, like, like, like, like, like] where = ("WHERE " + " AND ".join(conditions)) if conditions else "" return con.execute( f"SELECT * FROM commands {where} " "ORDER BY is_favorite DESC, category, subcategory, title LIMIT 50", params, ).fetchall() ``` -------------------------------- ### Template Dialog for Variable Input - Python Source: https://context7.com/bossflap/flow-command-vault/llms.txt A standalone Tkinter GUI dialog that prompts users to fill in `{variable}` placeholders within a command string. It provides real-time preview highlighting of variables and supports command-line execution for integration with other scripts. The dialog returns the filled command string or None if cancelled. ```Python # template_dialog.py - Template variable prompt dialog import re import json import sys import tkinter as tk VAR_PATTERN = re.compile(r"\{([a-zA-Z0-9_]+)\") def highlight_command(text_widget: tk.Text, command: str): """Insert command text with {variables} highlighted in yellow.""" text_widget.config(state="normal") text_widget.delete("1.0", "end") last = 0 for m in VAR_PATTERN.finditer(command): if m.start() > last: text_widget.insert("end", command[last:m.start()], "plain") text_widget.insert("end", m.group(0), "var") # Highlight variable last = m.end() if last < len(command): text_widget.insert("end", command[last:], "plain") text_widget.config(state="disabled") def run(command: str, title: str) -> str | None: """Show dialog for template variables, return filled command or None.""" vars_found = list(dict.fromkeys(VAR_PATTERN.findall(command))) if not vars_found: return command # No variables, return as-is root = tk.Tk() root.title("Command Vault - Template") result = {"value": None} entries: dict[str, tk.StringVar] = {} # Create input fields for each variable for var in vars_found: sv = tk.StringVar() entries[var] = sv # Real-time preview update def on_type(*_, v=var, sv=sv): filled = command for k, s in entries.items(): val = s.get() or f"{{{k}}}" filled = filled.replace(f"{{{k}}}", val) highlight_command(preview, filled) sv.trace_add("write", on_type) def on_ok(): filled = command for var, sv in entries.items(): filled = filled.replace(f"{{{var}}}", sv.get()) result["value"] = filled root.destroy() root.bind("", lambda _: on_ok()) root.bind("", lambda _: root.destroy()) root.mainloop() return result["value"] # Called as subprocess from main.py: # python template_dialog.py '{"command": "ssh {user}@{host}", "title": "SSH to host"}' if __name__ == "__main__": payload = json.loads(sys.argv[1]) filled = run(payload["command"], payload.get("title", "")) if filled: print(filled, end="") sys.exit(0) sys.exit(1) ``` -------------------------------- ### Import/Export Commands using JSON - Python Source: https://context7.com/bossflap/flow-command-vault/llms.txt Provides functionality to export the current filtered list of commands to a JSON file and import commands from a JSON file. It utilizes Tkinter for file dialogs and the `json` module for data serialization. The export function filters commands based on search, category, and favorites, while the import function inserts new commands into the vault. ```Python import json from tkinter import filedialog class VaultManager(tk.Tk): def cmd_export(self): """Export current view to JSON file.""" path = filedialog.asksaveasfilename( title="Export commands", defaultextension=".json", filetypes=[("JSON", "*.json"), ("All files", "*.*")], initialfile="command_vault_export.json", ) if not path: return # Export current filtered view rows = fetch_commands( search=self.v_search.get(), category=self._active_category, favorites_only=self._favs_only, ) data = [ {k: row[k] for k in ("category", "subcategory", "title", "command", "description", "tags", "is_favorite")} for row in rows ] with open(path, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) Toast(self, f"Exported {len(data)} commands", GREEN) def cmd_import(self): """Import commands from JSON file.""" path = filedialog.askopenfilename( title="Import commands", filetypes=[("JSON", "*.json"), ("All files", "*.*")], ) if not path: return with open(path, "r", encoding="utf-8") as f: data = json.load(f) count = 0 for entry in data: insert_cmd({ "category": entry.get("category", "Imported"), "subcategory": entry.get("subcategory", ""), "title": entry.get("title", "Untitled"), "command": entry.get("command", ""), "description": entry.get("description", ""), "tags": entry.get("tags", ""), "is_favorite": entry.get("is_favorite", 0), }) count += 1 self.full_refresh() Toast(self, f"Imported {count} commands", GREEN) ``` -------------------------------- ### SQLite Schema with FTS5 for Command Vault Source: https://context7.com/bossflap/flow-command-vault/llms.txt Defines the SQLite database schema for the Command Vault, including the main 'commands' table and a 'commands_fts' virtual table using FTS5 for full-text search capabilities. It also sets up triggers to automatically synchronize the FTS index with changes in the main table. ```sql PRAGMA journal_mode=WAL; -- Main commands table CREATE TABLE IF NOT EXISTS commands ( id INTEGER PRIMARY KEY AUTOINCREMENT, category TEXT NOT NULL, -- e.g. "Cisco", "Linux", "Proxmox", "Ansible" subcategory TEXT, -- e.g. "VLAN", "Disk", "VM" title TEXT NOT NULL, -- Display name command TEXT NOT NULL, -- The command (supports {var} templates) description TEXT, -- Short explanation (subtitle) tags TEXT, -- Comma-separated keywords is_favorite INTEGER NOT NULL DEFAULT 0, -- 1 = appears first on empty query created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); -- Indexes for common queries CREATE INDEX IF NOT EXISTS idx_cmd_category ON commands(category); CREATE INDEX IF NOT EXISTS idx_cmd_title ON commands(title); -- FTS5 virtual table for full-text search CREATE VIRTUAL TABLE IF NOT EXISTS commands_fts USING fts5( title, command, description, tags, category, subcategory, content='commands', content_rowid='id' ); -- Auto-sync FTS index on INSERT CREATE TRIGGER IF NOT EXISTS commands_ai AFTER INSERT ON commands BEGIN INSERT INTO commands_fts(rowid, title, command, description, tags, category, subcategory) VALUES (new.id, new.title, new.command, new.description, new.tags, new.category, new.subcategory); END; -- Auto-sync FTS index on DELETE CREATE TRIGGER IF NOT EXISTS commands_ad AFTER DELETE ON commands BEGIN INSERT INTO commands_fts(commands_fts, rowid, title, command, description, tags, category, subcategory) VALUES ('delete', old.id, old.title, old.command, old.description, old.tags, old.category, old.subcategory); END; -- Auto-sync FTS index on UPDATE CREATE TRIGGER IF NOT EXISTS commands_au AFTER UPDATE ON commands BEGIN INSERT INTO commands_fts(commands_fts, rowid, title, command, description, tags, category, subcategory) VALUES ('delete', old.id, old.title, old.command, old.description, old.tags, old.category, old.subcategory); INSERT INTO commands_fts(rowid, title, command, description, tags, category, subcategory) VALUES (new.id, new.title, new.command, new.description, new.tags, new.category, new.subcategory); END; ``` -------------------------------- ### Parse Search Query - Python Source: https://context7.com/bossflap/flow-command-vault/llms.txt Parses a raw search query string into plain text tokens and a dictionary of operator filters. It handles operators like 'category', 'subcategory', 'tag', and 'favorites'. ```Python OPERATORS = { "cat": "category", "c": "category", "category": "category", "sub": "subcategory", "s": "subcategory", "subcategory": "subcategory", "tag": "tag", "t": "tag", "fav": "favorites", "f": "favorites", "favorite": "favorites", } def _parse_query(raw: str) -> tuple[str, dict]: """Split query into plain text and operator filters. Examples: "cat:cisco vlan" -> ("vlan", {"category": "cisco"}) "fav: show mac" -> ("show mac", {"favorites": True}) "tag:ccna sub:vlan" -> ("", {"tag": "ccna", "subcategory": "vlan"}) """ filters: dict = {} plain_tokens: list[str] = [] for token in raw.split(): if ":" in token: key, _, val = token.partition(":") op = _OPERATORS.get(key.lower().strip()) if op == "favorites": filters["favorites"] = True elif op and val.strip(): filters[op] = val.strip() else: plain_tokens.append(token) else: plain_tokens.append(token) return " ".join(plain_tokens), filters ``` -------------------------------- ### Toggle Command Favorite Status Source: https://context7.com/bossflap/flow-command-vault/llms.txt Updates the database to flip the is_favorite boolean flag for a specific command ID and provides context menu integration for Flow Launcher. ```python def _toggle_favorite(cmd_id: int) -> None: with _db() as con: con.execute("UPDATE commands SET is_favorite = CASE WHEN is_favorite=1 THEN 0 ELSE 1 END, updated_at = datetime('now') WHERE id = ?", (cmd_id,)) con.commit() class CommandVault(FlowLauncher): def toggle_favorite(self, cmd_id: int) -> None: _toggle_favorite(cmd_id) ``` -------------------------------- ### Perform CRUD Operations on Commands Source: https://context7.com/bossflap/flow-command-vault/llms.txt Functions to insert, update, and delete command records in the SQLite database. These operations handle transaction commits and return relevant IDs or status. ```python def insert_cmd(d): with _db() as con: cur = con.execute("INSERT INTO commands(category,subcategory,title,command,description,tags,is_favorite) VALUES(?,?,?,?,?,?,?)", (d["category"], d["subcategory"], d["title"], d["command"], d["description"], d["tags"], 1 if d["is_favorite"] else 0)) con.commit() return cur.lastrowid def update_cmd(cmd_id, d): with _db() as con: con.execute("UPDATE commands SET category=?,subcategory=?,title=?,command=?,description=?,tags=?,is_favorite=?,updated_at=datetime('now') WHERE id=?", (d["category"], d["subcategory"], d["title"], d["command"], d["description"], d["tags"], 1 if d["is_favorite"] else 0, cmd_id)) con.commit() def delete_cmd(cmd_id): with _db() as con: con.execute("DELETE FROM commands WHERE id=?", (cmd_id,)) con.commit() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.