git-gx 0.9.2__tar.gz → 0.10.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 (35) hide show
  1. {git_gx-0.9.2 → git_gx-0.10.0}/PKG-INFO +36 -8
  2. {git_gx-0.9.2 → git_gx-0.10.0}/README.md +33 -5
  3. {git_gx-0.9.2 → git_gx-0.10.0}/pyproject.toml +7 -11
  4. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/__init__.py +1 -1
  5. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/cli.py +3 -1
  6. git_gx-0.10.0/src/gx/commands/integrate.py +139 -0
  7. git_gx-0.10.0/src/gx/commands/pull.py +121 -0
  8. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/branch.py +17 -0
  9. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/config.py +36 -0
  10. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/github.py +5 -6
  11. git_gx-0.10.0/src/gx/lib/options.py +36 -0
  12. git_gx-0.10.0/src/gx/lib/sync.py +384 -0
  13. git_gx-0.9.2/src/gx/commands/pull.py +0 -58
  14. git_gx-0.9.2/src/gx/lib/options.py +0 -18
  15. git_gx-0.9.2/src/gx/lib/sync.py +0 -90
  16. {git_gx-0.9.2 → git_gx-0.10.0}/LICENSE +0 -0
  17. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/__init__.py +0 -0
  18. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/clean.py +0 -0
  19. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/done.py +0 -0
  20. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/feat.py +0 -0
  21. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/info.py +0 -0
  22. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/log.py +0 -0
  23. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/push.py +0 -0
  24. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/commands/status.py +0 -0
  25. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/constants.py +0 -0
  26. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/__init__.py +0 -0
  27. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/display.py +0 -0
  28. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/git.py +0 -0
  29. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/info_panels.py +0 -0
  30. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/log_panel.py +0 -0
  31. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/nclutils_logging.py +0 -0
  32. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/stale_analyzer.py +0 -0
  33. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/status_panel.py +0 -0
  34. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/workspace.py +0 -0
  35. {git_gx-0.9.2 → git_gx-0.10.0}/src/gx/lib/worktree.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: git-gx
3
- Version: 0.9.2
3
+ Version: 0.10.0
4
4
  Summary: A CLI that wraps common git commands with sensible defaults, safety guards, and helpful summaries.
5
5
  Author: Nate Landau
6
6
  Author-email: Nate Landau <github@natenate.org>
@@ -27,9 +27,9 @@ License: MIT License
27
27
  SOFTWARE.
28
28
  Classifier: Programming Language :: Python :: 3.13
29
29
  Classifier: Programming Language :: Python :: 3.14
30
- Requires-Dist: nclutils>=3.4.1,<4.0.0
30
+ Requires-Dist: nclutils>=3.4.2,<4.0.0
31
31
  Requires-Dist: rich>=15.0.0,<16.0.0
32
- Requires-Dist: typer>=0.26.7,<1.0.0
32
+ Requires-Dist: typer>=0.26.8,<1.0.0
33
33
  Requires-Python: >=3.13, <3.15
34
34
  Description-Content-Type: text/markdown
35
35
 
@@ -41,7 +41,7 @@ A CLI wrapper around git that adds sensible defaults, safety guards, and summari
41
41
 
42
42
  - Auto-numbered feature branches with optional worktree isolation
43
43
  - Push with dirty-tree warnings and a confirmation prompt before touching the default branch
44
- - Pull with automatic stash/unstash and rebase
44
+ - Pull with automatic stash/unstash and rebase, with guided rebase-or-merge reconciliation on divergence
45
45
  - Batch cleanup of merged, gone, and empty branches
46
46
  - Color-coded commit log across all branches with inline branch and tag badges
47
47
  - Repository dashboard with metadata, branches, GitHub info, and recent commits
@@ -71,7 +71,7 @@ gx done # checkout main, pull, delete feat/1
71
71
 
72
72
  ## Commands
73
73
 
74
- Every command supports `-h` for help. The mutating commands (`feat`, `push`, `pull`, `clean`, `done`) and `log` also support `-v`/`-vv` for verbosity and `-n` for dry-run.
74
+ Every command supports `-h` for help. The mutating commands (`feat`, `push`, `pull`, `integrate`, `clean`, `done`) and `log` also support `-v`/`-vv` for verbosity and `-n` for dry-run.
75
75
 
76
76
  ### `gx info`
77
77
 
@@ -144,10 +144,13 @@ Safety guards:
144
144
 
145
145
  ### `gx pull`
146
146
 
147
- Fetch and rebase the current branch onto its upstream. Handles uncommitted changes automatically.
147
+ Fetch and rebase the current branch onto its upstream. Handles uncommitted changes automatically. If the branch has diverged from its upstream, gx guides you through reconciling it instead of failing the rebase.
148
148
 
149
149
  ```sh
150
150
  gx pull # pull and rebase
151
+ gx pull --rebase # reconcile a diverged branch by rebasing
152
+ gx pull --merge # reconcile a diverged branch with a merge commit
153
+ gx pull --ff-only # only fast-forward; fail if the branch has diverged
151
154
  gx pull -v # pull with debug output
152
155
  ```
153
156
 
@@ -155,12 +158,33 @@ The full sequence:
155
158
 
156
159
  1. Stash uncommitted changes (including untracked files)
157
160
  2. Fetch from the remote
158
- 3. Rebase onto the upstream branch
161
+ 3. Rebase onto the upstream branch, or reconcile a divergence
159
162
  4. Update submodules if `.gitmodules` is present
160
163
  5. Restore the stash
161
164
  6. Print a summary of new commits
162
165
 
163
- If a rebase conflict occurs, gx restores your stash and prints resolution steps.
166
+ If the branch has only diverged (both ahead of and behind its upstream), gx shows the commits unique to each side and asks whether to reconcile by rebase or merge, unless `--rebase`, `--merge`, `--ff-only`, or the `integrate.strategy` config setting already decides it. If a rebase or merge conflict occurs, gx leaves the operation in progress and prints resolution steps; any changes it stashed are left in the stash for you to restore with `git stash pop` after you resolve the conflict.
167
+
168
+ ### `gx integrate` (alias: `gx int`)
169
+
170
+ Reconcile the current branch with another ref, choosing between rebase and merge when they've diverged. Unlike `gx pull`, it doesn't touch your upstream or stash: it refuses to run on a dirty working tree instead.
171
+
172
+ ```sh
173
+ gx integrate # reconcile with the upstream
174
+ gx integrate main # bring main into the current branch
175
+ gx integrate main --merge # merge main in without prompting
176
+ gx int main -n # preview integrating main
177
+ ```
178
+
179
+ The current branch always receives the changes. With no argument, gx integrates against the upstream tracking branch; given a ref (a local branch like `main` or a remote-qualified ref like `origin/main`), gx fetches it if it names a known remote and brings its commits into the current branch.
180
+
181
+ Depending on how the branch relates to the target:
182
+
183
+ - **Already up to date**: nothing to do.
184
+ - **Fast-forward** (only behind): gx fast-forwards automatically.
185
+ - **Diverged** (both ahead and behind): gx previews the commits unique to each side, then reconciles by rebase or merge. Pass `--rebase`, `--merge`, or `--ff-only` to skip the prompt, or set `integrate.strategy` in your config. `--ff-only` fails cleanly if the branch has actually diverged.
186
+
187
+ `gx integrate` refuses to run against a dirty working tree. Commit or stash your changes first.
164
188
 
