gitacc-switcher 1.2.1__tar.gz → 1.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {gitacc_switcher-1.2.1/gitacc_switcher.egg-info → gitacc_switcher-1.4.0}/PKG-INFO +44 -1
  2. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/README.md +43 -0
  3. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/__init__.py +1 -1
  4. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/account_manager.py +63 -0
  5. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/cli.py +194 -0
  6. gitacc_switcher-1.4.0/gitacc_switcher/rules_manager.py +118 -0
  7. gitacc_switcher-1.4.0/gitacc_switcher/shell_hook.py +51 -0
  8. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/ssh_manager.py +49 -1
  9. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0/gitacc_switcher.egg-info}/PKG-INFO +44 -1
  10. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher.egg-info/SOURCES.txt +4 -0
  11. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/pyproject.toml +1 -1
  12. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/setup.py +1 -1
  13. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_account_manager.py +105 -0
  14. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_cli.py +199 -0
  15. gitacc_switcher-1.4.0/tests/test_rules_manager.py +142 -0
  16. gitacc_switcher-1.4.0/tests/test_shell_hook.py +34 -0
  17. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_ssh_manager.py +48 -0
  18. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/LICENSE +0 -0
  19. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/MANIFEST.in +0 -0
  20. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/completion.py +0 -0
  21. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/config_manager.py +0 -0
  22. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/hook_manager.py +0 -0
  23. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher/utils.py +0 -0
  24. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher.egg-info/dependency_links.txt +0 -0
  25. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher.egg-info/entry_points.txt +0 -0
  26. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher.egg-info/requires.txt +0 -0
  27. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/gitacc_switcher.egg-info/top_level.txt +0 -0
  28. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/requirements.txt +0 -0
  29. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/setup.cfg +0 -0
  30. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/__init__.py +0 -0
  31. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_completion.py +0 -0
  32. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_config_manager.py +0 -0
  33. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_hook_manager.py +0 -0
  34. {gitacc_switcher-1.2.1 → gitacc_switcher-1.4.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gitacc-switcher
3
- Version: 1.2.1
3
+ Version: 1.4.0
4
4
  Summary: Git Account Switcher - Manage multiple Git SSH accounts easily
5
5
  Home-page: https://github.com/ktechhub/gitacc_switcher
6
6
  Author: ktechhub
@@ -49,6 +49,7 @@ A Python CLI tool to easily switch between multiple Git SSH accounts. Manage mul
49
49
  - Opt-in SSH commit signing per account
50
50
  - Colored terminal output with active account indicator
51
51
  - Pre-commit hook to prevent commits with the wrong account
52
+ - Opt-in directory-based auto-switching (`gitacc rule`) with a bash/zsh shell hook
52
53
  - Shell autocomplete for bash and zsh
53
54
  - Cross-platform support (Linux / macOS)
54
55
 
@@ -184,6 +185,40 @@ Kill the SSH agent and unset the global Git user config.
184
185
  gitacc logout
185
186
  ```
186
187
 
188
+ ### `gitacc rule add <account> [directory]` / `gitacc rule remove [directory]` / `gitacc rule list`
189
+
190
+ Opt-in, direnv-style directory-based auto-switching: bind an account to a directory (and
191
+ everything beneath it) so the right identity is picked automatically as you move around, instead
192
+ of running `gitacc switch` by hand. `directory` defaults to the current directory. The most
193
+ specific matching directory wins, so a rule on a subdirectory overrides one on its parent.
194
+
195
+ ```bash
196
+ gitacc rule add work ~/projects/work # anything under ~/projects/work uses "work"
197
+ gitacc rule add personal ~/projects/side # anything under ~/projects/side uses "personal"
198
+ gitacc rule list
199
+ gitacc rule remove ~/projects/side
200
+ ```
201
+
202
+ Rules by themselves don't do anything — nothing triggers on `cd` until you install the shell hook
203
+ below.
204
+
205
+ ### `gitacc rule hook <bash|zsh>`
206
+
207
+ Print a shell snippet that calls `gitacc rule check` so rules apply automatically. Add it to your
208
+ shell profile and restart your shell (or `source` it):
209
+
210
+ ```bash
211
+ # bash
212
+ gitacc rule hook bash >> ~/.bashrc
213
+
214
+ # zsh
215
+ gitacc rule hook zsh >> ~/.zshrc
216
+ ```
217
+
218
+ The hook is silent unless it actually needs to switch accounts: no matching rule, an SSH agent
219
+ that isn't running, or an identity that's already correct all do nothing. This is entirely
220
+ opt-in — `gitacc rule add` alone never touches your shell config.
221
+
187
222
  ### `gitacc autocomplete install`
188
223
 
189
224
  Install tab-completion for your shell (bash or zsh). After running, restart your shell or `source` your profile.
@@ -212,6 +247,7 @@ gitacc --version
212
247
  | Path | Purpose |
213
248
  |------|---------|
214
249
  | `~/.gitacc` | Stores all account entries (INI format) |
250
+ | `~/.gitaccrules` | Directory → account rules for `gitacc rule` (opt-in auto-switch) |
215
251
  | `~/.ssh/id_<type>_<account>` | Private SSH key per account |
216
252
  | `~/.ssh/id_<type>_<account>.pub` | Public SSH key per account |
217
253
 
@@ -226,6 +262,13 @@ gitacc --version
226
262
  sign = false
227
263
  ```
228
264
 
265
+ `~/.gitaccrules` format (one rule per line, most-specific directory wins):
266
+
267
+ ```
268
+ /home/jane/projects/work = work
269
+ /home/jane/projects/work/client-a = client-a
270
+ ```
271
+
229
272
  ## Requirements
230
273
 
231
274
  - Python 3.8+
@@ -16,6 +16,7 @@ A Python CLI tool to easily switch between multiple Git SSH accounts. Manage mul
16
16
  - Opt-in SSH commit signing per account
17
17
  - Colored terminal output with active account indicator
18
18
  - Pre-commit hook to prevent commits with the wrong account
19
+ - Opt-in directory-based auto-switching (`gitacc rule`) with a bash/zsh shell hook
19
20
  - Shell autocomplete for bash and zsh
20
21
  - Cross-platform support (Linux / macOS)
21
22
 
@@ -151,6 +152,40 @@ Kill the SSH agent and unset the global Git user config.
151
152
  gitacc logout
152
153
  ```
153
154
 
155
+ ### `gitacc rule add <account> [directory]` / `gitacc rule remove [directory]` / `gitacc rule list`
156
+
157
+ Opt-in, direnv-style directory-based auto-switching: bind an account to a directory (and
158
+ everything beneath it) so the right identity is picked automatically as you move around, instead
159
+ of running `gitacc switch` by hand. `directory` defaults to the current directory. The most
160
+ specific matching directory wins, so a rule on a subdirectory overrides one on its parent.
161
+
162
+ ```bash
163
+ gitacc rule add work ~/projects/work # anything under ~/projects/work uses "work"
164
+ gitacc rule add personal ~/projects/side # anything under ~/projects/side uses "personal"
165
+ gitacc rule list
166
+ gitacc rule remove ~/projects/side
167
+ ```
168
+
169
+ Rules by themselves don't do anything — nothing triggers on `cd` until you install the shell hook
170
+ below.
171
+
172
+ ### `gitacc rule hook <bash|zsh>`
173
+
174
+ Print a shell snippet that calls `gitacc rule check` so rules apply automatically. Add it to your
175
+ shell profile and restart your shell (or `source` it):
176
+
177
+ ```bash
178
+ # bash
179
+ gitacc rule hook bash >> ~/.bashrc
180
+
181
+ # zsh
182
+ gitacc rule hook zsh >> ~/.zshrc
183
+ ```
184
+
185
+ The hook is silent unless it actually needs to switch accounts: no matching rule, an SSH agent
186
+ that isn't running, or an identity that's already correct all do nothing. This is entirely
187
+ opt-in — `gitacc rule add` alone never touches your shell config.
188
+
154
189
  ### `gitacc autocomplete install`
155
190
 
156
191
  Install tab-completion for your shell (bash or zsh). After running, restart your shell or `source` your profile.
@@ -179,6 +214,7 @@ gitacc --version
179
214
  | Path | Purpose |
180
215
  |------|---------|
181
216
  | `~/.gitacc` | Stores all account entries (INI format) |
217
+ | `~/.gitaccrules` | Directory → account rules for `gitacc rule` (opt-in auto-switch) |
182
218
  | `~/.ssh/id_<type>_<account>` | Private SSH key per account |
183
219
  | `~/.ssh/id_<type>_<account>.pub` | Public SSH key per account |
184
220
 
@@ -193,6 +229,13 @@ gitacc --version
193
229
  sign = false
194
230
  ```
195
231
 
232
+ `~/.gitaccrules` format (one rule per line, most-specific directory wins):
233
+
234
+ ```
235
+ /home/jane/projects/work = work
236
+ /home/jane/projects/work/client-a = client-a
237
+ ```
238
+
196
239
  ## Requirements
197
240
 
198
241
  - Python 3.8+
@@ -1,4 +1,4 @@
1
1
  """Git Account Switcher - Manage multiple Git SSH accounts easily."""
2
2
 
3
- __version__ = "1.2.1"
3
+ __version__ = "1.4.0"
4
4
  __author__ = "ktechhub"
@@ -7,6 +7,7 @@ from typing import Optional, Dict, List
7
7
  from .config_manager import ConfigManager
8
8
  from .ssh_manager import SSHManager
9
9
  from .hook_manager import HookManager
10
+ from .rules_manager import RulesManager
10
11
  from .utils import echo_color, ask_yes_no, validate_ssh_key_type
11
12
 
12
13
 
@@ -17,6 +18,7 @@ class AccountManager:
17
18
  self.config_manager = ConfigManager()
18
19
  self.ssh_manager = SSHManager()
19
20
  self.hook_manager = HookManager()
21
+ self.rules_manager = RulesManager()
20
22
 
21
23
  def add_account(self, key_type: str = "rsa", sign: bool = False) -> bool:
22
24
  """Add a new Git account.
@@ -382,6 +384,67 @@ class AccountManager:
382
384
 
383
385
  return True
384
386
 
387
+ def get_status(self, repo_path: Optional[Path] = None) -> Dict[str, object]:
388
+ """Report the currently active Git identity and SSH agent key, and
389
+ which registered account (if any) they match.
390
+
391
+ Read-only: makes no changes to Git config, the SSH agent, or any
392
+ managed files.
393
+
394
+ Args:
395
+ repo_path: Path to repository (default: current directory). Used
396
+ to resolve local Git config when run inside a repo.
397
+
398
+ Returns:
399
+ Dictionary with the current name/email, the matched account name
400
+ (or None), whether the SSH agent is running, and which account
401
+ (if any) the currently loaded agent key belongs to.
402
+ """
403
+ if self.config_manager.is_git_repo(repo_path):
404
+ current_config = self.config_manager.get_current_git_config_local(repo_path)
405
+ else:
406
+ current_config = self.config_manager.get_current_git_config()
407
+
408
+ current_name = current_config.get("name")
409
+ current_email = current_config.get("email")
410
+
411
+ accounts = self.config_manager.read_accounts()
412
+
413
+ matched_account = None
414
+ for account_name, account_info in accounts.items():
415
+ if (
416
+ current_name
417
+ and current_email
418
+ and account_info.get("name") == current_name
419
+ and account_info.get("email") == current_email
420
+ ):
421
+ matched_account = account_name
422
+ break
423
+
424
+ agent_running = self.ssh_manager.is_ssh_agent_running()
425
+ agent_fingerprints = (
426
+ self.ssh_manager.get_agent_fingerprints() if agent_running else []
427
+ )
428
+
429
+ matched_key_account = None
430
+ if agent_fingerprints:
431
+ for account_name, account_info in accounts.items():
432
+ public_key = account_info.get("public_key")
433
+ if not public_key:
434
+ continue
435
+ fingerprint = self.ssh_manager.get_key_fingerprint(public_key)
436
+ if fingerprint and fingerprint in agent_fingerprints:
437
+ matched_key_account = account_name
438
+ break
439
+
440
+ return {
441
+ "name": current_name,
442
+ "email": current_email,
443
+ "matched_account": matched_account,
444
+ "agent_running": agent_running,
445
+ "matched_key_account": matched_key_account,
446
+ }
447
+
385
448
  def init_repo(self, account_name: str, repo_path: Optional[Path] = None) -> bool:
386
449
  """Initialize repository with expected account and install pre-commit hook.
387
450
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  import argparse
4
4
  import sys
5
+ from pathlib import Path
5
6
  from typing import Optional
6
7
 
7
8
  try:
@@ -12,6 +13,7 @@ except ImportError:
12
13
  from . import __version__
13
14
  from .account_manager import AccountManager
14
15
  from .completion import get_account_names
16
+ from .shell_hook import get_hook_script, get_supported_shells
15
17
  from .utils import echo_color, get_ssh_key_types
16
18
 
17
19
 
@@ -45,10 +47,12 @@ class CLI:
45
47
  self._add_switch_command(subparsers)
46
48
  self._add_list_command(subparsers)
47
49
  self._add_logout_command(subparsers)
50
+ self._add_status_command(subparsers)
48
51
  self._add_init_command(subparsers)
49
52
  self._add_verify_command(subparsers)
50
53
  self._add_update_command(subparsers)
51
54
  self._add_autocomplete_command(subparsers)
55
+ self._add_rule_command(subparsers)
52
56
 
53
57
  # Include account names in top-level completion so `gitacc <TAB>` works for
54
58
  # the `gitacc <account>` shorthand, not just for subcommand names.
@@ -74,9 +78,12 @@ Examples:
74
78
  gitacc remove myaccount Remove an account
75
79
  gitacc list List all registered accounts
76
80
  gitacc logout Logout current account
81
+ gitacc status Show the currently active account
77
82
  gitacc init myaccount Initialize repo with account validation
78
83
  gitacc verify Verify current account matches repo
79
84
  gitacc update myaccount Update Git name for an account
85
+ gitacc rule add work ~/work Auto-switch to "work" inside that directory
86
+ gitacc rule hook bash Print the shell hook (add to ~/.bashrc)
80
87
  """
81
88
 
82
89
  def _add_add_command(self, subparsers: argparse._SubParsersAction) -> None:
@@ -158,6 +165,16 @@ Examples:
158
165
  )
159
166
  parser.set_defaults(func=self._handle_logout)
160
167
 
168
+ def _add_status_command(self, subparsers: argparse._SubParsersAction) -> None:
169
+ """Add the 'status' command parser."""
170
+ parser = subparsers.add_parser(
171
+ "status",
172
+ help="Show the currently active account",
173
+ description="Show the current Git identity and SSH agent key, "
174
+ "and which managed account (if any) matches",
175
+ )
176
+ parser.set_defaults(func=self._handle_status)
177
+
161
178
  def _add_init_command(self, subparsers: argparse._SubParsersAction) -> None:
162
179
  """Add the 'init' command parser."""
163
180
  parser = subparsers.add_parser(
@@ -242,6 +259,80 @@ Examples:
242
259
  )
243
260
  install_parser.set_defaults(func=self._handle_autocomplete_install)
244
261
 
262
+ def _add_rule_command(self, subparsers: argparse._SubParsersAction) -> None:
263
+ """Add the 'rule' command parser for directory-based auto-switching."""
264
+ parser = subparsers.add_parser(
265
+ "rule",
266
+ help="Manage directory-based account auto-switch rules",
267
+ description="Add, remove, and list rules that auto-switch accounts by directory",
268
+ )
269
+ rule_subparsers = parser.add_subparsers(
270
+ dest="rule_command",
271
+ help="Rule commands",
272
+ )
273
+
274
+ add_parser = rule_subparsers.add_parser(
275
+ "add",
276
+ help="Add or update a directory rule",
277
+ description="Auto-switch to an account whenever inside the given "
278
+ "directory (or a subdirectory of it)",
279
+ )
280
+ account_arg = add_parser.add_argument(
281
+ "account_name",
282
+ help="Account to switch to",
283
+ )
284
+ add_parser.add_argument(
285
+ "directory",
286
+ nargs="?",
287
+ default=None,
288
+ help="Directory the rule applies to (default: current directory)",
289
+ )
290
+ if argcomplete:
291
+ account_arg.completer = lambda **kwargs: get_account_names()
292
+ add_parser.set_defaults(func=self._handle_rule_add)
293
+
294
+ remove_parser = rule_subparsers.add_parser(
295
+ "remove",
296
+ help="Remove a directory rule",
297
+ )
298
+ remove_parser.add_argument(
299
+ "directory",
300
+ nargs="?",
301
+ default=None,
302
+ help="Directory whose rule should be removed (default: current directory)",
303
+ )
304
+ remove_parser.set_defaults(func=self._handle_rule_remove)
305
+
306
+ list_parser = rule_subparsers.add_parser(
307
+ "list",
308
+ help="List all directory rules",
309
+ )
310
+ list_parser.set_defaults(func=self._handle_rule_list)
311
+
312
+ hook_parser = rule_subparsers.add_parser(
313
+ "hook",
314
+ help="Print a shell hook that auto-switches on directory change",
315
+ description="Print a snippet for your shell profile that calls "
316
+ "'gitacc rule check' so rules apply automatically as you move "
317
+ "between directories",
318
+ )
319
+ hook_parser.add_argument(
320
+ "shell",
321
+ choices=get_supported_shells(),
322
+ help="Shell to generate the hook for",
323
+ )
324
+ hook_parser.set_defaults(func=self._handle_rule_hook)
325
+
326
+ check_parser = rule_subparsers.add_parser(
327
+ "check",
328
+ help="Match the current directory against rules (used by the shell hook)",
329
+ description="Intended to be called by the shell hook on every "
330
+ "prompt render, not run directly; silently does nothing unless "
331
+ "the current directory matches a rule for a different account "
332
+ "than the one currently active",
333
+ )
334
+ check_parser.set_defaults(func=self._handle_rule_check)
335
+
245
336
  def _handle_autocomplete_install(self, args: argparse.Namespace) -> int:
246
337
  """Handle the 'autocomplete install' command."""
247
338
  if not argcomplete:
@@ -396,6 +487,35 @@ Examples:
396
487
  success = self.account_manager.logout()
397
488
  return 0 if success else 1
398
489
 
490
+ def _handle_status(self, args: argparse.Namespace) -> int:
491
+ """Handle the 'status' command."""
492
+ status = self.account_manager.get_status()
493
+ name = status.get("name")
494
+ email = status.get("email")
495
+
496
+ echo_color("g", "Current Git identity:")
497
+ echo_color("g", f" Name: {name or '(not set)'}")
498
+ echo_color("g", f" Email: {email or '(not set)'}")
499
+
500
+ matched_account = status.get("matched_account")
501
+ if matched_account:
502
+ echo_color("g", f'Matched account: "{matched_account}"')
503
+ else:
504
+ echo_color("y", "No managed account matches the current Git identity.")
505
+
506
+ if status.get("agent_running"):
507
+ matched_key_account = status.get("matched_key_account")
508
+ if matched_key_account:
509
+ echo_color(
510
+ "g", f'SSH agent key matches account: "{matched_key_account}"'
511
+ )
512
+ else:
513
+ echo_color("y", "SSH agent key does not match any managed account.")
514
+ else:
515
+ echo_color("y", "SSH agent is not running.")
516
+
517
+ return 0
518
+
399
519
  def _handle_init(self, args: argparse.Namespace) -> int:
400
520
  """Handle the 'init' command."""
401
521
  success = self.account_manager.init_repo(args.account_name)
@@ -416,6 +536,80 @@ Examples:
416
536
  )
417
537
  return 0 if success else 1
418
538
 
539
+ def _handle_rule_add(self, args: argparse.Namespace) -> int:
540
+ """Handle the 'rule add' command."""
541
+ if not self.account_manager.account_exists(args.account_name):
542
+ echo_color("r", f'Account "{args.account_name}" not found!')
543
+ return 1
544
+
545
+ directory = Path(args.directory) if args.directory else Path.cwd()
546
+ success = self.account_manager.rules_manager.add_rule(
547
+ directory, args.account_name
548
+ )
549
+ if success:
550
+ resolved = Path(directory).expanduser().resolve()
551
+ echo_color("g", f'Rule added: "{resolved}" → "{args.account_name}"')
552
+ else:
553
+ echo_color("r", "Failed to add rule!")
554
+ return 0 if success else 1
555
+
556
+ def _handle_rule_remove(self, args: argparse.Namespace) -> int:
557
+ """Handle the 'rule remove' command."""
558
+ directory = Path(args.directory) if args.directory else Path.cwd()
559
+ success = self.account_manager.rules_manager.remove_rule(directory)
560
+ resolved = Path(directory).expanduser().resolve()
561
+ if success:
562
+ echo_color("g", f'Rule removed for "{resolved}"')
563
+ else:
564
+ echo_color("y", f'No rule was set for "{resolved}"')
565
+ return 0 if success else 1
566
+
567
+ def _handle_rule_list(self, args: argparse.Namespace) -> int:
568
+ """Handle the 'rule list' command."""
569
+ rules = self.account_manager.rules_manager.list_rules()
570
+ if not rules:
571
+ echo_color("y", "No directory rules registered yet.")
572
+ return 0
573
+
574
+ echo_color("g", "Directory auto-switch rules:")
575
+ for directory, account_name in rules.items():
576
+ print(f" {directory} → {account_name}")
577
+ return 0
578
+
579
+ def _handle_rule_hook(self, args: argparse.Namespace) -> int:
580
+ """Handle the 'rule hook' command."""
581
+ script = get_hook_script(args.shell)
582
+ if not script:
583
+ echo_color("r", f'Unsupported shell: "{args.shell}"')
584
+ return 1
585
+ print(script)
586
+ return 0
587
+
588
+ def _handle_rule_check(self, args: argparse.Namespace) -> int:
589
+ """Handle the 'rule check' command.
590
+
591
+ Called by the installed shell hook on every prompt render, so it
592
+ must stay quiet unless there is actually something to do: no match,
593
+ an already-correct identity, and a down SSH agent (which
594
+ `switch_account` would otherwise report loudly on every prompt) are
595
+ all silent no-ops.
596
+ """
597
+ account_name = self.account_manager.rules_manager.find_matching_account(
598
+ Path.cwd()
599
+ )
600
+ if not account_name or not self.account_manager.account_exists(account_name):
601
+ return 0
602
+
603
+ status = self.account_manager.get_status()
604
+ if status.get("matched_account") == account_name:
605
+ return 0
606
+
607
+ if not self.account_manager.ssh_manager.is_ssh_agent_running():
608
+ return 0
609
+
610
+ success = self.account_manager.switch_account(account_name)
611
+ return 0 if success else 1
612
+
419
613
  def _handle_account_name_shortcut(self, account_name: str) -> int:
420
614
  """Handle account name as shortcut for switch command."""
421
615
  success = self.account_manager.switch_account(account_name)
@@ -0,0 +1,118 @@
1
+ """Directory-based auto-switch rule storage and lookup.
2
+
3
+ Rules map a directory (and everything beneath it) to the account that should
4
+ become active whenever the shell's current working directory is there. This
5
+ is the pure-Python half of the opt-in auto-switch feature; the actual
6
+ "notice I changed directories" trigger comes from a shell hook (see
7
+ `shell_hook.py`) that calls `gitacc rule check` on every prompt render.
8
+ """
9
+
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Dict, Optional
13
+
14
+
15
+ class RulesManager:
16
+ """Manages directory-to-account auto-switch rules."""
17
+
18
+ def __init__(self, rules_file: Optional[Path] = None):
19
+ self.rules_file = rules_file or (Path.home() / ".gitaccrules")
20
+
21
+ def _normalize_path(self, directory: Path) -> str:
22
+ """Resolve a directory to its canonical absolute form."""
23
+ return str(Path(directory).expanduser().resolve())
24
+
25
+ def list_rules(self) -> Dict[str, str]:
26
+ """Read all rules from the rules file.
27
+
28
+ Returns:
29
+ Dictionary mapping normalized directory path to account name, in
30
+ file order. Blank lines and lines starting with '#' are ignored.
31
+ """
32
+ rules: Dict[str, str] = {}
33
+ if not self.rules_file.exists():
34
+ return rules
35
+
36
+ with open(self.rules_file, "r") as f:
37
+ for raw_line in f:
38
+ line = raw_line.strip()
39
+ if not line or line.startswith("#"):
40
+ continue
41
+ match = re.match(r"^(.+?)\s*=\s*(.+)$", line)
42
+ if not match:
43
+ continue
44
+ directory = match.group(1).strip()
45
+ account_name = match.group(2).strip()
46
+ if directory and account_name:
47
+ rules[directory] = account_name
48
+
49
+ return rules
50
+
51
+ def _write_rules(self, rules: Dict[str, str]) -> None:
52
+ with open(self.rules_file, "w") as f:
53
+ for directory, account_name in rules.items():
54
+ f.write(f"{directory} = {account_name}\n")
55
+
56
+ def add_rule(self, directory: Path, account_name: str) -> bool:
57
+ """Add or update the rule for a directory.
58
+
59
+ Args:
60
+ directory: Directory the rule applies to (and its subdirectories)
61
+ account_name: Account to switch to while inside that directory
62
+
63
+ Returns:
64
+ True if successful, False otherwise
65
+ """
66
+ try:
67
+ normalized = self._normalize_path(directory)
68
+ rules = self.list_rules()
69
+ rules[normalized] = account_name
70
+ self._write_rules(rules)
71
+ return True
72
+ except OSError:
73
+ return False
74
+
75
+ def remove_rule(self, directory: Path) -> bool:
76
+ """Remove the rule for a directory, if one exists.
77
+
78
+ Args:
79
+ directory: Directory whose rule should be removed
80
+
81
+ Returns:
82
+ True if a rule was removed, False if none existed or on error
83
+ """
84
+ try:
85
+ normalized = self._normalize_path(directory)
86
+ rules = self.list_rules()
87
+ if normalized not in rules:
88
+ return False
89
+ del rules[normalized]
90
+ self._write_rules(rules)
91
+ return True
92
+ except OSError:
93
+ return False
94
+
95
+ def find_matching_account(self, cwd: Path) -> Optional[str]:
96
+ """Find the account whose rule most specifically matches a directory.
97
+
98
+ Walks from the given directory up through its parents, direnv-style,
99
+ and returns the account for the first (deepest, most specific) rule
100
+ directory that is the given directory or an ancestor of it.
101
+
102
+ Args:
103
+ cwd: Directory to match against registered rules
104
+
105
+ Returns:
106
+ Matching account name, or None if no rule applies
107
+ """
108
+ rules = self.list_rules()
109
+ if not rules:
110
+ return None
111
+
112
+ current = Path(cwd).expanduser().resolve()
113
+ for directory in [current, *current.parents]:
114
+ account_name = rules.get(str(directory))
115
+ if account_name:
116
+ return account_name
117
+
118
+ return None
@@ -0,0 +1,51 @@
1
+ """Shell hook snippets for directory-based auto-switching.
2
+
3
+ These are opt-in: nothing in gitacc installs them automatically. A user adds
4
+ the output of `gitacc rule hook <shell>` to their shell profile, which then
5
+ calls `gitacc rule check` whenever the prompt is rendered (bash) or the
6
+ working directory changes (zsh), so the active account follows whatever
7
+ rules were registered with `gitacc rule add`.
8
+ """
9
+
10
+ from typing import Optional
11
+
12
+ _BASH_HOOK = """\
13
+ _gitacc_hook() {
14
+ local previous_exit_status=$?
15
+ command gitacc rule check
16
+ return $previous_exit_status
17
+ }
18
+ if [[ ";${PROMPT_COMMAND:-};" != *";_gitacc_hook;"* ]]; then
19
+ PROMPT_COMMAND="_gitacc_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
20
+ fi"""
21
+
22
+ _ZSH_HOOK = """\
23
+ _gitacc_hook() {
24
+ command gitacc rule check
25
+ }
26
+ if [[ -z "${chpwd_functions[(r)_gitacc_hook]}" ]]; then
27
+ chpwd_functions+=(_gitacc_hook)
28
+ fi
29
+ _gitacc_hook"""
30
+
31
+ _HOOKS = {
32
+ "bash": _BASH_HOOK,
33
+ "zsh": _ZSH_HOOK,
34
+ }
35
+
36
+
37
+ def get_hook_script(shell: str) -> Optional[str]:
38
+ """Get the shell hook snippet for a given shell.
39
+
40
+ Args:
41
+ shell: Shell name ("bash" or "zsh")
42
+
43
+ Returns:
44
+ Hook script text, or None if the shell isn't supported
45
+ """
46
+ return _HOOKS.get(shell.lower())
47
+
48
+
49
+ def get_supported_shells() -> list:
50
+ """Get the list of shells a hook script can be generated for."""
51
+ return list(_HOOKS.keys())