dirty-repo-guard.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Dirty Repo Guard Extension
  3. *
  4. * Prevents session changes when there are uncommitted git changes.
  5. * Useful to ensure work is committed before switching context.
  6. */
  7. import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
  8. async function checkDirtyRepo(
  9. pi: ExtensionAPI,
  10. ctx: ExtensionContext,
  11. action: string,
  12. ): Promise<{ cancel: boolean } | undefined> {
  13. // Check for uncommitted changes
  14. const { stdout, code } = await pi.exec("git", ["status", "--porcelain"]);
  15. if (code !== 0) {
  16. // Not a git repo, allow the action
  17. return;
  18. }
  19. const hasChanges = stdout.trim().length > 0;
  20. if (!hasChanges) {
  21. return;
  22. }
  23. if (!ctx.hasUI) {
  24. // In non-interactive mode, block by default
  25. return { cancel: true };
  26. }
  27. // Count changed files
  28. const changedFiles = stdout.trim().split("\n").filter(Boolean).length;
  29. const choice = await ctx.ui.select(`You have ${changedFiles} uncommitted file(s). ${action} anyway?`, [
  30. "Yes, proceed anyway",
  31. "No, let me commit first",
  32. ]);
  33. if (choice !== "Yes, proceed anyway") {
  34. ctx.ui.notify("Commit your changes first", "warning");
  35. return { cancel: true };
  36. }
  37. }
  38. export default function (pi: ExtensionAPI) {
  39. pi.on("session_before_switch", async (event, ctx) => {
  40. const action = event.reason === "new" ? "new session" : "switch session";
  41. return checkDirtyRepo(pi, ctx, action);
  42. });
  43. pi.on("session_before_fork", async (_event, ctx) => {
  44. return checkDirtyRepo(pi, ctx, "fork");
  45. });
  46. }