165
189
  ### `gx clean`
166
190
 
@@ -220,6 +244,9 @@ name = "origin" # default remote name
220
244
 
221
245
  [display]
222
246
  nerd_font = true # use Nerd Font icons in the log (see Icons below)
247
+
248
+ [integrate]
249
+ strategy = "ask" # ask, rebase, merge, or ff-only: default strategy for reconciling a diverged branch
223
250
  ```
224
251
 
225
252
  Every key is optional. Only specify the ones you want to change.
@@ -248,6 +275,7 @@ Override any setting per-invocation with environment variables. These take prior
248
275
  | `GX_PROTECTED_BRANCHES` | `GX_PROTECTED_BRANCHES=main,production gx clean` |
249
276
  | `GX_REMOTE_NAME` | `GX_REMOTE_NAME=upstream gx push` |
250
277
  | `GX_NERD_FONT` | `GX_NERD_FONT=false gx log` |
278
+ | `GX_INTEGRATE_STRATEGY` | `GX_INTEGRATE_STRATEGY=rebase gx pull` |
251
279
 
252
280
  ## License
253
281
 
@@ -6,7 +6,7 @@ A CLI wrapper around git that adds sensible defaults, safety guards, and summari
6
6
 
7
7
  - Auto-numbered feature branches with optional worktree isolation
8
8
  - Push with dirty-tree warnings and a confirmation prompt before touching the default branch
9
- - Pull with automatic stash/unstash and rebase
9
+ - Pull with automatic stash/unstash and rebase, with guided rebase-or-merge reconciliation on divergence
10
10
  - Batch cleanup of merged, gone, and empty branches
11
11
  - Color-coded commit log across all branches with inline branch and tag badges
12
12
  - Repository dashboard with metadata, branches, GitHub info, and recent commits
@@ -36,7 +36,7 @@ gx done # checkout main, pull, delete feat/1
36
36
 
37
37
  ## Commands
38
38
 
39
- Every command supports `-h` for help. The mutating commands (`feat`, `push`, `pull`, `clean`, `done`) and `log` also support `-v`/`-vv` for verbosity and `-n` for dry-run.
39
+ Every command supports `-h` for help. The mutating commands (`feat`, `push`, `pull`, `integrate`, `clean`, `done`) and `log` also support `-v`/`-vv` for verbosity and `-n` for dry-run.
40
40
 
41
41
  ### `gx info`
42
42
 
@@ -109,10 +109,13 @@ Safety guards:
109
109
 
110
110
  ### `gx pull`
111
111
 
112
- Fetch and rebase the current branch onto its upstream. Handles uncommitted changes automatically.
112
+ Fetch and rebase the current branch onto its upstream. Handles uncommitted changes automatically. If the branch has diverged from its upstream, gx guides you through reconciling it instead of failing the rebase.
113
113
 
114
114
  ```sh
115
115
  gx pull # pull and rebase
116
+ gx pull --rebase # reconcile a diverged branch by rebasing
117
+ gx pull --merge # reconcile a diverged branch with a merge commit
118
+ gx pull --ff-only # only fast-forward; fail if the branch has diverged
116
119
  gx pull -v # pull with debug output
117
120
  ```
118
121
 
@@ -120,12 +123,33 @@ The full sequence:
120
123
 
121
124
  1. Stash uncommitted changes (including untracked files)
122
125
  2. Fetch from the remote
123
- 3. Rebase onto the upstream branch
126
+ 3. Rebase onto the upstream branch, or reconcile a divergence
124
127
  4. Update submodules if `.gitmodules` is present
125
128
  5. Restore the stash
126
129
  6. Print a summary of new commits
127
130
 
128
- If a rebase conflict occurs, gx restores your stash and prints resolution steps.
131
+ If the branch has only diverged (both ahead of and behind its upstream), gx shows the commits unique to each side and asks whether to reconcile by rebase or merge, unless `--rebase`, `--merge`, `--ff-only`, or the `integrate.strategy` config setting already decides it. If a rebase or merge conflict occurs, gx leaves the operation in progress and prints resolution steps; any changes it stashed are left in the stash for you to restore with `git stash pop` after you resolve the conflict.
132
+
133
+ ### `gx integrate` (alias: `gx int`)
134
+
135
+ Reconcile the current branch with another ref, choosing between rebase and merge when they've diverged. Unlike `gx pull`, it doesn't touch your upstream or stash: it refuses to run on a dirty working tree instead.
136
+
137
+ ```sh
138
+ gx integrate # reconcile with the upstream
139
+ gx integrate main # bring main into the current branch
140
+ gx integrate main --merge # merge main in without prompting
141
+ gx int main -n # preview integrating main
142
+ ```
143
+
144
+ The current branch always receives the changes. With no argument, gx integrates against the upstream tracking branch; given a ref (a local branch like `main` or a remote-qualified ref like `origin/main`), gx fetches it if it names a known remote and brings its commits into the current branch.
145
+
146
+ Depending on how the branch relates to the target:
147
+
148
+ - **Already up to date**: nothing to do.
149
+ - **Fast-forward** (only behind): gx fast-forwards automatically.
150
+ - **Diverged** (both ahead and behind): gx previews the commits unique to each side, then reconciles by rebase or merge. Pass `--rebase`, `--merge`, or `--ff-only` to skip the prompt, or set `integrate.strategy` in your config. `--ff-only` fails cleanly if the branch has actually diverged.
151
+
152
+ `gx integrate` refuses to run against a dirty working tree. Commit or stash your changes first.
129
153
 
130
154
  ### `gx clean`
131
155
 
@@ -185,6 +209,9 @@ name = "origin" # default remote name
185
209
 
186
210
  [display]
187
211
  nerd_font = true # use Nerd Font icons in the log (see Icons below)
212
+
213
+ [integrate]
214
+ strategy = "ask" # ask, rebase, merge, or ff-only: default strategy for reconciling a diverged branch
188
215
  ```
189
216
 
190
217
  Every key is optional. Only specify the ones you want to change.
@@ -213,6 +240,7 @@ Override any setting per-invocation with environment variables. These take prior
213
240
  | `GX_PROTECTED_BRANCHES` | `GX_PROTECTED_BRANCHES=main,production gx clean` |
214
241
  | `GX_REMOTE_NAME` | `GX_REMOTE_NAME=upstream gx push` |
215
242
  | `GX_NERD_FONT` | `GX_NERD_FONT=false gx log` |
243
+ | `GX_INTEGRATE_STRATEGY` | `GX_INTEGRATE_STRATEGY=rebase gx pull` |
216
244
 
