gitacc-switcher 1.6.0__tar.gz → 1.7.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.6.0/gitacc_switcher.egg-info → gitacc_switcher-1.7.0}/PKG-INFO +1 -1
  2. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/__init__.py +1 -1
  3. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/account_manager.py +213 -0
  4. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/cli.py +62 -0
  5. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/ssh_manager.py +20 -0
  6. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0/gitacc_switcher.egg-info}/PKG-INFO +1 -1
  7. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/pyproject.toml +1 -1
  8. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/setup.py +1 -1
  9. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_account_manager.py +301 -0
  10. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_cli.py +61 -0
  11. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_ssh_manager.py +14 -0
  12. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/LICENSE +0 -0
  13. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/MANIFEST.in +0 -0
  14. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/README.md +0 -0
  15. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/completion.py +0 -0
  16. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/config_manager.py +0 -0
  17. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/hook_manager.py +0 -0
  18. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/rules_manager.py +0 -0
  19. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/shell_hook.py +0 -0
  20. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher/utils.py +0 -0
  21. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher.egg-info/SOURCES.txt +0 -0
  22. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher.egg-info/dependency_links.txt +0 -0
  23. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher.egg-info/entry_points.txt +0 -0
  24. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher.egg-info/requires.txt +0 -0
  25. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/gitacc_switcher.egg-info/top_level.txt +0 -0
  26. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/requirements.txt +0 -0
  27. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/setup.cfg +0 -0
  28. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/__init__.py +0 -0
  29. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_completion.py +0 -0
  30. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_config_manager.py +0 -0
  31. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_hook_manager.py +0 -0
  32. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_rules_manager.py +0 -0
  33. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.0}/tests/test_shell_hook.py +0 -0
  34. {gitacc_switcher-1.6.0 → gitacc_switcher-1.7.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.6.0
3
+ Version: 1.7.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
@@ -1,4 +1,4 @@
1
1
  """Git Account Switcher - Manage multiple Git SSH accounts easily."""
2
2
 
3
- __version__ = "1.6.0"
3
+ __version__ = "1.7.0"
4
4
  __author__ = "ktechhub"
@@ -1,6 +1,7 @@
1
1
  """Account management operations."""
2
2
 
3
3
  import getpass
4
+ import json
4
5
  import subprocess
5
6
  from pathlib import Path
6
7
  from typing import Optional, Dict, List
@@ -629,3 +630,215 @@ class AccountManager:
629
630
  echo_color("y", f"Please switch to the correct account:")
630
631
  echo_color("y", f" gitacc switch {expected_account}")
631
632
  return False
633
+
634
+ def export_accounts(self, output_path: Path, include_keys: bool = False) -> bool:
635
+ """Export registered accounts' metadata to a portable JSON file.
636
+
637
+ Metadata-only by default (name, email, sign preference, key *paths*,
638
+ and any host aliases bound to each account's key) — no key material
639
+ is read or written unless `include_keys` is explicitly set.
640
+
641
+ Args:
642
+ output_path: File to write the export to
643
+ include_keys: If True, also embed each account's private/public
644
+ SSH key file contents in the export. The resulting file will
645
+ contain private key material in plain text; it is written
646
+ with 0600 permissions, but the caller is responsible for
647
+ keeping it secure afterwards.
648
+
649
+ Returns:
650
+ True if successful, False otherwise
651
+ """
652
+ accounts = self.config_manager.read_accounts()
653
+ if not accounts:
654
+ echo_color("y", "No accounts registered yet. Nothing to export.")
655
+ return False
656
+
657
+ host_aliases = self.ssh_manager.list_host_aliases()
658
+
659
+ exported_accounts = {}
660
+ for account_name, info in accounts.items():
661
+ private_key = info.get("private_key", "")
662
+ public_key = info.get("public_key", "")
663
+
664
+ entry = {
665
+ "name": info.get("name", account_name),
666
+ "email": info.get("email", ""),
667
+ "sign": info.get("sign", "false"),
668
+ "private_key": private_key,
669
+ "public_key": public_key,
670
+ }
671
+
672
+ matching_aliases = {
673
+ alias: {"hostname": alias_info["hostname"], "user": alias_info["user"]}
674
+ for alias, alias_info in host_aliases.items()
675
+ if private_key and alias_info.get("identity_file") == private_key
676
+ }
677
+ if matching_aliases:
678
+ entry["host_aliases"] = matching_aliases
679
+
680
+ if include_keys:
681
+ if public_key:
682
+ public_key_content = self.ssh_manager.get_public_key_content(
683
+ public_key
684
+ )
685
+ if public_key_content:
686
+ entry["public_key_content"] = public_key_content
687
+ if private_key:
688
+ private_key_content = self.ssh_manager.get_private_key_content(
689
+ private_key
690
+ )
691
+ if private_key_content:
692
+ entry["private_key_content"] = private_key_content
693
+
694
+ exported_accounts[account_name] = entry
695
+
696
+ export_data = {
697
+ "version": 1,
698
+ "include_keys": include_keys,
699
+ "accounts": exported_accounts,
700
+ }
701
+
702
+ output_path = Path(output_path)
703
+ try:
704
+ with open(output_path, "w") as f:
705
+ json.dump(export_data, f, indent=2)
706
+ f.write("\n")
707
+ if include_keys:
708
+ output_path.chmod(0o600)
709
+ except OSError as e:
710
+ echo_color("r", f"Failed to write export file: {e}")
711
+ return False
712
+
713
+ echo_color(
714
+ "g",
715
+ f'Exported {len(exported_accounts)} account(s) to "{output_path}"',
716
+ )
717
+ if include_keys:
718
+ echo_color(
719
+ "y",
720
+ "This file contains private key material in plain text — "
721
+ "keep it secure (e.g. encrypt it or delete it once transferred).",
722
+ )
723
+ else:
724
+ echo_color(
725
+ "y",
726
+ "Metadata only: key files themselves were not copied. Pass "
727
+ "--include-keys to also embed key material.",
728
+ )
729
+ return True
730
+
731
+ def _write_imported_key_file(
732
+ self, path_str: str, content: str, mode: int, force: bool
733
+ ) -> bool:
734
+ """Write key material from an import file to disk, if safe to do so.
735
+
736
+ Args:
737
+ path_str: Destination path for the key file
738
+ content: Key file content to write
739
+ mode: File permission mode to set (e.g. 0o600 for a private key)
740
+ force: If True, overwrite an existing file at that path
741
+
742
+ Returns:
743
+ True if the file was written, False if skipped or on error
744
+ """
745
+ if not path_str:
746
+ return False
747
+ path = Path(path_str)
748
+ if path.exists() and not force:
749
+ return False
750
+ try:
751
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
752
+ path.write_text(content)
753
+ path.chmod(mode)
754
+ return True
755
+ except OSError:
756
+ return False
757
+
758
+ def import_accounts(self, input_path: Path, force: bool = False) -> bool:
759
+ """Import accounts previously written by `export_accounts`.
760
+
761
+ Args:
762
+ input_path: File previously created with `gitacc export`
763
+ force: If True, overwrite existing accounts, host aliases, and
764
+ key files with the same name/path. Without it, anything
765
+ that already exists is left untouched and skipped.
766
+
767
+ Returns:
768
+ True if the file was read and processed, False if the file
769
+ could not be read or contained no accounts
770
+ """
771
+ input_path = Path(input_path)
772
+ if not input_path.exists():
773
+ echo_color("r", f'Import file not found: "{input_path}"')
774
+ return False
775
+
776
+ try:
777
+ with open(input_path, "r") as f:
778
+ data = json.load(f)
779
+ except (OSError, json.JSONDecodeError) as e:
780
+ echo_color("r", f"Failed to read import file: {e}")
781
+ return False
782
+
783
+ accounts = data.get("accounts", {})
784
+ if not accounts:
785
+ echo_color("y", "No accounts found in import file.")
786
+ return False
787
+
788
+ imported = 0
789
+ skipped = 0
790
+
791
+ for account_name, entry in accounts.items():
792
+ if self.account_exists(account_name) and not force:
793
+ echo_color(
794
+ "y",
795
+ f'Skipping "{account_name}": account already exists '
796
+ "(use --force to overwrite).",
797
+ )
798
+ skipped += 1
799
+ continue
800
+
801
+ private_key = entry.get("private_key", "")
802
+ public_key = entry.get("public_key", "")
803
+
804
+ private_key_content = entry.get("private_key_content")
805
+ if private_key_content:
806
+ self._write_imported_key_file(
807
+ private_key, private_key_content, 0o600, force
808
+ )
809
+ public_key_content = entry.get("public_key_content")
810
+ if public_key_content:
811
+ self._write_imported_key_file(
812
+ public_key, public_key_content, 0o644, force
813
+ )
814
+
815
+ if self.account_exists(account_name):
816
+ self.config_manager.remove_account(account_name)
817
+
818
+ success = self.config_manager.add_account(
819
+ account_name,
820
+ entry.get("name", account_name),
821
+ entry.get("email", ""),
822
+ private_key,
823
+ public_key,
824
+ sign=str(entry.get("sign", "false")).lower() == "true",
825
+ )
826
+ if not success:
827
+ echo_color("r", f'Failed to import account "{account_name}".')
828
+ continue
829
+
830
+ for alias, alias_info in entry.get("host_aliases", {}).items():
831
+ if self.ssh_manager.has_host_alias(alias) and not force:
832
+ continue
833
+ self.ssh_manager.add_host_alias(
834
+ alias,
835
+ alias_info.get("hostname", "github.com"),
836
+ private_key,
837
+ alias_info.get("user", "git"),
838
+ )
839
+
840
+ imported += 1
841
+ echo_color("g", f'Imported account "{account_name}"')
842
+
843
+ echo_color("g", f"Import complete: {imported} imported, {skipped} skipped.")
844
+ return True
@@ -55,6 +55,8 @@ class CLI:
55
55
  self._add_autocomplete_command(subparsers)
56
56
  self._add_rule_command(subparsers)
57
57
  self._add_alias_command(subparsers)
58
+ self._add_export_command(subparsers)
59
+ self._add_import_command(subparsers)
58
60
 
59
61
  # Include account names in top-level completion so `gitacc <TAB>` works for
60
62
  # the `gitacc <account>` shorthand, not just for subcommand names.
@@ -89,6 +91,8 @@ Examples:
89
91
  gitacc rule hook bash Print the shell hook (add to ~/.bashrc)
90
92
  gitacc alias add work github-work Bind a Host alias to an account's key
91
93
  gitacc alias list List managed SSH config host aliases
94
+ gitacc export accounts.json Export account metadata to a file
95
+ gitacc import accounts.json Import accounts from an export file
92
96
  """
93
97
 
94
98
  def _add_add_command(self, subparsers: argparse._SubParsersAction) -> None:
@@ -408,6 +412,50 @@ Examples:
408
412
  )
409
413
  list_parser.set_defaults(func=self._handle_alias_list)
410
414
 
415
+ def _add_export_command(self, subparsers: argparse._SubParsersAction) -> None:
416
+ """Add the 'export' command parser."""
417
+ parser = subparsers.add_parser(
418
+ "export",
419
+ help="Export account metadata to a file",
420
+ description="Export registered accounts (metadata only by "
421
+ "default) to a portable file for backup or migration to "
422
+ "another machine",
423
+ )
424
+ parser.add_argument(
425
+ "output_file",
426
+ help="File to write the export to",
427
+ )
428
+ parser.add_argument(
429
+ "--include-keys",
430
+ dest="include_keys",
431
+ action="store_true",
432
+ help="Also embed each account's private/public SSH key file "
433
+ "contents in the export. The output file will contain private "
434
+ "key material in plain text (written with 0600 permissions) — "
435
+ "keep it secure.",
436
+ )
437
+ parser.set_defaults(func=self._handle_export)
438
+
439
+ def _add_import_command(self, subparsers: argparse._SubParsersAction) -> None:
440
+ """Add the 'import' command parser."""
441
+ parser = subparsers.add_parser(
442
+ "import",
443
+ help="Import accounts from an export file",
444
+ description="Import accounts previously created with 'gitacc export'",
445
+ )
446
+ parser.add_argument(
447
+ "input_file",
448
+ help="File previously created with 'gitacc export'",
449
+ )
450
+ parser.add_argument(
451
+ "--force",
452
+ dest="force",
453
+ action="store_true",
454
+ help="Overwrite existing accounts, host aliases, and key files "
455
+ "with the same name/path",
456
+ )
457
+ parser.set_defaults(func=self._handle_import)
458
+
411
459
  def _handle_autocomplete_install(self, args: argparse.Namespace) -> int:
412
460
  """Handle the 'autocomplete install' command."""
413
461
  if not argcomplete:
@@ -746,6 +794,20 @@ Examples:
746
794
  )
747
795
  return 0
748
796
 
797
+ def _handle_export(self, args: argparse.Namespace) -> int:
798
+ """Handle the 'export' command."""
799
+ success = self.account_manager.export_accounts(
800
+ args.output_file, include_keys=getattr(args, "include_keys", False)
801
+ )
802
+ return 0 if success else 1
803
+
804
+ def _handle_import(self, args: argparse.Namespace) -> int:
805
+ """Handle the 'import' command."""
806
+ success = self.account_manager.import_accounts(
807
+ args.input_file, force=getattr(args, "force", False)
808
+ )
809
+ return 0 if success else 1
810
+
749
811
  def _handle_account_name_shortcut(self, account_name: str) -> int:
750
812
  """Handle account name as shortcut for switch command."""
751
813
  success = self.account_manager.switch_account(account_name)
@@ -310,6 +310,26 @@ class SSHManager:
310
310
  except Exception:
311
311
  return None
312
312
 
313
+ def get_private_key_content(self, private_key_path: str) -> Optional[str]:
314
+ """Read private key file content.
315
+
316
+ Used by `gitacc export --include-keys` to embed key material in an
317
+ export file; callers must handle the returned content as sensitive
318
+ (e.g. write it only to a restrictively-permissioned file).
319
+
320
+ Args:
321
+ private_key_path: Path to private key file
322
+
323
+ Returns:
324
+ Private key content (unmodified, including trailing newline) or
325
+ None on error
326
+ """
327
+ try:
328
+ with open(private_key_path, "r") as f:
329
+ return f.read()
330
+ except Exception:
331
+ return None
332
+
313
333
  def get_ssh_config_path(self) -> Path:
314
334
  """Get the path to the user's SSH config file (~/.ssh/config)."""
315
335
  return self.ssh_dir / "config"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gitacc-switcher
3
- Version: 1.6.0
3
+ Version: 1.7.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gitacc-switcher"
7
- version = "1.6.0"
7
+ version = "1.7.0"
8
8
  description = "Git Account Switcher - Manage multiple Git SSH accounts easily"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.7"
@@ -9,7 +9,7 @@ long_description = readme_file.read_text() if readme_file.exists() else ""
9
9
 
10
10
  setup(
11
11
  name="gitacc-switcher",
12
- version="1.6.0",
12
+ version="1.7.0",
13
13
  description="Git Account Switcher - Manage multiple Git SSH accounts easily",
14
14
  long_description=long_description,
15
15
  long_description_content_type="text/markdown",
@@ -1,8 +1,11 @@
1
1
  """Tests for AccountManager — orchestration of account operations."""
2
2
 
3
+ import json
3
4
  import pytest
4
5
  from unittest.mock import patch, MagicMock
5
6
  from gitacc_switcher.account_manager import AccountManager
7
+ from gitacc_switcher.config_manager import ConfigManager
8
+ from gitacc_switcher.ssh_manager import SSHManager
6
9
 
7
10
 
8
11
  @pytest.fixture
@@ -653,3 +656,301 @@ class TestListHostAliases:
653
656
  def test_empty(self, manager):
654
657
  manager.ssh_manager.list_host_aliases.return_value = {}
655
658
  assert manager.list_host_aliases() == {}
659
+
660
+
661
+ class TestExportAccounts:
662
+ def test_fails_when_no_accounts(self, manager, tmp_path):
663
+ manager.config_manager.read_accounts.return_value = {}
664
+ assert manager.export_accounts(tmp_path / "out.json") is False
665
+
666
+ def test_writes_metadata_only_by_default(self, manager, tmp_path):
667
+ manager.config_manager.read_accounts.return_value = {"work": WORK_ACCOUNT}
668
+ manager.ssh_manager.list_host_aliases.return_value = {}
669
+ output = tmp_path / "out.json"
670
+
671
+ assert manager.export_accounts(output) is True
672
+
673
+ data = json.loads(output.read_text())
674
+ assert data["include_keys"] is False
675
+ work = data["accounts"]["work"]
676
+ assert work["name"] == "Work User"
677
+ assert work["email"] == "work@company.com"
678
+ assert work["private_key"] == WORK_ACCOUNT["private_key"]
679
+ assert "private_key_content" not in work
680
+ assert "public_key_content" not in work
681
+ manager.ssh_manager.get_private_key_content.assert_not_called()
682
+
683
+ def test_includes_key_content_when_opted_in(self, manager, tmp_path):
684
+ manager.config_manager.read_accounts.return_value = {"work": WORK_ACCOUNT}
685
+ manager.ssh_manager.list_host_aliases.return_value = {}
686
+ manager.ssh_manager.get_public_key_content.return_value = "ssh-rsa AAAA"
687
+ manager.ssh_manager.get_private_key_content.return_value = "PRIVATE-DATA"
688
+ output = tmp_path / "out.json"
689
+
690
+ assert manager.export_accounts(output, include_keys=True) is True
691
+
692
+ data = json.loads(output.read_text())
693
+ work = data["accounts"]["work"]
694
+ assert work["private_key_content"] == "PRIVATE-DATA"
695
+ assert work["public_key_content"] == "ssh-rsa AAAA"
696
+ assert (output.stat().st_mode & 0o777) == 0o600
697
+
698
+ def test_includes_host_aliases_bound_to_account_key(self, manager, tmp_path):
699
+ manager.config_manager.read_accounts.return_value = {"work": WORK_ACCOUNT}
700
+ manager.ssh_manager.list_host_aliases.return_value = {
701
+ "github-work": {
702
+ "hostname": "github.com",
703
+ "user": "git",
704
+ "identity_file": WORK_ACCOUNT["private_key"],
705
+ },
706
+ "other-alias": {
707
+ "hostname": "gitlab.com",
708
+ "user": "git",
709
+ "identity_file": "/home/user/.ssh/id_rsa_other",
710
+ },
711
+ }
712
+ output = tmp_path / "out.json"
713
+
714
+ assert manager.export_accounts(output) is True
715
+
716
+ work = json.loads(output.read_text())["accounts"]["work"]
717
+ assert work["host_aliases"] == {
718
+ "github-work": {"hostname": "github.com", "user": "git"}
719
+ }
720
+
721
+
722
+ class TestImportAccounts:
723
+ def _write_export(self, tmp_path, accounts, include_keys=False):
724
+ export_file = tmp_path / "export.json"
725
+ export_file.write_text(
726
+ json.dumps(
727
+ {"version": 1, "include_keys": include_keys, "accounts": accounts}
728
+ )
729
+ )
730
+ return export_file
731
+
732
+ def test_fails_when_file_missing(self, manager, tmp_path):
733
+ assert manager.import_accounts(tmp_path / "nope.json") is False
734
+
735
+ def test_fails_when_no_accounts_in_file(self, manager, tmp_path):
736
+ export_file = self._write_export(tmp_path, {})
737
+ assert manager.import_accounts(export_file) is False
738
+
739
+ def test_imports_new_account(self, manager, tmp_path):
740
+ export_file = self._write_export(
741
+ tmp_path,
742
+ {
743
+ "work": {
744
+ "name": "Work User",
745
+ "email": "work@company.com",
746
+ "sign": "false",
747
+ "private_key": "/home/user/.ssh/id_rsa_work",
748
+ "public_key": "/home/user/.ssh/id_rsa_work.pub",
749
+ }
750
+ },
751
+ )
752
+ manager.config_manager.get_account.return_value = None
753
+ manager.config_manager.add_account.return_value = True
754
+
755
+ assert manager.import_accounts(export_file) is True
756
+
757
+ manager.config_manager.add_account.assert_called_once_with(
758
+ "work",
759
+ "Work User",
760
+ "work@company.com",
761
+ "/home/user/.ssh/id_rsa_work",
762
+ "/home/user/.ssh/id_rsa_work.pub",
763
+ sign=False,
764
+ )
765
+ manager.config_manager.remove_account.assert_not_called()
766
+
767
+ def test_skips_existing_account_without_force(self, manager, tmp_path):
768
+ export_file = self._write_export(
769
+ tmp_path,
770
+ {
771
+ "work": {
772
+ "name": "Work User",
773
+ "email": "work@company.com",
774
+ "private_key": "/home/user/.ssh/id_rsa_work",
775
+ "public_key": "/home/user/.ssh/id_rsa_work.pub",
776
+ }
777
+ },
778
+ )
779
+ manager.config_manager.get_account.return_value = WORK_ACCOUNT
780
+
781
+ assert manager.import_accounts(export_file) is True
782
+
783
+ manager.config_manager.add_account.assert_not_called()
784
+
785
+ def test_force_overwrites_existing_account(self, manager, tmp_path):
786
+ export_file = self._write_export(
787
+ tmp_path,
788
+ {
789
+ "work": {
790
+ "name": "New Name",
791
+ "email": "work@company.com",
792
+ "private_key": "/home/user/.ssh/id_rsa_work",
793
+ "public_key": "/home/user/.ssh/id_rsa_work.pub",
794
+ }
795
+ },
796
+ )
797
+ manager.config_manager.get_account.return_value = WORK_ACCOUNT
798
+ manager.config_manager.add_account.return_value = True
799
+
800
+ assert manager.import_accounts(export_file, force=True) is True
801
+
802
+ manager.config_manager.remove_account.assert_called_once_with("work")
803
+ manager.config_manager.add_account.assert_called_once()
804
+
805
+ def test_writes_key_material_when_present(self, manager, tmp_path):
806
+ private_key = tmp_path / "id_rsa_work"
807
+ public_key = tmp_path / "id_rsa_work.pub"
808
+ export_file = self._write_export(
809
+ tmp_path,
810
+ {
811
+ "work": {
812
+ "name": "Work User",
813
+ "email": "work@company.com",
814
+ "private_key": str(private_key),
815
+ "public_key": str(public_key),
816
+ "private_key_content": "PRIVATE-DATA",
817
+ "public_key_content": "ssh-rsa AAAA",
818
+ }
819
+ },
820
+ include_keys=True,
821
+ )
822
+ manager.config_manager.get_account.return_value = None
823
+ manager.config_manager.add_account.return_value = True
824
+
825
+ assert manager.import_accounts(export_file) is True
826
+
827
+ assert private_key.read_text() == "PRIVATE-DATA"
828
+ assert public_key.read_text() == "ssh-rsa AAAA"
829
+ assert (private_key.stat().st_mode & 0o777) == 0o600
830
+
831
+ def test_does_not_overwrite_existing_key_file_without_force(
832
+ self, manager, tmp_path
833
+ ):
834
+ private_key = tmp_path / "id_rsa_work"
835
+ private_key.write_text("ORIGINAL")
836
+ export_file = self._write_export(
837
+ tmp_path,
838
+ {
839
+ "work": {
840
+ "name": "Work User",
841
+ "email": "work@company.com",
842
+ "private_key": str(private_key),
843
+ "public_key": str(tmp_path / "id_rsa_work.pub"),
844
+ "private_key_content": "IMPORTED-DATA",
845
+ }
846
+ },
847
+ include_keys=True,
848
+ )
849
+ manager.config_manager.get_account.return_value = None
850
+ manager.config_manager.add_account.return_value = True
851
+
852
+ manager.import_accounts(export_file)
853
+
854
+ assert private_key.read_text() == "ORIGINAL"
855
+
856
+ def test_imports_host_aliases(self, manager, tmp_path):
857
+ export_file = self._write_export(
858
+ tmp_path,
859
+ {
860
+ "work": {
861
+ "name": "Work User",
862
+ "email": "work@company.com",
863
+ "private_key": "/home/user/.ssh/id_rsa_work",
864
+ "public_key": "/home/user/.ssh/id_rsa_work.pub",
865
+ "host_aliases": {
866
+ "github-work": {"hostname": "github.com", "user": "git"}
867
+ },
868
+ }
869
+ },
870
+ )
871
+ manager.config_manager.get_account.return_value = None
872
+ manager.config_manager.add_account.return_value = True
873
+ manager.ssh_manager.has_host_alias.return_value = False
874
+
875
+ manager.import_accounts(export_file)
876
+
877
+ manager.ssh_manager.add_host_alias.assert_called_once_with(
878
+ "github-work",
879
+ "github.com",
880
+ "/home/user/.ssh/id_rsa_work",
881
+ "git",
882
+ )
883
+
884
+
885
+ class TestExportImportRoundTrip:
886
+ """Round-trips a real (unmocked) config through export then import."""
887
+
888
+ def _real_manager(self, tmp_path, label):
889
+ config = ConfigManager.__new__(ConfigManager)
890
+ config.gitacc_file = tmp_path / f"{label}.gitacc"
891
+ config._ensure_gitacc_file()
892
+
893
+ ssh = SSHManager.__new__(SSHManager)
894
+ ssh.ssh_dir = tmp_path / f"{label}-ssh"
895
+ ssh.ssh_dir.mkdir(mode=0o700)
896
+
897
+ mgr = AccountManager.__new__(AccountManager)
898
+ mgr.config_manager = config
899
+ mgr.ssh_manager = ssh
900
+ return mgr
901
+
902
+ def test_round_trip_metadata_only(self, tmp_path):
903
+ source = self._real_manager(tmp_path, "source")
904
+ key = source.ssh_manager.ssh_dir / "id_rsa_work"
905
+ key.write_text("PRIVATE")
906
+ pub = source.ssh_manager.ssh_dir / "id_rsa_work.pub"
907
+ pub.write_text("PUBLIC")
908
+ assert source.config_manager.add_account(
909
+ "work", "Work User", "work@company.com", str(key), str(pub), sign=False
910
+ )
911
+
912
+ export_file = tmp_path / "export.json"
913
+ assert source.export_accounts(export_file) is True
914
+
915
+ target = self._real_manager(tmp_path, "target")
916
+ assert target.import_accounts(export_file) is True
917
+
918
+ imported = target.config_manager.read_accounts()
919
+ assert imported["work"]["name"] == "Work User"
920
+ assert imported["work"]["email"] == "work@company.com"
921
+ assert imported["work"]["private_key"] == str(key)
922
+ # Metadata-only: no key material was embedded, so nothing is written
923
+ # to disk at the target other than the .gitacc entry itself.
924
+ assert not (target.ssh_manager.ssh_dir / "id_rsa_work").exists()
925
+
926
+ def test_round_trip_with_keys_restores_key_files(self, tmp_path):
927
+ source = self._real_manager(tmp_path, "shared")
928
+ key = source.ssh_manager.ssh_dir / "id_rsa_work"
929
+ key.write_text("PRIVATE-CONTENT")
930
+ pub = source.ssh_manager.ssh_dir / "id_rsa_work.pub"
931
+ pub.write_text("PUBLIC-CONTENT")
932
+ assert source.config_manager.add_account(
933
+ "work", "Work User", "work@company.com", str(key), str(pub), sign=False
934
+ )
935
+
936
+ export_file = tmp_path / "export.json"
937
+ assert source.export_accounts(export_file, include_keys=True) is True
938
+
939
+ # Simulate a fresh machine: a separate .gitacc, and the key files
940
+ # for this account are gone (never existed there).
941
+ key.unlink()
942
+ pub.unlink()
943
+ target = AccountManager.__new__(AccountManager)
944
+ target_config = ConfigManager.__new__(ConfigManager)
945
+ target_config.gitacc_file = tmp_path / "fresh.gitacc"
946
+ target_config._ensure_gitacc_file()
947
+ target.config_manager = target_config
948
+ target.ssh_manager = source.ssh_manager # same ~/.ssh path on "this machine"
949
+
950
+ assert target.import_accounts(export_file) is True
951
+
952
+ assert key.read_text() == "PRIVATE-CONTENT"
953
+ assert pub.read_text() == "PUBLIC-CONTENT"
954
+ assert (key.stat().st_mode & 0o777) == 0o600
955
+ imported = target_config.read_accounts()
956
+ assert imported["work"]["private_key"] == str(key)
@@ -674,3 +674,64 @@ class TestAliasCommandHandlers:
674
674
  out = capsys.readouterr().out
675
675
  assert "github-work" in out
676
676
  assert "git@github.com" in out
677
+
678
+
679
+ # ---------------------------------------------------------------------------
680
+ # `export` / `import` commands
681
+ # ---------------------------------------------------------------------------
682
+
683
+
684
+ class TestExportImportParserCommands:
685
+ def test_export_parses_output_file(self, cli):
686
+ args = cli.parser.parse_args(["export", "accounts.json"])
687
+ assert args.command == "export"
688
+ assert args.output_file == "accounts.json"
689
+ assert args.include_keys is False
690
+
691
+ def test_export_include_keys_flag(self, cli):
692
+ args = cli.parser.parse_args(["export", "accounts.json", "--include-keys"])
693
+ assert args.include_keys is True
694
+
695
+ def test_import_parses_input_file(self, cli):
696
+ args = cli.parser.parse_args(["import", "accounts.json"])
697
+ assert args.command == "import"
698
+ assert args.input_file == "accounts.json"
699
+ assert args.force is False
700
+
701
+ def test_import_force_flag(self, cli):
702
+ args = cli.parser.parse_args(["import", "accounts.json", "--force"])
703
+ assert args.force is True
704
+
705
+
706
+ class TestExportImportHandlers:
707
+ def test_handle_export_success(self, cli):
708
+ args = argparse.Namespace(output_file="accounts.json", include_keys=False)
709
+ cli.account_manager.export_accounts.return_value = True
710
+ assert cli._handle_export(args) == 0
711
+ cli.account_manager.export_accounts.assert_called_once_with(
712
+ "accounts.json", include_keys=False
713
+ )
714
+
715
+ def test_handle_export_failure(self, cli):
716
+ args = argparse.Namespace(output_file="accounts.json", include_keys=True)
717
+ cli.account_manager.export_accounts.return_value = False
718
+ assert cli._handle_export(args) == 1
719
+ cli.account_manager.export_accounts.assert_called_once_with(
720
+ "accounts.json", include_keys=True
721
+ )
722
+
723
+ def test_handle_import_success(self, cli):
724
+ args = argparse.Namespace(input_file="accounts.json", force=False)
725
+ cli.account_manager.import_accounts.return_value = True
726
+ assert cli._handle_import(args) == 0
727
+ cli.account_manager.import_accounts.assert_called_once_with(
728
+ "accounts.json", force=False
729
+ )
730
+
731
+ def test_handle_import_failure(self, cli):
732
+ args = argparse.Namespace(input_file="accounts.json", force=True)
733
+ cli.account_manager.import_accounts.return_value = False
734
+ assert cli._handle_import(args) == 1
735
+ cli.account_manager.import_accounts.assert_called_once_with(
736
+ "accounts.json", force=True
737
+ )
@@ -185,6 +185,20 @@ class TestGetPublicKeyContent:
185
185
  assert ssh.get_public_key_content(str(tmp_path / "nonexistent.pub")) is None
186
186
 
187
187
 
188
+ class TestGetPrivateKeyContent:
189
+ def test_reads_content(self, ssh, tmp_path):
190
+ priv_key = tmp_path / "id_rsa_test"
191
+ priv_key.write_text(
192
+ "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----\n"
193
+ )
194
+ assert ssh.get_private_key_content(str(priv_key)) == (
195
+ "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----\n"
196
+ )
197
+
198
+ def test_returns_none_for_missing_file(self, ssh, tmp_path):
199
+ assert ssh.get_private_key_content(str(tmp_path / "nonexistent")) is None
200
+
201
+
188
202
  class TestGetAgentFingerprints:
189
203
  def test_returns_fingerprints_for_loaded_keys(self, ssh):
190
204
  output = (
File without changes