git-well 0.2.4__tar.gz → 0.3.2__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 (70) hide show
  1. git_well-0.3.2/PKG-INFO +53 -0
  2. {git_well-0.2.4 → git_well-0.3.2}/README.rst +135 -0
  3. {git_well-0.2.4 → git_well-0.3.2}/git_well/__init__.py +3 -1
  4. {git_well-0.2.4 → git_well-0.3.2}/git_well/__main__.py +3 -0
  5. git_well-0.3.2/git_well/_utils.py +380 -0
  6. {git_well-0.2.4 → git_well-0.3.2}/git_well/demo/__init__.py +16 -10
  7. git_well-0.3.2/git_well/git_archive_source.py +1571 -0
  8. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_autoconf_gpgsign.py +138 -52
  9. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_branch_cleanup.py +47 -20
  10. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_branch_upgrade.py +33 -15
  11. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_discover_remote.py +103 -44
  12. git_well-0.3.2/git_well/git_rebase_add_continue.py +203 -0
  13. git_well-0.3.2/git_well/git_remote_protocol.py +206 -0
  14. git_well-0.3.2/git_well/git_squash.py +148 -0
  15. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_squash_streaks.py +366 -250
  16. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_stats.py +50 -12
  17. git_well-0.3.2/git_well/git_sync.py +349 -0
  18. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_track_upstream.py +44 -16
  19. {git_well-0.2.4 → git_well-0.3.2}/git_well/git_url_components.py +30 -11
  20. git_well-0.3.2/git_well/ipfs.py +1143 -0
  21. {git_well-0.2.4 → git_well-0.3.2}/git_well/main.py +10 -4
  22. git_well-0.3.2/git_well/patchdir/__init__.py +1 -0
  23. git_well-0.3.2/git_well/patchdir/git_patchdir_apply.py +164 -0
  24. git_well-0.3.2/git_well/patchdir/git_patchdir_save.py +101 -0
  25. git_well-0.3.2/git_well/patchdir/patchdir_modal.py +16 -0
  26. {git_well-0.2.4 → git_well-0.3.2}/git_well/repo.py +31 -16
  27. git_well-0.3.2/git_well.egg-info/PKG-INFO +53 -0
  28. {git_well-0.2.4 → git_well-0.3.2}/git_well.egg-info/SOURCES.txt +10 -16
  29. {git_well-0.2.4 → git_well-0.3.2}/git_well.egg-info/entry_points.txt +2 -0
  30. git_well-0.3.2/git_well.egg-info/requires.txt +71 -0
  31. git_well-0.3.2/pyproject.toml +188 -0
  32. {git_well-0.2.4 → git_well-0.3.2}/requirements/optional.txt +2 -0
  33. {git_well-0.2.4 → git_well-0.3.2}/requirements/runtime.txt +2 -1
  34. git_well-0.3.2/requirements/tests.txt +14 -0
  35. git_well-0.3.2/tests/test_bugfixes.py +284 -0
  36. git_well-0.3.2/tests/test_cli.py +817 -0
  37. git_well-0.3.2/tests/test_import.py +2 -0
  38. git_well-0.3.2/tests/test_ipfs.py +307 -0
  39. git_well-0.2.4/PKG-INFO +0 -350
  40. git_well-0.2.4/git_well/__main__.pyi +0 -1
  41. git_well-0.2.4/git_well/_utils.py +0 -262
  42. git_well-0.2.4/git_well/_utils.pyi +0 -18
  43. git_well-0.2.4/git_well/git_autoconf_gpgsign.pyi +0 -33
  44. git_well-0.2.4/git_well/git_branch_cleanup.pyi +0 -18
  45. git_well-0.2.4/git_well/git_branch_upgrade.pyi +0 -19
  46. git_well-0.2.4/git_well/git_discover_remote.pyi +0 -25
  47. git_well-0.2.4/git_well/git_rebase_add_continue.py +0 -208
  48. git_well-0.2.4/git_well/git_rebase_add_continue.pyi +0 -20
  49. git_well-0.2.4/git_well/git_remote_protocol.py +0 -136
  50. git_well-0.2.4/git_well/git_remote_protocol.pyi +0 -38
  51. git_well-0.2.4/git_well/git_squash_streaks.pyi +0 -134
  52. git_well-0.2.4/git_well/git_stats.pyi +0 -22
  53. git_well-0.2.4/git_well/git_sync.py +0 -295
  54. git_well-0.2.4/git_well/git_sync.pyi +0 -38
  55. git_well-0.2.4/git_well/git_track_upstream.pyi +0 -20
  56. git_well-0.2.4/git_well/main.pyi +0 -9
  57. git_well-0.2.4/git_well/repo.pyi +0 -31
  58. git_well-0.2.4/git_well.egg-info/PKG-INFO +0 -350
  59. git_well-0.2.4/git_well.egg-info/requires.txt +0 -386
  60. git_well-0.2.4/pyproject.toml +0 -44
  61. git_well-0.2.4/requirements/tests.txt +0 -37
  62. git_well-0.2.4/setup.py +0 -259
  63. git_well-0.2.4/tests/test_cli.py +0 -19
  64. git_well-0.2.4/tests/test_import.py +0 -2
  65. {git_well-0.2.4 → git_well-0.3.2}/MANIFEST.in +0 -0
  66. {git_well-0.2.4 → git_well-0.3.2}/git_well/py.typed +0 -0
  67. {git_well-0.2.4 → git_well-0.3.2}/git_well.egg-info/dependency_links.txt +0 -0
  68. {git_well-0.2.4 → git_well-0.3.2}/git_well.egg-info/top_level.txt +0 -0
  69. {git_well-0.2.4 → git_well-0.3.2}/requirements/docs.txt +0 -0
  70. {git_well-0.2.4 → git_well-0.3.2}/setup.cfg +0 -0
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: git_well
3
+ Version: 0.3.2
4
+ Summary: The git_well module
5
+ Author-email: Jon Crall <erotemic@gmail.com>
6
+ License: Apache 2
7
+ Project-URL: Homepage, https://github.com/Erotemic/git_well
8
+ Classifier: Development Status :: 1 - Planning
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: ubelt>=1.3.3
19
+ Requires-Dist: kwconf>=0.10.0; python_version >= "3.10"
20
+ Requires-Dist: rich>=12.4.4; python_version >= "3.8"
21
+ Requires-Dist: rich>=11.2.0; python_version < "3.8" and python_version >= "3.6"
22
+ Requires-Dist: git-python>=1.0.0; python_version >= "2.7"
23
+ Requires-Dist: packaging>=21.3
24
+ Requires-Dist: pyyaml>=6.0
25
+ Requires-Dist: networkx>=2.8; python_version < "4.0" and python_version >= "3.11"
26
+ Requires-Dist: networkx>=2.7; python_version < "3.11" and python_version >= "3.8"
27
+ Requires-Dist: networkx>=2.6.2; python_version < "3.8" and python_version >= "3.7"
28
+ Requires-Dist: networkx<=2.5.1,>=2.2.0; python_version < "3.7.0" and python_version >= "3.6.0"
29
+ Provides-Extra: docs
30
+ Requires-Dist: sphinx>=5.0.1; extra == "docs"
31
+ Requires-Dist: sphinx-autobuild>=2021.3.14; extra == "docs"
32
+ Requires-Dist: sphinx_rtd_theme>=1.0.0; extra == "docs"
33
+ Requires-Dist: sphinxcontrib-napoleon>=0.7; extra == "docs"
34
+ Requires-Dist: sphinx-autoapi>=1.8.4; extra == "docs"
35
+ Requires-Dist: Pygments>=2.9.0; extra == "docs"
36
+ Requires-Dist: myst_parser>=0.18.0; extra == "docs"
37
+ Requires-Dist: sphinx-reredirects>=0.0.1; extra == "docs"
38
+ Provides-Extra: optional
39
+ Requires-Dist: argcomplete>=1.0; extra == "optional"
40
+ Requires-Dist: rich_argparse>=1.1.0; python_version >= "3.7" and extra == "optional"
41
+ Requires-Dist: fsspec; extra == "optional"
42
+ Requires-Dist: paramiko; extra == "optional"
43
+ Provides-Extra: tests
44
+ Requires-Dist: xdoctest>=1.1.5; extra == "tests"
45
+ Requires-Dist: pytest>=8.1.1; (python_version < "4.0" and python_version >= "3.13") and extra == "tests"
46
+ Requires-Dist: pytest>=8.1.1; python_version < "3.13" and extra == "tests"
47
+ Requires-Dist: pytest-cov>=3.0.0; extra == "tests"
48
+ Requires-Dist: pytest_timeout>=2.3.1; (python_version < "4.0" and python_version >= "3.12") and extra == "tests"
49
+ Requires-Dist: pytest_timeout>=1.4.2; python_version < "3.12" and extra == "tests"
50
+ Requires-Dist: coverage>=7.3.0; (python_version < "4.0" and python_version >= "3.12") and extra == "tests"
51
+ Requires-Dist: coverage>=6.1.1; (python_version < "3.12" and python_version >= "3.10") and extra == "tests"
52
+ Requires-Dist: coverage>=5.3.1; (python_version < "3.10" and python_version >= "3.9") and extra == "tests"
53
+ Requires-Dist: coverage>=6.1.1; (python_version < "3.9" and python_version >= "3.8") and extra == "tests"
@@ -95,6 +95,141 @@ The tools in this module are derived from:
95
95
 