217
245
  ## License
218
246
 
@@ -4,17 +4,13 @@
4
4
  "Programming Language :: Python :: 3.13",
5
5
  "Programming Language :: Python :: 3.14",
6
6
  ]
7
- dependencies = [
8
- "nclutils>=3.4.1,<4.0.0",
9
- "rich>=15.0.0, <16.0.0",
10
- "typer>=0.26.7,<1.0.0",
11
- ]
7
+ dependencies = ["nclutils>=3.4.2,<4.0.0", "rich>=15.0.0, <16.0.0", "typer>=0.26.8,<1.0.0"]
12
8
  description = "A CLI that wraps common git commands with sensible defaults, safety guards, and helpful summaries."
13
9
  license = { file = "LICENSE" }
14
10
  name = "git-gx"
15
11
  readme = "README.md"
16
12
  requires-python = ">=3.13,<3.15"
17
- version = "0.9.2"
13
+ version = "0.10.0"
18
14
 
19
15
  [project.scripts]
20
16
  gx = "gx.cli:main"
@@ -29,9 +25,9 @@
29
25
  [dependency-groups]
30
26
  dev = [
31
27
  "commitizen>=4.16.4",
32
- "coverage>=7.14.2",
28
+ "coverage>=7.15.0",
33
29
  "duty>=1.9.0",
34
- "prek>=0.4.5",
30
+ "prek>=0.4.8",
35
31
  "pytest-clarity>=1.0.1",
36
32
  "pytest-cov>=7.1.0",
37
33
  "pytest-devtools>=1.2.0",
@@ -40,10 +36,10 @@
40
36
  "pytest-sugar>=1.1.1",
41
37
  "pytest-xdist>=3.8.0",
42
38
  "pytest>=9.1.1",
43
- "ruff>=0.15.18",
39
+ "ruff>=0.15.20",
44
40
  "shellcheck-py>=0.11.0.1",
45
- "ty>=0.0.51",
46
- "typos>=1.47.2",
41
+ "ty>=0.0.57",
42
+ "typos>=1.48.0",
47
43
  "yamllint>=1.38.0",
48
44
  ]
49
45
 
@@ -1,3 +1,3 @@
1
1
  """GX - A CLI tool for managing Git repositories."""
2
2
 
3
- __version__ = "0.9.2"
3
+ __version__ = "0.10.0"
@@ -8,7 +8,7 @@ from nclutils.git import is_git_repo
8
8
  from typer import rich_utils
9
9
 
10
10
  from gx import __version__
11
- from gx.commands import clean, done, feat, info, log, pull, push, status
11
+ from gx.commands import clean, done, feat, info, integrate, log, pull, push, status
12
12
  from gx.lib.git import check_git_installed
13
13
  from gx.lib.nclutils_logging import configure_nclutils_logging
14
14
  from gx.lib.options import VERBOSE_OPTION
@@ -26,6 +26,8 @@ app.add_typer(done.app, name="done")
26
26
  app.add_typer(status.app, name="status")
27
27
  app.add_typer(log.app, name="log")
28
28
  app.add_typer(info.app, name="info")
29
+ app.add_typer(integrate.app, name="integrate")
30
+ app.add_typer(integrate.app, name="int")
29
31
 
30
32
 
31
33
  def _version_callback(value: bool) -> None: # noqa: FBT001
@@ -0,0 +1,139 @@
1
+ """Integrate subcommand for gx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+ from nclutils import pp
7
+ from nclutils.git import ahead_behind, current_branch, is_dirty, tracking_branch
8
+
9
+ from gx.lib.branch import is_remote_ref
10
+ from gx.lib.git import check_git_repo, git, raise_on_error, set_dry_run
11
+ from gx.lib.options import (
12
+ DRY_RUN_OPTION,
13
+ FF_ONLY_OPTION,
14
+ MERGE_OPTION,
15
+ REBASE_OPTION,
16
+ VERBOSE_OPTION,
17
+ )
18
+ from gx.lib.sync import (
19
+ SyncState,
20
+ announce_push_hint,
21
+ classify_sync_state,
22
+ ensure_one_strategy_flag,
23
+ fast_forward,
24
+ reconcile_divergence,
25
+ warn_if_stale_base,
26
+ )
27
+
28
+ CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
29
+
30
+ app = typer.Typer(rich_markup_mode="rich", context_settings=CONTEXT_SETTINGS)
31
+
32
+
33
+ REF_ARGUMENT: str | None = typer.Argument(
34
+ None,
35
+ help="Ref to integrate into the current branch. Defaults to the upstream.",
36
+ )
37
+
38
+
39
+ def _resolve_target(ref: str | None) -> tuple[str, str | None]:
40
+ """Resolve the target ref and the remote to fetch, if any.
41
+
42
+ Args:
43
+ ref: The positional ref argument, or None to use the upstream.
44
+
45
+ Returns:
46
+ A (target_ref, fetch_remote) tuple. fetch_remote is None when the
47
+ target is a local branch that needs no fetch.
48
+
49
+ Raises:
50
+ typer.Exit: When no ref is given and no upstream is configured.
51
+ """
52
+ if ref is not None:
53
+ fetch_remote = ref.split("/", 1)[0] if is_remote_ref(ref) else None
54
+ return ref, fetch_remote
55
+
56
+ tracking = tracking_branch()
57
+ if tracking is None:
58
+ pp.info("Nothing to integrate: no upstream is configured.")
59
+ raise typer.Exit(0)
60
+ remote, remote_branch = tracking
61
+ return f"{remote}/{remote_branch}", remote
62
+
63
+
64
+ @app.callback(invoke_without_command=True)
65
+ def integrate(
66
+ ctx: typer.Context, # noqa: ARG001
67
+ ref: str | None = REF_ARGUMENT,
68
+ verbose: int = VERBOSE_OPTION,
69
+ dry_run: bool = DRY_RUN_OPTION, # noqa: FBT001
70
+ rebase: bool = REBASE_OPTION, # noqa: FBT001
71
+ merge: bool = MERGE_OPTION, # noqa: FBT001
72
+ ff_only: bool = FF_ONLY_OPTION, # noqa: FBT001
73
+ ) -> None:
74
+ """Reconcile the current branch with another ref, guiding rebase vs merge.
75
+
76
+ The current branch always receives. With no argument, reconciles against the
77
+ upstream; given a ref (e.g. main or origin/main), brings that ref's commits
78
+ into the current branch. On divergence you choose a rebase (linear history)
79
+ or a merge commit, unless a strategy flag or the integrate.strategy config
80
+ setting decides for you.
81
+
82
+ [bold]Examples:[/bold]
83
+
84
+ gx integrate Reconcile with the upstream
85
+ gx integrate main Bring main into the current branch
86
+ gx integrate main --merge Merge main in without prompting
87
+ gx int main -n Preview integrating main
88
+ """
89
+ if verbose:
90
+ pp.configure(verbosity=verbose)
91
+ if dry_run:
92
+ set_dry_run(enabled=True)
93
+ check_git_repo()
94
+
95
+ ensure_one_strategy_flag(rebase=rebase, merge=merge, ff_only=ff_only)
96
+
97
+ branch = current_branch()
98
+ if branch is None:
99
+ pp.error("Cannot integrate in detached HEAD state.")
100
+ raise typer.Exit(1)
101
+
102
+ if is_dirty():
103
+ pp.error("Working tree has uncommitted changes. Commit or stash before integrating.")
104
+ raise typer.Exit(1)
105
+
106
+ target_ref, fetch_remote = _resolve_target(ref)
107
+
108
+ if fetch_remote is not None:
109
+ with pp.step(f"Fetch from {fetch_remote}"):
110
+ raise_on_error(git("fetch", fetch_remote))
111
+
112
+ if not git("rev-parse", "--verify", "--quiet", target_ref).ok:
113
+ pp.error(f"Cannot resolve ref '{target_ref}'.")
114
+ raise typer.Exit(1)
115
+
116
+ warn_if_stale_base(target_ref)
117
+
118
+ ahead, behind = ahead_behind(branch, target_ref)
119
+ state = classify_sync_state(ahead, behind)
120
+
121
+ if state is SyncState.UP_TO_DATE:
122
+ if ahead > 0:
123
+ pp.success(f"Already up to date with {target_ref}; {ahead} commit(s) ahead.")
124
+ announce_push_hint()
125
+ else:
126
+ pp.success(f"Already up to date with {target_ref}.")
127
+ return
128
+
129
+ if state is SyncState.FAST_FORWARD:
130
+ fast_forward(target_ref)
131
+ pp.success(f"Fast-forwarded to {target_ref}.")
132
+ announce_push_hint()
133
+ return
134
+
135
+ reconcile_divergence(
136
+ branch, target_ref, ahead, behind, rebase=rebase, merge=merge, ff_only=ff_only
137
+ )
138
+ pp.success(f"Integrated {target_ref} into {branch}.")
139
+ announce_push_hint()
@@ -0,0 +1,121 @@
1
+ """Pull subcommand for gx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+ from nclutils import pp
7
+ from nclutils.git import ahead_behind, is_rebase_in_progress
8
+
9
+ from gx.lib.git import check_git_repo, git, set_dry_run
10
+ from gx.lib.options import (
11
+ DRY_RUN_OPTION,
12
+ FF_ONLY_OPTION,
13
+ MERGE_OPTION,
14
+ REBASE_OPTION,
15
+ VERBOSE_OPTION,
16
+ )
17
+ from gx.lib.sync import (
18
+ SyncState,
19
+ announce_push_hint,
20
+ classify_sync_state,
21
+ ensure_one_strategy_flag,
22
+ print_pull_summary,
23
+ reconcile_divergence,
24
+ report_conflict,
25
+ validate_branch,
26
+ )
27
+ from gx.lib.workspace import rollback, stash_if_dirty, unstash, update_submodules
28
+
29
+ CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
30
+
31
+ app = typer.Typer(rich_markup_mode="rich", context_settings=CONTEXT_SETTINGS)
32
+
33
+
34
+ @app.callback(invoke_without_command=True)
35
+ def pull(
36
+ ctx: typer.Context, # noqa: ARG001
37
+ verbose: int = VERBOSE_OPTION,
38
+ dry_run: bool = DRY_RUN_OPTION, # noqa: FBT001
39
+ rebase: bool = REBASE_OPTION, # noqa: FBT001
40
+ merge: bool = MERGE_OPTION, # noqa: FBT001
41
+ ff_only: bool = FF_ONLY_OPTION, # noqa: FBT001
42
+ ) -> None:
43
+ """Pull latest changes from the remote tracking branch.
44
+
45
+ Fetches and rebases the current branch onto its upstream. Automatically handles uncommitted changes by stashing before the pull and restoring after. If the branch has diverged from its upstream, gx asks how to reconcile (rebase or merge), unless a strategy flag (--rebase/--merge/--ff-only) or the integrate.strategy config setting decides for you.
46
+
47
+ [bold]What happens:[/bold]
48
+
49
+ 1. Stashes any uncommitted changes (including untracked files)
50
+ 2. Fetches from the remote
51
+ 3. Rebases onto the upstream branch, or reconciles a divergence
52
+ 4. Updates submodules if .gitmodules is present
53
+ 5. Restores stashed changes
54
+ 6. Prints a summary of new commits
55
+
56
+ If a rebase or merge conflict occurs, gx leaves the operation in progress and prints resolution steps. Any changes it stashed are left in the stash, so restore them with 'git stash pop' after you resolve the conflict.
57
+
58
+ [bold]Examples:[/bold]
59
+
60
+ gx pull Pull and rebase current branch
61
+ gx pull --rebase Reconcile a diverged branch by rebasing
62
+ gx pull --merge Reconcile a diverged branch with a merge commit
63
+ gx pull -n Preview what would happen
64
+ gx pull -v Pull with debug output
65
+ """
66
+ if verbose:
67
+ pp.configure(verbosity=verbose)
68
+ if dry_run:
69
+ set_dry_run(enabled=True)
70
+ check_git_repo()
71
+
72
+ ensure_one_strategy_flag(rebase=rebase, merge=merge, ff_only=ff_only)
73
+
74
+ branch, remote, remote_branch = validate_branch()
75
+ upstream_ref = f"{remote}/{remote_branch}"
76
+ stashed = stash_if_dirty()
77
+ head_before = git("rev-parse", "HEAD")
78
+
79
+ with pp.step(f"Fetch from {remote}"):
80
+ result = git("fetch", remote)
81
+ if not result.ok:
82
+ pp.error(f"Failed to fetch from {remote}: {result.stderr}")
83
+ rollback(stashed=stashed)
84
+
85
+ ahead, behind = ahead_behind(branch, upstream_ref)
86
+ state = classify_sync_state(ahead, behind)
87
+
88
+ if state is SyncState.DIVERGED:
89
+ reconcile_divergence(
90
+ branch,
91
+ upstream_ref,
92
+ ahead,
93
+ behind,
94
+ rebase=rebase,
95
+ merge=merge,
96
+ ff_only=ff_only,
97
+ stashed=stashed,
98
+ )
99
+ else:
100
+ with pp.step(f"Pull with rebase from {upstream_ref}"):
101
+ result = git("pull", "--rebase", remote, remote_branch)
102
+ if not result.ok:
103
+ if is_rebase_in_progress():
104
+ report_conflict("rebase")
105
+ if stashed:
106
+ pp.warning(
107
+ "Your local changes remain stashed. "
108
+ "Run 'git stash pop' after resolving the conflict."
109
+ )
110
+ rollback(stashed=False)
111
+ else:
112
+ pp.error(f"Failed to pull from {upstream_ref}")
113
+ rollback(stashed=stashed)
114
+
115
+ update_submodules(stashed=stashed)
116
+ unstash(stashed=stashed)
117
+
118
+ if state is SyncState.DIVERGED:
119
+ announce_push_hint()
120
+
121
+ print_pull_summary(head_before.stdout, remote, remote_branch)
@@ -66,6 +66,23 @@ def default_branch() -> str:
66
66
  raise typer.Exit(1)