96
96
 
97
97
 
98
+ Tracking large files with IPFS
99
+ ------------------------------
100
+
101
+ ``git-well`` also exposes an experimental ``git ipfs`` helper for keeping
102
+ large payloads out of Git while tracking reproducible IPFS CIDs in small
103
+ ``*.ipfs`` sidecar files. There is intentionally no repository-local IPFS
104
+ store and no required ``git ipfs init`` step: Kubo still owns its normal
105
+ ``$IPFS_PATH`` repository, while Git only tracks small sidecar metadata.
106
+
107
+ The minimum supported Kubo version is **0.37.0**. This is the first Kubo
108
+ release with ``ipfs add --pin-name``, which ``git ipfs add --name`` uses to
109
+ assign a human-readable name at import time.
110
+
111
+ The intended happy path is:
112
+
113
+ .. code:: bash
114
+
115
+ git ipfs doctor
116
+ git ipfs add data/ --name my-data
117
+ git commit -m "Track data with IPFS"
118
+
119
+ When you know the peer that is likely to provide the content, record it during
120
+ add:
121
+
122
+ .. code:: bash
123
+
124
+ git ipfs add data/ --name my-data --suggested-peers 12D3KooW...
125
+
126
+ A collaborator can then materialize the payloads with:
127
+
128
+ .. code:: bash
129
+
130
+ git clone <repo-url>
131
+ cd <repo>
132
+ git ipfs doctor
133
+ git ipfs pull
134
+
135
+ The sidecar stores the CID, relative path, object kind, byte size, and the
136
+ CID-affecting import settings. Volatile local details such as mtimes, command
137
+ elapsed time, and machine-specific cache state are intentionally left out of
138
+ the committed sidecar so repeated runs stay reviewable.
139
+
140
+ Sidecar schema v1
141
+ ~~~~~~~~~~~~~~~~~
142
+
143
+ The ``schema_version: 1`` contract is intentionally small and YAML-first.
144
+ Unknown fields should be ignored by readers, and fields that are not needed to
145
+ materialize content should be treated as advisory. This keeps hand-written
146
+ sidecars easy to review and gives future versions room to add optional metadata
147
+ without breaking old repositories.
148
+
149
+ .. code:: yaml
150
+
151
+ schema_version: 1
152
+ type: ipfs-sidecar
153
+ cid: bafy...
154
+ rel_path: data
155
+ kind: directory
156
+ size_bytes: 123456
157
+ num_files: 42
158
+ pin_name: my-data
159
+ import:
160
+ recursive: true
161
+ cid_version: 1
162
+ raw_leaves: false
163
+ suggested_peers:
164
+ - 12D3KooW...
165
+ - /ip4/203.0.113.10/tcp/4001/p2p/12D3KooW...
166
+
167
+ Required fields for materialization are ``cid`` and ``rel_path``. The
168
+ ``import`` mapping records options that affect CID reproducibility.
169
+ ``pin_name``, sizes, counts, and ``suggested_peers`` are useful metadata, but a
170
+ reader should still be able to pull content without them.
171
+
172
+ Sidecars may include peer hints. Bare peer IDs are useful hints when routing
173
+ can discover addresses; full multiaddrs are more reliable when known.
174
+ ``git ipfs pull`` makes a best-effort attempt to connect to ``suggested_peers``
175
+ before downloading. Peer hints can also be inspected or connected manually:
176
+
177
+ .. code:: bash
178
+
179
+ git ipfs peers
180
+ git ipfs peers --connect
181
+
182
+ To make the data retrievable by others, configure a Kubo remote pinning service
183
+ and push sidecar CIDs:
184
+
185
+ .. code:: bash
186
+
187
+ ipfs pin remote service add <service-name> <endpoint> <key>
188
+ git ipfs push --service <service-name>
189
+
190
+ Useful inspection commands:
191
+
192
+ .. code:: bash
193
+
194
+ git ipfs status
195
+ git ipfs status --full
196
+ git ipfs export --emit_bash
197
+
198
+ Dogfood checklist
199
+ ~~~~~~~~~~~~~~~~~
200
+
201
+ When changing this workflow, test it on a scratch branch with a small real
202
+ payload before publishing the change:
203
+
204
+ .. code:: bash
205
+
206
+ git ipfs doctor
207
+ mkdir -p .git-well-ipfs-smoke
208
+ printf 'hello from git ipfs\n' > .git-well-ipfs-smoke/payload.txt
209
+ git ipfs add .git-well-ipfs-smoke --name git-well-ipfs-smoke
210
+ git status --short .gitignore .git-well-ipfs-smoke.ipfs
211
+ rm -rf .git-well-ipfs-smoke
212
+ git ipfs pull .git-well-ipfs-smoke.ipfs
213
+ git ipfs status .git-well-ipfs-smoke.ipfs
214
+
215
+ The helper script ``dev/ipfs_dogfood_smoke.sh`` runs the same smoke flow and
216
+ accepts an optional peer hint as its second argument.
217
+
218
+ Troubleshooting
219
+ ~~~~~~~~~~~~~~~
220
+
221
+ ``git ipfs doctor`` is the first command to run when retrieval is confusing.
222
+ Common failure modes are reported with actionable hints:
223
+
224
+ * ``ipfs`` is missing from ``PATH``: install Kubo >= 0.37.0.
225
+ * The Kubo repo is missing: run ``ipfs init`` for Kubo itself. This does not
226
+ create anything inside the Git repository.
227
+ * The daemon/API is offline: start ``ipfs daemon`` or check ``IPFS_PATH``.
228
+ * Retrieval cannot find a CID: check that someone is pinning the content, then
229
+ try ``git ipfs peers --connect`` or add more specific ``suggested_peers``.
230
+ * Named pins fail: upgrade to Kubo >= 0.37.0 or omit ``--name``.
231
+
232
+
98
233
  Use Cases
99
234
  ---------
100
235
 
@@ -1,7 +1,9 @@
1
+ from __future__ import annotations
2
+
1
3
  """
2
4
  Basic
3
5
  """
4
- __version__ = '0.2.4'
6
+ __version__ = '0.3.2'
5
7
  __author__ = 'Jon Crall'
6
8
  __author_email__ = 'erotemic@gmail.com'
7
9
  __url__ = 'https://github.com/Erotemic/git_well/'
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env python3
2
2
  # PYTHON_ARGCOMPLETE_OK
3
+ from __future__ import annotations
4
+
3
5
  from .main import main
6
+
4
7
  if __name__ == '__main__':
5
8
  """
6
9
  CommandLine:
@@ -0,0 +1,380 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Any, TypedDict
6
+
7
+ import ubelt as ub
8
+
9
+
10
+ def rich_print(*args: Any, **kwargs: Any) -> Any:
11
+ try:
12
+ from rich import print as rich_printer
13
+ except Exception:
14
+ return print(*args, **kwargs)
15
+ else:
16
+ return rich_printer(*args, **kwargs)
17
+
18
+
19
+ def rich_link_path(path: str | os.PathLike[str]) -> str:
20
+ """
21
+ Return rich markup that makes a filesystem path clickable.
22
+
23
+ This intentionally uses rich's link markup form so terminals that support
24
+ hyperlinks can open local paths directly. Callers should print this with
25
+ :func:`rich_print` or :func:`rich_print_path` when rich is available.
26
+ """
27
+ path_text = os.fspath(path)
28
+ return f'[link={path_text}]{path_text}[/link]'
29
+
30
+
31
+ def rich_print_path(
32
+ prefix: str,
33
+ path: str | os.PathLike[str],
34
+ suffix: str = '',
35
+ **kwargs: Any,
36
+ ) -> Any:
37
+ """
38
+ Print a filesystem path as a rich hyperlink when rich is available.
39
+
40
+ If rich cannot be imported, fall back to builtin :func:`print` with the
41
+ plain path text so users do not see raw rich markup.
42
+ """
43
+ path_text = os.fspath(path)
44
+ try:
45
+ from rich import print as rich_printer
46
+ except Exception:
47
+ msg = f'{prefix}{path_text}{suffix}'
48
+ return print(msg, **kwargs)
49
+ else:
50
+ msg = f'{prefix}{rich_link_path(path_text)}{suffix}'
51
+ return rich_printer(msg, **kwargs)
52
+
53
+
54
+ def cmd_output_text(output: str | bytes | None) -> str:
55
+ """Normalize command output into text.
56
+
57
+ ``ub.cmd`` can be configured to return text, bytes, or no captured output.
58
+ Centralizing this conversion keeps call sites honest and makes the expected
59
+ behavior visible to static type checkers.
60
+ """
61
+ if output is None:
62
+ return ''
63
+ if isinstance(output, bytes):
64
+ return output.decode(errors='replace')
65
+ return output
66
+
67
+
68
+ def find_merged_branches(repo: Any, main_branch: str = 'main') -> Any:
69
+ # git branch --merged main
70
+ # main_branch = 'main'
71
+ merged_branch_names = [
72
+ p.replace('*', '').strip()
73
+ for p in repo.git.branch(merged=main_branch).split('\n')
74
+ if p.strip()
75
+ ]
76
+ merged_branches = ub.oset(merged_branch_names) - {main_branch}
77
+ return merged_branches
78
+
79
+
80
+ def confirm(msg: str) -> bool:
81
+ try:
82
+ from rich import prompt
83
+
84
+ ret = prompt.Confirm.ask(msg)
85
+ except ImportError:
86
+ while True:
87
+ ans = input(msg + ' [y/n]')
88
+ if ans in {'y', 'yes'}:
89
+ ret = True
90
+ break
91
+ elif ans in {'n', 'no'}:
92
+ ret = False
93
+ break
94
+ else:
95
+ print('invalid response')
96
+ return ret
97
+
98
+
99
+ def choice_prompt(msg: str, choices: list[str]) -> str:
100
+ """
101
+ Ignore:
102
+ choice_prompt('which one?', choices=['a', 'b', 'c'])
103
+ """
104
+ try:
105
+ from rich.prompt import InvalidResponse, Prompt
106
+ except ImportError:
107
+ print('Rich is required here')
108
+ raise
109
+
110
+ class ChoiceWithIntPrompt(Prompt):
111
+ """
112
+ Assigns an integer to each choice.
113
+ """
114
+
115
+ def make_prompt(self, default: Any) -> Any:
116
+ prompt = self.prompt.copy()
117
+ prompt.end = ''
118
+
119
+ if self.show_choices and self.choices:
120
+ prompt.append('\n')
121
+ for idx, choice in enumerate(self.choices, start=1):
122
+ try:
123
+ int(choice)
124
+ except ValueError:
125
+ ...
126
+ else:
127
+ raise AssertionError('choices cannot be integers')
128
+
129
+ prompt.append(f'{idx}. ', style='json.number')
130
+ prompt.append(f'{choice}\n', style='prompt')
131
+ if (
132
+ default != ...
133
+ and self.show_default
134
+ and isinstance(default, (str, self.response_type))
135
+ ):
136
+ prompt.append(' ')
137
+ _default = self.render_default(default)
138
+ prompt.append(_default)
139
+
140
+ prompt.append(self.prompt_suffix)
141
+ return prompt
142
+
143
+ def process_response(self, value: str) -> str:
144
+ value = value.strip()
145
+ assert self.choices is not None
146
+ try:
147
+ return_value = self.response_type(value)
148
+ except ValueError:
149
+ raise InvalidResponse(self.validate_error_message)
150
+
151
+ try:
152
+ idx = int(return_value) - 1
153
+ return_value = self.choices[idx]
154
+ except Exception:
155
+ ...
156
+
157
+ if return_value not in self.choices:
158
+ raise InvalidResponse(self.illegal_choice_message)
159
+
160
+ return return_value
161
+
162
+ return ChoiceWithIntPrompt.ask(msg, choices=choices)
163
+
164
+
165
+ def find_git_root(dpath: str | os.PathLike[str]) -> ub.Path:
166
+ if 0:
167
+ # Old implementation
168
+ cwd = ub.Path(dpath).absolute()
169
+ parts = cwd.parts
170
+ found = None
171
+ for i in reversed(range(0, len(parts) + 1)):
172
+ p = ub.Path(*parts[0:i])
173
+ cand = p / '.git'
174
+ if cand.exists():
175
+ found = p
176
+ break
177
+ if found is None:
178
+ raise Exception('cannot find git root')
179
+ else:
180
+ # New implementation (should be more robust)
181
+ # allow running inside a subdir of a repo
182
+ info = ub.cmd('git rev-parse --show-toplevel', cwd=dpath, verbose=0)
183
+ if info['ret'] != 0:
184
+ raise RuntimeError(f'Not a git repo: {dpath}')
185
+ found = ub.Path(info['out'].strip())
186
+ return found
187
+
188
+
189
+ class _GitURLInfoRequired(TypedDict):
190
+ host: str | None
191
+ port: int | None
192
+ group: str
193
+ repo_name: str
194
+ repo_endpoint: str
195
+ user: str | None
196
+ protocol: str
197
+ url: str
198
+
199
+
200
+ class GitURLInfo(_GitURLInfoRequired, total=False):
201
+ path: str
202
+
203
+
204
+ class GitURL(str):
205
+ """Parse and convert common network Git remote URL forms.
206
+
207
+ Local paths are parsed so callers can inspect or skip them, but they cannot
208
+ be converted into a network URL without an explicit host.
209
+
210
+ Example:
211
+ >>> from git_well._utils import GitURL
212
+ >>> urls = [
213
+ >>> GitURL('https://foo.bar/group/subgroup/repo.git'),
214
+ >>> GitURL('ssh://git@foo.bar:2222/group/repo.git'),
215
+ >>> GitURL('alice@foo.bar:group/repo.git'),
216
+ >>> GitURL('/home/me/repo.git'),
217
+ >>> ]
218
+ >>> assert urls[0].info['group'] == 'group/subgroup'
219
+ >>> assert urls[0].info['repo_name'] == 'repo'
220
+ >>> assert urls[1].to_ssh() == urls[1]
221
+ >>> assert urls[2].info['user'] == 'alice'
222
+ >>> assert urls[3].info['protocol'] == 'local'
223
+ """
224
+
225
+ def __init__(self, data: str) -> None:
226
+ self._info: GitURLInfo | None = None
227
+
228
+ @staticmethod
229
+ def _fixup_endpoint(repo_endpoint: str) -> tuple[str, str]:
230
+ if repo_endpoint.endswith('/.git'):
231
+ repo_name = repo_endpoint[: -len('/.git')].rsplit('/', 1)[-1]
232
+ elif repo_endpoint.endswith('.git'):
233
+ repo_name = repo_endpoint[:-4]
234
+ else:
235
+ repo_name = repo_endpoint
236
+ repo_endpoint = repo_name + '.git'
237
+ return repo_name, repo_endpoint
238
+
239
+ @classmethod
240
+ def _split_repo_path(cls, path: str) -> tuple[str, str, str]:
241
+ path = path.strip('/')
242
+ if not path:
243
+ raise ValueError('Git remote URL does not contain a repository path')
244
+ parts = path.split('/')
245
+ if parts[-1] == '.git':
246
+ if len(parts) < 2:
247
+ raise ValueError(f'Invalid explicit-directory Git URL: {path!r}')
248
+ repo_endpoint = parts[-2] + '/.git'
249
+ repo_name = parts[-2]
250
+ group = '/'.join(parts[:-2])
251
+ else:
252
+ repo_name, repo_endpoint = cls._fixup_endpoint(parts[-1])
253
+ group = '/'.join(parts[:-1])
254
+ return group, repo_name, repo_endpoint
255
+
256
+ @property
257
+ def info(self) -> GitURLInfo:
258
+ if self._info is not None:
259
+ return self._info
260
+
261
+ import re
262
+ from urllib.parse import unquote, urlsplit
263
+
264
+ url = str(self)
265
+ info: GitURLInfo
266
+ parsed = urlsplit(url) if '://' in url else None
267
+ if parsed is not None:
268
+ protocol = parsed.scheme.lower()
269
+ if protocol == 'file':
270
+ info = {
271
+ 'host': parsed.hostname,
272
+ 'port': parsed.port,
273
+ 'group': '',
274
+ 'repo_name': Path(unquote(parsed.path)).stem,
275
+ 'repo_endpoint': Path(unquote(parsed.path)).name,
276
+ 'user': parsed.username,
277
+ 'protocol': 'file',
278
+ 'path': unquote(parsed.path),
279
+ 'url': url,
280
+ }
281
+ elif protocol in {'http', 'https', 'ssh', 'git'}:
282
+ group, repo_name, repo_endpoint = self._split_repo_path(
283
+ unquote(parsed.path)
284
+ )
285
+ info = {
286
+ 'host': parsed.hostname,
287
+ 'port': parsed.port,
288
+ 'group': group,
289
+ 'repo_name': repo_name,
290
+ 'repo_endpoint': repo_endpoint,
291
+ 'user': parsed.username,
292
+ 'protocol': protocol,
293
+ 'url': url,
294
+ }
295
+ else:
296
+ raise ValueError(f'Unsupported Git URL protocol: {protocol!r}')
297
+ else:
298
+ scp_match = re.match(
299
+ r'^(?:(?P<user>[^/@:]+)@)?'
300
+ r'(?P<host>[^/:\\]+):(?P<path>.+)$',
301
+ url,
302
+ )
303
+ is_windows_drive = bool(re.match(r'^[A-Za-z]:[\\/]', url))
304
+ if scp_match and not is_windows_drive:
305
+ group, repo_name, repo_endpoint = self._split_repo_path(
306
+ scp_match.group('path')
307
+ )
308
+ user = scp_match.group('user')
309
+ info = {
310
+ 'host': scp_match.group('host'),
311
+ 'port': None,
312
+ 'group': group,
313
+ 'repo_name': repo_name,
314
+ 'repo_endpoint': repo_endpoint,
315
+ 'user': user,
316
+ 'protocol': 'git' if user == 'git' else 'scp',
317
+ 'url': url,
318
+ }
319
+ else:
320
+ local_path = Path(url)
321
+ endpoint = local_path.name
322
+ if endpoint == '.git':
323
+ repo_name = local_path.parent.name
324
+ endpoint = repo_name + '/.git'
325
+ else:
326
+ repo_name, endpoint = self._fixup_endpoint(endpoint)
327
+ info = {
328
+ 'host': None,
329
+ 'port': None,
330
+ 'group': '',
331
+ 'repo_name': repo_name,
332
+ 'repo_endpoint': endpoint,
333
+ 'user': None,
334
+ 'protocol': 'local',
335
+ 'path': url,
336
+ 'url': url,
337
+ }
338
+ self._info = info
339
+ return info
340
+
341
+ def _network_path(self) -> str:
342
+ info = self.info
343
+ if not info.get('host'):
344
+ raise ValueError(f'Cannot convert local Git URL: {self!s}')
345
+ parts = [info['group'], info['repo_endpoint']]
346
+ return '/'.join(part for part in parts if part)
347
+
348
+ def to_protocol(self, protocol: str) -> GitURL:
349
+ if protocol == 'git':
350
+ return self.to_git()
351
+ if protocol in {'ssh', 'scp'}:
352
+ return self.to_ssh()
353
+ if protocol == 'https':
354
+ return self.to_https()
355
+ raise KeyError(protocol)
356
+
357
+ def to_git(self) -> GitURL:
358
+ info = self.info
359
+ path = self._network_path()
360
+ host = info['host']
361
+ if info.get('port') is not None:
362
+ return self.__class__(
363
+ f"ssh://git@{host}:{info['port']}/{path}"
364
+ )
365
+ return self.__class__(f'git@{host}:{path}')
366
+
367
+ def to_ssh(self) -> GitURL:
368
+ info = self.info
369
+ path = self._network_path()
370
+ user = info.get('user')
371
+ user_part = '' if user is None else user + '@'
372
+ port_part = '' if info.get('port') is None else f":{info['port']}"
373
+ return self.__class__(
374
+ f"ssh://{user_part}{info['host']}{port_part}/{path}"
375
+ )
376
+
377
+ def to_https(self) -> GitURL:
378
+ info = self.info
379
+ path = self._network_path()
380
+ return self.__class__(f"https://{info['host']}/{path}")
@@ -1,12 +1,16 @@
1
+ from __future__ import annotations
2
+
1
3
 
2
4
  def make_dummy_git_repo():
3
5
  import ubelt as ub
6
+
4
7
  repo_dpath = ub.Path.appdir('git_well', 'tests', 'dummy-git-repo')
5
8
 
6
9
  # On windows we need to use a tempdir because it doesn't seem to let you
7
10
  # clean up after yourself.
8
11
  if ub.WIN32:
9
12
  import tempfile
13
+
10
14
  repo_dpath = ub.Path(tempfile.mkdtemp()) / 'dummy-git-repo'
11
15
 
12
16
  # try:
@@ -28,46 +32,47 @@ def make_dummy_git_repo():
28
32
  # raise
29
33
 
30
34
  import git
35
+
31
36
  repo = git.Repo.init(repo_dpath, initial_branch='main')
32
37
 
33
38
  repo.git.config('user.email', 'demo.user@zombo.com', local=True)
34
39
  repo.git.config('user.name', 'Demo User', local=True)
35
40
 
36
- fpath = (repo_dpath / 'data1.txt')
41
+ fpath = repo_dpath / 'data1.txt'
37
42
  fpath.write_text('data')
38
43
 
39
44
  repo.git.add(fpath)
40
- repo.git.commit(a=True, m="Add Data1")
45
+ repo.git.commit(a=True, m='Add Data1')
41
46
 
42
47
  for idx in range(5):
43
48
  fpath.write_text(f'data{idx}')
44
- repo.git.commit(a=True, m="wip")
49
+ repo.git.commit(a=True, m='wip')
45
50
 
46
51
  repo.git.checkout(b='branch1')
47
- fpath = (repo_dpath / 'data2.txt')
52
+ fpath = repo_dpath / 'data2.txt'
48
53
  for idx in range(5):
49
54
  fpath.write_text(f'data{idx}')
50
55
  repo.git.add(fpath)
51
- repo.git.commit(a=True, m="wip")
56
+ repo.git.commit(a=True, m='wip')
52
57
 
53
58
  repo.git.checkout('main')
54
59
 
55
60
  repo.git.checkout(b='branch2')
56
- fpath = (repo_dpath / 'data3.txt')
61
+ fpath = repo_dpath / 'data3.txt'
57
62
  for idx in range(5):
58
63
  fpath.write_text(f'data{idx}')
59
64
  repo.git.add(fpath)
60
- repo.git.commit(a=True, m="wip")
65
+ repo.git.commit(a=True, m='wip')
61
66
 
62
67
  repo.git.checkout('main')
63
68
  repo.git.merge('branch1')
64
69
  repo.git.merge('branch2')
65
70
 
66
- fpath = (repo_dpath / 'data3.txt')
71
+ fpath = repo_dpath / 'data3.txt'
67
72
  for idx in range(10):
68
73
  fpath.write_text(f'data{idx}')
69
74
  repo.git.add(fpath)
70
- repo.git.commit(a=True, m="wip")
75
+ repo.git.commit(a=True, m='wip')
71
76
 
72
77
  return repo_dpath
73
78
 
@@ -75,6 +80,7 @@ def make_dummy_git_repo():
75
80
  def make_dummy_git_repo_with_orphans():
76
81
  import ubelt as ub
77
82
  import git
83
+
78
84
  repo_dpath = ub.Path.appdir('git_well', 'tests', 'dummy-git-orphan-repo')
79
85
  repo_dpath.delete().ensuredir()
80
86
 
@@ -84,7 +90,7 @@ def make_dummy_git_repo_with_orphans():
84
90
  repo.git.config('user.name', 'Demo User', local=True)
85
91
 
86
92
  # Write a starting commit
87
- fpath = (repo_dpath / 'data1.txt')
93
+ fpath = repo_dpath / 'data1.txt'
88
94
  fpath.write_text('data-base')
89
95
  repo.git.add(fpath)
90
96
  repo.git.commit(a=True, m='base commit')