67
67
 
68
68
 
69
+ def is_remote_ref(ref: str) -> bool:
70
+ """Report whether a ref is qualified by a configured remote (e.g. origin/main).
71
+
72
+ Distinguishes a remote-tracking ref from a local branch that merely contains
73
+ a slash, like ``feat/123``. Callers use it to decide whether a ref needs a
74
+ fetch and whether a staleness check applies.
75
+
76
+ Args:
77
+ ref: The ref name to test.
78
+ """
79
+ if "/" not in ref:
80
+ return False
81
+ prefix = ref.split("/", 1)[0]
82
+ result = git("remote")
83
+ return result.ok and prefix in result.stdout.splitlines()
84
+
85
+
69
86
  def has_commits() -> bool:
70
87
  """Report whether the repository has at least one commit.
71
88
 
@@ -11,6 +11,8 @@ from nclutils import pp
11
11
 
12
12
  from gx.constants import CONFIG_DIR
13
13
 
14
+ VALID_STRATEGIES: frozenset[str] = frozenset({"ask", "rebase", "merge", "ff-only"})
15
+
14
16
 
15
17
  @dataclass(frozen=True)
16
18
  class GxConfig:
@@ -27,6 +29,7 @@ class GxConfig:
27
29
  )
28
30
  remote_name: str = "origin"
29
31
  nerd_font: bool = True
32
+ integrate_strategy: str = "ask"
30
33
 
31
34
 
32
35
  def _load_toml() -> dict:
@@ -87,6 +90,26 @@ def _extract_bool(table: dict, key: str, config_path: str) -> bool | None:
87
90
  return None
88
91
 
89
92
 
93
+ def _valid_strategy_or_warn(value: str, source: str, action: str) -> str | None:
94
+ """Return value if it names a valid reconcile strategy, else warn and drop it.
95
+
96
+ Shared by the TOML and env-var readers so the two paths can never accept or
97
+ reject different values.
98
+
99
+ Args:
100
+ value: The raw strategy string.
101
+ source: Where the value came from, for the warning (e.g. "GX_INTEGRATE_STRATEGY").
102
+ action: The verb describing the fallback (e.g. "Skipping", "Ignoring").
103
+
104
+ Returns:
105
+ The value if valid, otherwise None.
106
+ """
107
+ if value in VALID_STRATEGIES:
108
+ return value
109
+ pp.warning(f"{source} must be one of {sorted(VALID_STRATEGIES)}. {action}.")
110
+ return None
111
+
112
+
90
113
  def _extract_toml_values(data: dict) -> dict:
91
114
  """Extract and validate known config values from parsed TOML data.
92
115
 
@@ -126,6 +149,14 @@ def _extract_toml_values(data: dict) -> dict:
126
149
  ):
127
150
  values["nerd_font"] = nerd_font
128
151
 
152
+ integrate = data.get("integrate", {})
153
+ if isinstance(integrate, dict) and (
154
+ strategy := _extract_str(integrate, "strategy", "integrate.strategy")
155
+ ):
156
+ valid = _valid_strategy_or_warn(strategy, "Config: integrate.strategy", "Skipping")
157
+ if valid is not None:
158
+ values["integrate_strategy"] = valid
159
+
129
160
  return values
130
161
 
131
162
 
@@ -154,6 +185,11 @@ def _load_env_overrides() -> dict:
154
185
  if (val := os.environ.get("GX_NERD_FONT")) is not None:
155
186
  overrides["nerd_font"] = val.strip().lower() not in {"0", "false", "no", "off", ""}
156
187
 
188
+ if val := os.environ.get("GX_INTEGRATE_STRATEGY"):
189
+ valid = _valid_strategy_or_warn(val, "GX_INTEGRATE_STRATEGY", "Ignoring")
190
+ if valid is not None:
191
+ overrides["integrate_strategy"] = val
192
+
157
193
  return overrides
158
194
 
159
195
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Literal
5
+ from typing import Literal, cast
6
6
 
7
7
  from nclutils.git import primary_remote
8
8
  from nclutils.sh import run_command, which
@@ -55,8 +55,7 @@ def pr_state(branch: str) -> PrState | None:
55
55
  if not result.ok:
56
56
  return None
57
57
 
58
- match result.stdout:
59
- case "MERGED" | "OPEN" | "CLOSED" as state:
60
- return state
61
- case _:
62
- return None
58
+ if result.stdout in ("MERGED", "OPEN", "CLOSED"):
59
+ return cast("PrState", result.stdout)
60
+
61
+ return None
@@ -0,0 +1,36 @@
1
+ """Shared Typer options and arguments for gx commands."""
2
+
3
+ import typer
4
+
5
+ VERBOSE_OPTION: int = typer.Option(
6
+ 0,
7
+ "--verbose",
8
+ "-v",
9
+ count=True,
10
+ help="Increase verbosity (-v debug, -vv trace).",
11
+ )
12
+
13
+ DRY_RUN_OPTION: bool = typer.Option(
14
+ False, # noqa: FBT003
15
+ "--dry-run",
16
+ "-n",
17
+ help="Show what would be done without making changes.",
18
+ )
19
+
20
+ REBASE_OPTION: bool = typer.Option(
21
+ False, # noqa: FBT003
22
+ "--rebase",
23
+ help="Reconcile by rebasing (linear history). Skips the prompt.",
24
+ )
25
+
26
+ MERGE_OPTION: bool = typer.Option(
27
+ False, # noqa: FBT003
28
+ "--merge",
29
+ help="Reconcile by creating a merge commit. Skips the prompt.",
30
+ )
31
+
32
+ FF_ONLY_OPTION: bool = typer.Option(
33
+ False, # noqa: FBT003
34
+ "--ff-only",
35
+ help="Only fast-forward; fail if the branch has diverged.",
36
+ )
@@ -0,0 +1,384 @@
1
+ """Pull-the-remote flow helpers.
2
+
3
+ Reusable primitives for fetching, rebasing, and reporting on remote-sync
4
+ operations against the current branch's upstream.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from enum import Enum
11
+
12
+ import typer
13
+ from nclutils import pp
14
+ from nclutils.git import ahead_behind, current_branch, is_rebase_in_progress, tracking_branch
15
+ from rich.prompt import Prompt
16
+
17
+ from gx.lib.branch import is_remote_ref
18
+ from gx.lib.config import config
19
+ from gx.lib.display import commit_text
20
+ from gx.lib.git import git
21
+ from gx.lib.workspace import rollback
22
+
23
+
24
+ class SyncState(Enum):
25
+ """Relationship of the current branch to a target ref."""
26
+
27
+ UP_TO_DATE = "up_to_date" # equal, or only ahead of the target
28
+ FAST_FORWARD = "fast_forward" # behind only, no local-only commits
29
+ DIVERGED = "diverged" # both ahead of and behind the target
30
+
31
+
32
+ class Strategy(Enum):
33
+ """How to reconcile a diverged branch."""
34
+
35
+ REBASE = "rebase"
36
+ MERGE = "merge"
37
+ FF_ONLY = "ff-only"
38
+
39
+
40
+ def classify_sync_state(ahead: int, behind: int) -> SyncState:
41
+ """Classify how the current branch relates to a target from ahead/behind counts.
42
+
43
+ Kept pure (no git calls) so callers can compute the counts once and both
44
+ branch on the state and report the numbers.
45
+
46
+ Args:
47
+ ahead: Number of commits the current branch is ahead of the target.
48
+ behind: Number of commits the current branch is behind the target.
49
+
50
+ Returns:
51
+ SyncState: The relationship between the current branch and target.
52
+ """
53
+ if behind == 0:
54
+ return SyncState.UP_TO_DATE
55
+ if ahead == 0:
56
+ return SyncState.FAST_FORWARD
57
+ return SyncState.DIVERGED
58
+
59
+
60
+ def resolve_strategy(
61
+ *, rebase: bool, merge: bool, ff_only: bool, config_strategy: str
62
+ ) -> Strategy | None:
63
+ """Resolve the reconcile strategy by precedence: explicit flag, then config.
64
+
65
+ Returns None only when nothing selects a strategy (no flag and config is
66
+ "ask"), signaling the caller to prompt interactively.
67
+
68
+ Args:
69
+ rebase: Whether the rebase flag is set.
70
+ merge: Whether the merge flag is set.
71
+ ff_only: Whether the ff-only flag is set.
72
+ config_strategy: The configured default strategy (rebase, merge, ff-only, or ask).
73
+
74
+ Returns:
75
+ Strategy | None: The selected strategy, or None to prompt the user.
76
+ """
77
+ if rebase:
78
+ return Strategy.REBASE
79
+ if merge:
80
+ return Strategy.MERGE
81
+ if ff_only:
82
+ return Strategy.FF_ONLY
83
+ if config_strategy != "ask":
84
+ return Strategy(config_strategy)
85
+ return None
86
+
87
+
88
+ def is_merge_in_progress() -> bool:
89
+ """Return True if a merge is mid-flight (MERGE_HEAD exists)."""
90
+ return git("rev-parse", "-q", "--verify", "MERGE_HEAD").ok
91
+
92
+
93
+ def preview_divergence(current: str, target_ref: str, ahead: int, behind: int) -> None:
94
+ """Show the commits unique to each side so the user can choose informed.
95
+
96
+ Args:
97
+ current: The current branch name.
98
+ target_ref: The ref being integrated in.
99
+ ahead: Commits on current not on target_ref.
100
+ behind: Commits on target_ref not on current.
101
+ """
102
+ pp.info(f"'{current}' and '{target_ref}' have diverged: {ahead} ahead, {behind} behind.")
103
+
104
+ yours = git("log", "--oneline", f"{target_ref}..HEAD")
105
+ if yours.ok and yours.stdout:
106
+ pp.info("Your commits:", details=[commit_text(c) for c in yours.stdout.splitlines()])
107
+
108
+ theirs = git("log", "--oneline", f"HEAD..{target_ref}")
109
+ if theirs.ok and theirs.stdout:
110
+ pp.info(
111
+ f"Commits on {target_ref}:",
112
+ details=[commit_text(c) for c in theirs.stdout.splitlines()],
113
+ )
114
+
115
+
116
+ def report_conflict(operation: str) -> None:
117
+ """Print numbered steps to resolve an in-progress rebase or merge conflict.
118
+
119
+ Args:
120
+ operation: Either "rebase" or "merge".
121
+ """
122
+ pp.error(
123
+ f"{operation.capitalize()} conflict detected",
124
+ details=[
125
+ "1. Fix the conflicts in the affected files",
126
+ "2. Stage the resolved files with 'git add'",
127
+ f"3. Continue with 'git {operation} --continue'",
128
+ f"Or abort with 'git {operation} --abort'",
129
+ ],
130
+ )
131
+
132
+
133
+ def fast_forward(target_ref: str, *, stashed: bool = False) -> None:
134
+ """Fast-forward the current branch to target_ref.
135
+
136
+ Args:
137
+ target_ref: The ref to fast-forward to.
138
+ stashed: Whether local changes were stashed, used for rollback.
139
+ """
140
+ with pp.step(f"Fast-forward to {target_ref}"):
141
+ result = git("merge", "--ff-only", target_ref)
142
+ if not result.ok:
143
+ pp.error(f"Failed to fast-forward to {target_ref}: {result.stderr}")
144
+ rollback(stashed=stashed)
145
+
146
+
147
+ def execute_reconcile(strategy: Strategy, target_ref: str, *, stashed: bool = False) -> None:
148
+ """Run a rebase or merge, reporting conflicts and rolling back if needed.
149
+
150
+ On conflict, the operation is left in progress so the user can resolve
151
+ it. A stash is never popped mid-conflict (git would refuse); instead the
152
+ user is warned the stash is still there so they can pop it themselves
153
+ once the conflict is resolved.
154
+
155
+ Args:
156
+ strategy: Strategy.REBASE or Strategy.MERGE.
157
+ target_ref: The ref to integrate in.
158
+ stashed: Whether local changes were stashed, used for rollback.
159
+ """
160
+ if strategy is Strategy.REBASE:
161
+ operation, args = "rebase", ("rebase", target_ref)
162
+ else:
163
+ operation, args = "merge", ("merge", "--no-edit", target_ref)
164
+
165
+ with pp.step(f"{operation.capitalize()} onto {target_ref}"):
166
+ result = git(*args)
167
+ if not result.ok:
168
+ if is_rebase_in_progress() or is_merge_in_progress():
169
+ report_conflict(operation)
170
+ if stashed:
171
+ pp.warning(
172
+ "Your local changes remain stashed. "
173
+ "Run 'git stash pop' after resolving the conflict."
174
+ )
175
+ rollback(stashed=False)
176
+ else:
177
+ pp.error(f"Failed to {operation} onto {target_ref}: {result.stderr}")
178
+ rollback(stashed=stashed)
179
+
180
+
181
+ def ensure_one_strategy_flag(*, rebase: bool, merge: bool, ff_only: bool) -> None:
182
+ """Exit with an error if more than one strategy flag was supplied.
183
+
184
+ Raises:
185
+ typer.Exit: If two or more of the strategy flags are set.
186
+ """
187
+ if sum((rebase, merge, ff_only)) > 1:
188
+ pp.error("Choose at most one of --rebase, --merge, --ff-only.")
189
+ raise typer.Exit(1)
190
+
191
+
192
+ def needs_force_push(upstream_ref: str) -> bool:
193
+ """Return True if a normal push would be rejected (upstream not an ancestor).
194
+
195
+ Args:
196
+ upstream_ref: The upstream tracking ref, e.g. "origin/feature".
197
+ """
198
+ return not git("merge-base", "--is-ancestor", upstream_ref, "HEAD").ok
199
+
200
+
201
+ def warn_if_stale_base(target_ref: str) -> None:
202
+ """Warn when integrating a local branch that trails its own upstream.
203
+
204
+ Skips remote refs (which are freshly fetched) and untracked local branches.
205
+
206
+ Args:
207
+ target_ref: The ref being integrated in.
208
+ """
209
+ if is_remote_ref(target_ref): # a remote ref like origin/main is already fresh
210
+ return
211
+ tracking = tracking_branch(target_ref)
212
+ if tracking is None:
213
+ return
214
+ upstream_ref = f"{tracking[0]}/{tracking[1]}"
215
+ _, behind = ahead_behind(target_ref, upstream_ref)
216
+ if behind > 0:
217
+ pp.warning(
218
+ f"'{target_ref}' is {behind} commit(s) behind {upstream_ref}; "
219
+ "consider updating it first."
220
+ )
221
+
222
+
223
+ def announce_push_hint() -> None:
224
+ """Hint the user to push if the branch now leads its upstream."""
225
+ branch = current_branch()
226
+ if branch is None:
227
+ return
228
+ tracking = tracking_branch()
229
+ if tracking is None:
230
+ return
231
+ upstream_ref = f"{tracking[0]}/{tracking[1]}"
232
+ ahead, _ = ahead_behind(branch, upstream_ref)
233
+ if ahead == 0:
234
+ return
235
+ if needs_force_push(upstream_ref):
236
+ pp.warning("Your branch has diverged from its upstream. Push with: gx push -f")
237
+ else:
238
+ pp.info("Your branch is ahead of its upstream. Push with: gx push")
239
+
240
+
241
+ def prompt_strategy(*, stashed: bool = False) -> Strategy:
242
+ """Ask whether to rebase or merge; exit cleanly when not interactive.
243
+
244
+ Args:
245
+ stashed: Whether local changes were stashed, used for rollback.
246
+
247
+ Raises:
248
+ typer.Exit: If stdin is not a TTY, since no choice can be gathered.
249
+ """
250
+ if not sys.stdin.isatty():
251
+ pp.error(
252
+ "Branch has diverged and no strategy was given.",
253
+ details=[
254
+ "Pass --rebase or --merge, or set integrate.strategy in your config.",
255
+ ],
256
+ )
257
+ rollback(stashed=stashed)
258
+ choice = Prompt.ask(
259
+ "Branches have diverged. Reconcile by", choices=["rebase", "merge"], default="rebase"
260
+ )
261
+ return Strategy.REBASE if choice == "rebase" else Strategy.MERGE
262
+
263
+
264
+ def reconcile_divergence( # noqa: PLR0913
265
+ current: str,
266
+ target_ref: str,
267
+ ahead: int,
268
+ behind: int,
269
+ *,
270
+ rebase: bool,
271
+ merge: bool,
272
+ ff_only: bool,
273
+ stashed: bool = False,
274
+ ) -> None:
275
+ """Guide a diverged branch to reconciliation via the resolved strategy.
276
+
277
+ Shows the diverged commits, resolves the strategy (flag, then config, then
278
+ prompt), errors on an impossible ff-only, and executes the rebase or merge.
279
+
280
+ Args:
281
+ current: The current branch name.
282
+ target_ref: The ref to integrate in.
283
+ ahead: Commits on current not on target_ref.
284
+ behind: Commits on target_ref not on current.
285
+ rebase: The --rebase flag.
286
+ merge: The --merge flag.
287
+ ff_only: The --ff-only flag.
288
+ stashed: Whether local changes were stashed, used for rollback.
289
+
290
+ Raises:
291
+ typer.Exit: On an impossible ff-only reconcile.
292
+ """
293
+ preview_divergence(current, target_ref, ahead, behind)
294
+
295
+ strategy = resolve_strategy(
296
+ rebase=rebase, merge=merge, ff_only=ff_only, config_strategy=config.integrate_strategy
297
+ )
298
+ if strategy is None:
299
+ strategy = prompt_strategy(stashed=stashed)
300
+
301
+ if strategy is Strategy.FF_ONLY:
302
+ pp.error(f"Cannot fast-forward: '{current}' has diverged from {target_ref}.")
303
+ rollback(stashed=stashed)
304
+
305
+ execute_reconcile(strategy, target_ref, stashed=stashed)
306
+
307
+
308
+ def validate_branch() -> tuple[str, str, str]:
309
+ """Validate branch state and return (branch, remote, remote_branch).
310
+
311
+ Raises:
312
+ typer.Exit: If the branch is detached or has no upstream configured.
313
+ """
314
+ branch = current_branch()
315
+ if branch is None:
316
+ pp.error("Cannot sync - HEAD is detached.")
317
+ raise typer.Exit(1)
318
+
319
+ tracking = tracking_branch()
320
+ if tracking is None:
321
+ pp.error(f"Branch '{branch}' has no upstream tracking branch configured.")
322
+ raise typer.Exit(1)
323
+
324
+ remote, remote_branch = tracking
325
+ return branch, remote, remote_branch
326
+
327
+
328
+ def fetch_and_rebase(remote: str, remote_branch: str, *, stashed: bool) -> None:
329
+ """Fetch from remote and pull with rebase.
330
+
331
+ Args:
332
+ remote: The remote name to fetch from.
333
+ remote_branch: The remote branch to rebase onto.
334
+ stashed: Whether local changes were stashed, used for rollback.
335
+ """
336
+ with pp.step(f"Fetch from {remote}"):
337
+ result = git("fetch", remote)
338
+ if not result.ok:
339
+ rollback(stashed=stashed)
340
+
341
+ with pp.step(f"Pull with rebase from {remote}/{remote_branch}"):
342
+ result = git("pull", "--rebase", remote, remote_branch)
343
+ if not result.ok:
344
+ if is_rebase_in_progress():
345
+ report_conflict("rebase")
346
+ if stashed:
347
+ pp.warning(
348
+ "Your local changes remain stashed. "
349
+ "Run 'git stash pop' after resolving the conflict."
350
+ )
351
+ rollback(stashed=False)
352
+ else:
353
+ pp.error(f"Failed to pull from {remote}/{remote_branch}")
354
+ rollback(stashed=stashed)
355
+
356
+
357
+ def print_pull_summary(head_before: str, remote: str, remote_branch: str) -> None:
358
+ """Print a summary of the commits that arrived from the remote.
359
+
360
+ Counts commits against the remote-tracking ref rather than HEAD. A
361
+ reconciling rebase rewrites the SHAs of local commits, so a ``head_before..HEAD``
362
+ range would wrongly report the user's own commits as newly pulled; measuring
363
+ against ``remote/branch`` isolates only what actually came from the remote.
364
+
365
+ Args:
366
+ head_before: The commit SHA before the pull.
367
+ remote: The remote name.
368
+ remote_branch: The remote branch name.
369
+ """
370
+ upstream_ref = f"{remote}/{remote_branch}"
371
+ remote_tip = git("rev-parse", upstream_ref)
372
+ if head_before == remote_tip.stdout:
373
+ pp.success("Already up to date")
374
+ return
375
+
376
+ log_result = git("log", "--oneline", f"{head_before}..{upstream_ref}")
377
+ if log_result.ok and log_result.stdout:
378
+ commits = log_result.stdout.splitlines()
379
+ pp.success(
380
+ f"Pull {len(commits)} new commit(s) from {upstream_ref}",
381
+ details=[commit_text(c) for c in commits],
382
+ )
383
+ else:
384
+ pp.success("Pull complete")
@@ -1,58 +0,0 @@
1
- """Pull subcommand for gx."""
2
-
3
- from __future__ import annotations
4
-
5
- import typer
6
- from nclutils import pp
7
-
8
- from gx.lib.git import check_git_repo, git, set_dry_run
9
- from gx.lib.options import DRY_RUN_OPTION, VERBOSE_OPTION
10
- from gx.lib.sync import fetch_and_rebase, print_pull_summary, validate_branch
11
- from gx.lib.workspace import stash_if_dirty, unstash, update_submodules
12
-
13
- CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
14
-
15
- app = typer.Typer(rich_markup_mode="rich", context_settings=CONTEXT_SETTINGS)
16
-
17
-
18
- @app.callback(invoke_without_command=True)
19
- def pull(
20
- ctx: typer.Context, # noqa: ARG001
21
- verbose: int = VERBOSE_OPTION,
22
- dry_run: bool = DRY_RUN_OPTION, # noqa: FBT001
23
- ) -> None:
24
- """Pull latest changes from the remote tracking branch.
25
-
26
- Fetches and rebases the current branch onto its upstream. Automatically handles uncommitted changes by stashing before the pull and restoring after.
27
-
28
- [bold]What happens:[/bold]
29
-
30
- 1. Stashes any uncommitted changes (including untracked files)
31
- 2. Fetches from the remote
32
- 3. Rebases onto the upstream branch
33
- 4. Updates submodules if .gitmodules is present
34
- 5. Restores stashed changes
35
- 6. Prints a summary of new commits
36
-
37
- If a rebase conflict occurs, gx restores your stash and provides instructions for resolving the conflict manually.
38
-
39
- [bold]Examples:[/bold]
40
-
41
- gx pull Pull and rebase current branch
42
- gx pull -n Preview what would happen
43
- gx pull -v Pull with debug output
44
- """
45
- if verbose:
46
- pp.configure(verbosity=verbose)
47
- if dry_run:
48
- set_dry_run(enabled=True)
49
- check_git_repo()
50
-
51
- _branch, remote, remote_branch = validate_branch()
52
- stashed = stash_if_dirty()
53
- head_before = git("rev-parse", "HEAD")
54
-
55
- fetch_and_rebase(remote, remote_branch, stashed=stashed)
56
- update_submodules(stashed=stashed)
57
- unstash(stashed=stashed)
58
- print_pull_summary(head_before.stdout, remote, remote_branch)
@@ -1,18 +0,0 @@
1
- """Shared Typer options and arguments for gx commands."""
2
-
3
- import typer
4
-
5
- VERBOSE_OPTION: int = typer.Option(
6
- 0,
7
- "--verbose",
8
- "-v",
9
- count=True,
10
- help="Increase verbosity (-v debug, -vv trace).",
11
- )
12
-
13
- DRY_RUN_OPTION: bool = typer.Option(
14
- False, # noqa: FBT003
15
- "--dry-run",
16
- "-n",
17
- help="Show what would be done without making changes.",
18
- )
@@ -1,90 +0,0 @@
1
- """Pull-the-remote flow helpers.
2
-
3
- Reusable primitives for fetching, rebasing, and reporting on remote-sync
4
- operations against the current branch's upstream.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import typer
10
- from nclutils import pp
11
- from nclutils.git import current_branch, is_rebase_in_progress, tracking_branch
12
-
13
- from gx.lib.display import commit_text
14
- from gx.lib.git import git
15
- from gx.lib.workspace import rollback
16
-
17
-
18
- def validate_branch() -> tuple[str, str, str]:
19
- """Validate branch state and return (branch, remote, remote_branch).
20
-
21
- Raises:
22
- typer.Exit: If the branch is detached or has no upstream configured.
23
- """
24
- branch = current_branch()
25
- if branch is None:
26
- pp.error("Cannot sync - HEAD is detached.")
27
- raise typer.Exit(1)
28
-
29
- tracking = tracking_branch()
30
- if tracking is None:
31
- pp.error(f"Branch '{branch}' has no upstream tracking branch configured.")
32
- raise typer.Exit(1)
33
-
34
- remote, remote_branch = tracking
35
- return branch, remote, remote_branch
36
-
37
-
38
- def fetch_and_rebase(remote: str, remote_branch: str, *, stashed: bool) -> None:
39
- """Fetch from remote and pull with rebase.
40
-
41
- Args:
42
- remote: The remote name to fetch from.
43
- remote_branch: The remote branch to rebase onto.
44
- stashed: Whether local changes were stashed, used for rollback.
45
- """
46
- with pp.step(f"Fetch from {remote}"):
47
- result = git("fetch", remote)
48
- if not result.ok:
49
- rollback(stashed=stashed)
50
-
51
- with pp.step(f"Pull with rebase from {remote}/{remote_branch}"):
52
- result = git("pull", "--rebase", remote, remote_branch)
53
- if not result.ok:
54
- if is_rebase_in_progress():
55
- pp.error(
56
- "Rebase conflict detected",
57
- details=[
58
- "1. Fix the conflicts in the affected files",
59
- "2. Stage the resolved files with 'git add'",
60
- "3. Continue with 'git rebase --continue'",
61
- "Or abort with 'git rebase --abort'",
62
- ],
63
- )
64
- else:
65
- pp.error(f"Failed to pull from {remote}/{remote_branch}")
66
- rollback(stashed=stashed)
67
-
68
-
69
- def print_pull_summary(head_before: str, remote: str, remote_branch: str) -> None:
70
- """Print a summary of commits pulled since the pre-pull HEAD.
71
-
72
- Args:
73
- head_before: The commit SHA before the pull.
74
- remote: The remote name.
75
- remote_branch: The remote branch name.
76
- """
77
- head_after = git("rev-parse", "HEAD")
78
- if head_before == head_after.stdout:
79
- pp.success("Already up to date")
80
- return
81
-
82
- log_result = git("log", "--oneline", f"{head_before}..{head_after.stdout}")
83
- if log_result.ok and log_result.stdout:
84
- commits = log_result.stdout.splitlines()
85
- pp.success(
86
- f"Pull {len(commits)} new commit(s) from {remote}/{remote_branch}",
87
- details=[commit_text(c) for c in commits],
88
- )
89
- else:
90
- pp.success("Pull complete")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes