Compare commits

...
3 Commits
Author SHA1 Message Date
Rahul Yadav affca0d4ab sync: add repo.smartsyncdefault checkout policy
Workspace managers that provision repo checkouts need a way to make
Smart Sync the default for branches that define a manifest server,
without silently falling back to ToT on Smart Sync failures (where
unapproved or broken ToT trees defeat the point of Smart Sync).

Previously, setting repo.smartsync=true on init had two drawbacks:
it overrode per-user sync.smartsync=false and manifest-level opt-outs,
and default Smart Sync failures still fell back silently to ToT.
Removing <manifest-server> from a branch manifest to opt out also broke
explicit -s/-t syncs.

With repo.smartsyncdefault=explicit configured on a checkout:

- Plain repo sync enables Smart Sync whenever the manifest defines
  <manifest-server>, unless overridden by CLI flags, repo.smartsync,
  sync.smartsync, or <default sync-smartsync="false"/>.
- Default-enabled Smart Sync failures abort the sync instead of
  falling back to ToT, and print a hint pointing users to
  --no-smart-sync (or --head) to bypass Smart Sync for that sync.
- Branches without <manifest-server> or with
  <default sync-smartsync="false"/> sync ToT by default while keeping
  explicit -s/-t functional.

Bug: 543101585
Bug: 568962967
Test: pytest tests/test_manifest_xml.py tests/test_project.py
Test: pytest tests/test_subcmds_sync.py tests/e2e/test_init_sync.py
Change-Id: I5de45544df84366592978dd81c01e10dae964a1e
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/658243
Tested-by: Rahul Yadav <yadavrah@google.com>
Reviewed-by: Gavin Mak <gavinmak@google.com>
Commit-Queue: Rahul Yadav <yadavrah@google.com>
2026-11-23 11:08:55 -08:00
Gavin Mak 344ec87370 init, sync: persist --manifest-depth across syncs
Store --manifest-depth in repo.manifestdepth so subsequent repo sync and
repo init runs preserve shallow manifest checkouts instead of
unshallowing .repo/manifests, while --manifest-depth=0 restores a full
manifest clone.

Also exclude pre-fetch shallow upstream commits when updating shallow
tracking branches so advancing a shallow manifest branch resets cleanly
without bogus discard notices or failed shallow-root rebases.

Bug: 543101585
Change-Id: I59d056e9d12a3ded8c55a3f55b7de3447e2bf788
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/653243
Tested-by: Gavin Mak <gavinmak@google.com>
Reviewed-by: Brian Gan <brgan@google.com>
Commit-Queue: Gavin Mak <gavinmak@google.com>
2026-11-17 15:14:55 -08:00
Ram Peri 08b54387c7 manifest: default sync-tags to false when depth is set
Default per-project `sync-tags` to `false` on non-mirror checkouts
whenever `clone-depth` or `repo init --depth` is set to any value
(including shallow git submodules) and neither `<project>` nor
`<default>` explicitly specifies `sync-tags`. Preserve explicit
`sync-tags` overrides on `<default>` and `<project>` across `ToXml()`
serialization, and update the manifest format docs and manpage.

Also evaluate `clone_filter_for_depth` before checking `_HasShallow()`
in `Sync_NetworkHalf` (and guard `RepoProject` via `isinstance` rather
than a hardcoded path) so incremental syncs with `REPO_ALLOW_SHALLOW=0`
keep passing the configured partial-clone filter when no `.git/shallow`
file exists.

Previously, depth-limited projects relied on `_RemoteFetch` forcing
`--no-tags` only while `depth` remained non-None, so partial-clone or
converted checkouts without `.git/shallow` fell back to
`sync-tags="true"` and fetched all remote tags.

Bug: 584022911
Test: vpython3 run_tests
Change-Id: I9167f4e9fc075c4f1514f729acfb188bc093d5c5
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/656244
Tested-by: Ram Peri <ramperi@google.com>
Commit-Queue: Ram Peri <ramperi@google.com>
Reviewed-by: Mike Frysinger <vapier@google.com>
2026-11-17 10:29:43 -08:00
17 changed files with 1459 additions and 82 deletions

No files matched your search

+2
View File
@@ -175,11 +175,13 @@ User controlled settings are initialized when running `repo init`.
| repo.depth | `--depth` | Create shallow checkouts when cloning | | repo.depth | `--depth` | Create shallow checkouts when cloning |
| repo.dissociate | `--dissociate` | Dissociate from any reference/mirrors after initial clone | | repo.dissociate | `--dissociate` | Dissociate from any reference/mirrors after initial clone |
| repo.git-lfs | `--git-lfs` | Enable [Git LFS] support | | repo.git-lfs | `--git-lfs` | Enable [Git LFS] support |
| repo.manifestdepth | `--manifest-depth` | Create shallow manifest checkout when cloning |
| repo.mirror | `--mirror` | Checkout is a repo mirror | | repo.mirror | `--mirror` | Checkout is a repo mirror |
| repo.partialclone | `--partial-clone` | Create [partial git clones] | | repo.partialclone | `--partial-clone` | Create [partial git clones] |
| repo.partialcloneexclude | `--partial-clone-exclude` | Comma-delimited list of project names (not paths) to exclude while using [partial git clones] | | repo.partialcloneexclude | `--partial-clone-exclude` | Comma-delimited list of project names (not paths) to exclude while using [partial git clones] |
| repo.reference | `--reference` | Reference repo client checkout | | repo.reference | `--reference` | Reference repo client checkout |
| repo.smartsync | `--smart-sync` | Default to [Smart Sync](./smart-sync.md) when syncing | | repo.smartsync | `--smart-sync` | Default to [Smart Sync](./smart-sync.md) when syncing |
| repo.smartsyncdefault | (internal) | Fallback [Smart Sync](./smart-sync.md) policy; `explicit` enables Smart Sync when `<manifest-server>` is set (below CLI, `repo.smartsync`, `sync.smartsync`, and `sync-smartsync`) and treats default Smart Syncs as explicit |
| repo.\<branch\>.smartsyncbranch | `--smart-sync-branch` | Server branch to query when [Smart Sync](./smart-sync.md)ing `<branch>` | | repo.\<branch\>.smartsyncbranch | `--smart-sync-branch` | Server branch to query when [Smart Sync](./smart-sync.md)ing `<branch>` |
| repo.submodules | `--submodules` | Sync git submodules | | repo.submodules | `--submodules` | Sync git submodules |
| repo.superproject | `--use-superproject` | Sync [superproject] | | repo.superproject | `--use-superproject` | Sync [superproject] |
+21 -3
View File
@@ -235,9 +235,16 @@ Attribute `sync-s`: Set to true to also sync sub-projects.
Attribute `sync-tags`: Set to false to only sync the given Git Attribute `sync-tags`: Set to false to only sync the given Git
branch (specified in the `revision` attribute) rather than branch (specified in the `revision` attribute) rather than
the other ref tags. the other ref tags, or set to true to force syncing tags even
for projects with `clone-depth` (or `repo init --depth`) set.
Project elements lacking a `sync-tags` attribute of their own
will use this value if specified; otherwise projects default to
false when depth is set on a non-mirror checkout, and true
otherwise.
Attribute `sync-smartsync`: Set to true to enable smart sync by default. Attribute `sync-smartsync`: Set to true to enable smart sync by default,
or set to false to disable default smart sync for the manifest (explicit
`-s`/`-t` invocations still work when `<manifest-server>` is defined).
### Element manifest-server ### Element manifest-server
@@ -390,13 +397,24 @@ whole ref space.
Attribute `sync-s`: Set to true to also sync sub-projects. Attribute `sync-s`: Set to true to also sync sub-projects.
Attribute `sync-tags`: Set to false to only sync the given Git
branch (specified in the `revision` attribute) rather than other
ref tags, or set to true to force syncing tags. If unspecified,
the `default` element's `sync-tags` setting is used if set;
otherwise defaults to false when `clone-depth` (or
`repo init --depth`) is set on a non-mirror checkout, and true
otherwise.
Attribute `upstream`: Name of the Git ref in which a sha1 Attribute `upstream`: Name of the Git ref in which a sha1
can be found. Used when syncing a revision locked manifest in can be found. Used when syncing a revision locked manifest in
-c mode to avoid having to sync the entire ref space. -c mode to avoid having to sync the entire ref space.
Attribute `clone-depth`: Set the depth to use when fetching this Attribute `clone-depth`: Set the depth to use when fetching this
project. If specified, this value will override any value given project. If specified, this value will override any value given
to repo init with the --depth option on the command line. to repo init with the --depth option on the command line. Setting
`clone-depth` also defaults this project's `sync-tags` attribute
to false unless `sync-tags` is explicitly set on the `project` or
`default` element.
Attribute `force-path`: Set to true to force this project to create the Attribute `force-path`: Set to true to force this project to create the
local mirror repository according to its `path` attribute (if supplied) local mirror repository according to its `path` attribute (if supplied)
+5
View File
@@ -245,6 +245,11 @@ explicit target or manifest source (such as `-t`/`--smart-tag`,
`-m`/`--manifest-name` or `--superproject-revision`) will also disable the `-m`/`--manifest-name` or `--superproject-revision`) will also disable the
default Smart Sync behavior. default Smart Sync behavior.
Setting `sync-smartsync="false"` explicitly opts the manifest out of default
Smart Sync (for example, overriding a checkout fallback policy) while keeping
`<manifest-server>` available for explicit `-s`/`--smart-sync` and
`-t`/`--smart-tag` invocations.
Users can override this manifest default on their workstation with the Users can override this manifest default on their workstation with the
`sync.smartsync` user setting; see `sync.smartsync` user setting; see
[Per-user default](#Per_user-default-sync_smartsync) below. [Per-user default](#Per_user-default-sync_smartsync) below.
+1 -1
View File
@@ -47,7 +47,7 @@ sync any submodules associated with the manifest repo
download the manifest as a static file rather then create a git checkout of the manifest repo download the manifest as a static file rather then create a git checkout of the manifest repo
.TP .TP
\fB\-\-manifest\-depth\fR=\fI\,DEPTH\/\fR \fB\-\-manifest\-depth\fR=\fI\,DEPTH\/\fR
create a shallow clone of the manifest repo with given depth (0 for full clone); see git clone (default: 0) create a shallow clone of the manifest repo with given depth (0 for full clone); see git clone
.SS Manifest (only) checkout options: .SS Manifest (only) checkout options:
.TP .TP
\fB\-c\fR, \fB\-\-current\-branch\fR \fB\-c\fR, \fB\-\-current\-branch\fR
+18 -4
View File
@@ -1,5 +1,5 @@
.\" DO NOT MODIFY THIS FILE! It was generated by help2man. .\" DO NOT MODIFY THIS FILE! It was generated by help2man.
.TH REPO "1" "October 2026" "repo manifest" "Repo Manual" .TH REPO "1" "November 2026" "repo manifest" "Repo Manual"
.SH NAME .SH NAME
repo \- repo manifest - manual page for repo manifest repo \- repo manifest - manual page for repo manifest
.SH SYNOPSIS .SH SYNOPSIS
@@ -340,9 +340,15 @@ lacking a sync\-c element of their own will use this value.
Attribute `sync\-s`: Set to true to also sync sub\-projects. Attribute `sync\-s`: Set to true to also sync sub\-projects.
.PP .PP
Attribute `sync\-tags`: Set to false to only sync the given Git branch (specified Attribute `sync\-tags`: Set to false to only sync the given Git branch (specified
in the `revision` attribute) rather than the other ref tags. in the `revision` attribute) rather than the other ref tags, or set to true to
force syncing tags even for projects with `clone\-depth` (or `repo init \fB\-\-depth\fR`)
set. Project elements lacking a `sync\-tags` attribute of their own will use this
value if specified; otherwise projects default to false when depth is set on a
non\-mirror checkout, and true otherwise.
.PP .PP
Attribute `sync\-smartsync`: Set to true to enable smart sync by default. Attribute `sync\-smartsync`: Set to true to enable smart sync by default, or set
to false to disable default smart sync for the manifest (explicit `\-s`/`\-t`
invocations still work when `<manifest\-server>` is defined).
.PP .PP
Element manifest\-server Element manifest\-server
.PP .PP
@@ -482,13 +488,21 @@ the `revision` attribute) rather than the whole ref space.
.PP .PP
Attribute `sync\-s`: Set to true to also sync sub\-projects. Attribute `sync\-s`: Set to true to also sync sub\-projects.
.PP .PP
Attribute `sync\-tags`: Set to false to only sync the given Git branch (specified
in the `revision` attribute) rather than other ref tags, or set to true to force
syncing tags. If unspecified, the `default` element's `sync\-tags` setting is
used if set; otherwise defaults to false when `clone\-depth` (or `repo init
\fB\-\-depth\fR`) is set on a non\-mirror checkout, and true otherwise.
.PP
Attribute `upstream`: Name of the Git ref in which a sha1 can be found. Used Attribute `upstream`: Name of the Git ref in which a sha1 can be found. Used
when syncing a revision locked manifest in \fB\-c\fR mode to avoid having to sync the when syncing a revision locked manifest in \fB\-c\fR mode to avoid having to sync the
entire ref space. entire ref space.
.PP .PP
Attribute `clone\-depth`: Set the depth to use when fetching this project. If Attribute `clone\-depth`: Set the depth to use when fetching this project. If
specified, this value will override any value given to repo init with the specified, this value will override any value given to repo init with the
\fB\-\-depth\fR option on the command line. \fB\-\-depth\fR option on the command line. Setting `clone\-depth` also defaults this
project's `sync\-tags` attribute to false unless `sync\-tags` is explicitly set on
the `project` or `default` element.
.PP .PP
Attribute `force\-path`: Set to true to force this project to create the local Attribute `force\-path`: Set to true to force this project to create the local
mirror repository according to its `path` attribute (if supplied) rather than mirror repository according to its `path` attribute (if supplied) rather than
+32 -11
View File
@@ -18,6 +18,7 @@ import os
import platform import platform
import re import re
import sys import sys
from typing import Optional
import urllib.parse import urllib.parse
import xml.dom.minidom import xml.dom.minidom
@@ -157,8 +158,8 @@ class _Default:
sync_j_max = None sync_j_max = None
sync_c = False sync_c = False
sync_s = False sync_s = False
sync_tags = True sync_tags = None
sync_smartsync = False sync_smartsync = None
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, _Default): if not isinstance(other, _Default):
@@ -654,12 +655,14 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
if d.sync_s: if d.sync_s:
have_default = True have_default = True
e.setAttribute("sync-s", "true") e.setAttribute("sync-s", "true")
if not d.sync_tags: if d.sync_tags is not None:
have_default = True have_default = True
e.setAttribute("sync-tags", "false") e.setAttribute("sync-tags", "true" if d.sync_tags else "false")
if d.sync_smartsync: if d.sync_smartsync is not None:
have_default = True have_default = True
e.setAttribute("sync-smartsync", "true") e.setAttribute(
"sync-smartsync", "true" if d.sync_smartsync else "false"
)
if have_default: if have_default:
root.appendChild(e) root.appendChild(e)
root.appendChild(doc.createTextNode("")) root.appendChild(doc.createTextNode(""))
@@ -776,8 +779,9 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
if p.sync_s: if p.sync_s:
e.setAttribute("sync-s", "true") e.setAttribute("sync-s", "true")
if not p.sync_tags: sync_tags = self._project_sync_tags.get(p)
e.setAttribute("sync-tags", "false") if sync_tags is not None:
e.setAttribute("sync-tags", "true" if sync_tags else "false")
if p.clone_depth: if p.clone_depth:
e.setAttribute("clone-depth", str(p.clone_depth)) e.setAttribute("clone-depth", str(p.clone_depth))
@@ -1176,6 +1180,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
""" """
self._loaded = False self._loaded = False
self._projects = {} self._projects = {}
self._project_sync_tags = {}
self._paths = {} self._paths = {}
self._remotes = {} self._remotes = {}
self._default = None self._default = None
@@ -1810,8 +1815,8 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
d.sync_c = XmlBool(node, "sync-c", False) d.sync_c = XmlBool(node, "sync-c", False)
d.sync_s = XmlBool(node, "sync-s", False) d.sync_s = XmlBool(node, "sync-s", False)
d.sync_tags = XmlBool(node, "sync-tags", True) d.sync_tags = XmlBool(node, "sync-tags")
d.sync_smartsync = XmlBool(node, "sync-smartsync", False) d.sync_smartsync = XmlBool(node, "sync-smartsync")
return d return d
def _ParseNotice(self, node): def _ParseNotice(self, node):
@@ -1920,6 +1925,14 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
def _UnjoinName(self, parent_name, name): def _UnjoinName(self, parent_name, name):
return os.path.relpath(name, parent_name) return os.path.relpath(name, parent_name)
def _default_project_sync_tags(self, clone_depth: Optional[int]) -> bool:
"""Return the default sync-tags value for a project."""
if self._default.sync_tags is not None:
return self._default.sync_tags
if (clone_depth or self.manifestProject.depth) and not self.IsMirror:
return False
return True
def _ParseProject(self, node, parent=None, **extra_proj_attrs): def _ParseProject(self, node, parent=None, **extra_proj_attrs):
""" """
reads a <project> element from the manifest file reads a <project> element from the manifest file
@@ -1965,7 +1978,6 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
rebase = XmlBool(node, "rebase", True) rebase = XmlBool(node, "rebase", True)
sync_c = XmlBool(node, "sync-c", False) sync_c = XmlBool(node, "sync-c", False)
sync_s = XmlBool(node, "sync-s", self._default.sync_s) sync_s = XmlBool(node, "sync-s", self._default.sync_s)
sync_tags = XmlBool(node, "sync-tags", self._default.sync_tags)
clone_depth = XmlInt(node, "clone-depth") clone_depth = XmlInt(node, "clone-depth")
if clone_depth is not None and clone_depth <= 0: if clone_depth is not None and clone_depth <= 0:
@@ -1974,6 +1986,13 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
% (self.manifestFile, clone_depth) % (self.manifestFile, clone_depth)
) )
sync_tags_attr = XmlBool(node, "sync-tags")
sync_tags = (
sync_tags_attr
if sync_tags_attr is not None
else self._default_project_sync_tags(clone_depth)
)
sync_strategy = node.getAttribute("sync-strategy") or None sync_strategy = node.getAttribute("sync-strategy") or None
dest_branch = ( dest_branch = (
@@ -2029,6 +2048,8 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md
use_git_worktrees=use_git_worktrees, use_git_worktrees=use_git_worktrees,
**extra_proj_attrs, **extra_proj_attrs,
) )
if sync_tags_attr is not None:
self._project_sync_tags[project] = sync_tags_attr
for n in node.childNodes: for n in node.childNodes:
if n.nodeName == "copyfile": if n.nodeName == "copyfile":
+168 -32
View File
@@ -29,7 +29,7 @@ import sys
import tarfile import tarfile
import tempfile import tempfile
import time import time
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Union
import urllib.parse import urllib.parse
import color import color
@@ -180,6 +180,32 @@ def not_rev(r):
return "^" + r return "^" + r
def _SameTrackedUpstream(
branch_merge: Optional[str], revision_expr: Optional[str]
) -> bool:
"""Return whether |branch_merge| tracks |revision_expr|'s upstream."""
if (
not isinstance(branch_merge, str)
or not isinstance(revision_expr, str)
or not branch_merge
or not revision_expr
):
return False
if git_config.IsId(branch_merge) and git_config.IsId(revision_expr):
return True
norm_merge = (
branch_merge
if git_config.IsId(branch_merge) or branch_merge.startswith("refs/")
else git_refs.R_HEADS + branch_merge
)
norm_rev = (
revision_expr
if git_config.IsId(revision_expr) or revision_expr.startswith("refs/")
else git_refs.R_HEADS + revision_expr
)
return norm_merge == norm_rev
def sq(r): def sq(r):
return "'" + r.replace("'", "'''") + "'" return "'" + r.replace("'", "'''") + "'"
@@ -621,6 +647,7 @@ class RemoteSpec:
class Project: class Project:
# How long to wait before the first retry of a failed fetch. # How long to wait before the first retry of a failed fetch.
RETRY_SLEEP_INITIAL_SEC = 4.0 RETRY_SLEEP_INITIAL_SEC = 4.0
_pre_fetch_revid: Optional[str] = None
# These objects can be shared between several working trees. # These objects can be shared between several working trees.
@property @property
@@ -728,6 +755,7 @@ class Project:
self.annotations = [] self.annotations = []
self.dest_branch = dest_branch self.dest_branch = dest_branch
self.stateless_prune_needed = False self.stateless_prune_needed = False
self._pre_fetch_revid = None
# This will be filled in if a project is later identified to be the # This will be filled in if a project is later identified to be the
# project containing repo hooks. # project containing repo hooks.
@@ -1998,25 +2026,34 @@ class Project:
elif self.manifest.default.sync_c: elif self.manifest.default.sync_c:
current_branch_only = True current_branch_only = True
if tags is None: if self.manifest.IsMirror or isinstance(self, RepoProject):
tags = self.sync_tags
if self.clone_depth:
depth = self.clone_depth
else:
depth = self.manifest.manifestProject.depth
# If the project has been manually unshallowed (e.g. via
# `git fetch --unshallow`), don't re-shallow it during sync.
if depth and not is_new and not self._HasShallow():
depth = None depth = None
else:
depth = self._GetCloneDepth()
has_shallow = self._HasShallow()
if tags is None:
if isinstance(self, MetaProject) and depth:
# If using depth then we should not get all the tags since they
# may be outside of the depth.
tags = False
else:
tags = self.sync_tags
if depth and clone_filter_for_depth: if depth and clone_filter_for_depth:
depth = None depth = None
clone_filter = clone_filter_for_depth clone_filter = clone_filter_for_depth
# If the project has been manually unshallowed (e.g. via
# `git fetch --unshallow`), don't re-shallow it during sync.
if depth and not is_new and not has_shallow:
depth = None
self._pre_fetch_revid = None
remote_fetched = False remote_fetched = False
if use_fetch_cmd: if use_fetch_cmd:
if has_shallow and not is_new:
self._pre_fetch_revid = self._GetPreFetchRevisionId()
# The custom fetch command is executed unconditionally on every sync # The custom fetch command is executed unconditionally on every sync
# because it is responsible for updating tracking refs and # because it is responsible for updating tracking refs and
# FETCH_HEAD. # FETCH_HEAD.
@@ -2038,7 +2075,6 @@ class Project:
) )
else: else:
# See if we can skip the standard network fetch entirely. # See if we can skip the standard network fetch entirely.
has_shallow = self._HasShallow()
skip_fetch = ( skip_fetch = (
optimized_fetch optimized_fetch
and git_config.IsId(self.revisionExpr) and git_config.IsId(self.revisionExpr)
@@ -2050,6 +2086,8 @@ class Project:
) )
if not skip_fetch: if not skip_fetch:
if has_shallow and not is_new:
self._pre_fetch_revid = self._GetPreFetchRevisionId()
remote_fetched = True remote_fetched = True
try: try:
if not self._RemoteFetch( if not self._RemoteFetch(
@@ -2431,6 +2469,7 @@ class Project:
# See if we can perform a fast forward merge. This can happen if our # See if we can perform a fast forward merge. This can happen if our
# branch isn't in the exact same state as we last published. # branch isn't in the exact same state as we last published.
is_ancestor = True
try: try:
self.work_git.merge_base( self.work_git.merge_base(
"--is-ancestor", git_refs.HEAD, revid, log_as_error=False "--is-ancestor", git_refs.HEAD, revid, log_as_error=False
@@ -2438,6 +2477,7 @@ class Project:
# Skip the published logic. # Skip the published logic.
pub = False pub = False
except error.GitError: except error.GitError:
is_ancestor = False
pub = self.WasPublished(branch.name, all_refs) pub = self.WasPublished(branch.name, all_refs)
if pub: if pub:
@@ -2479,9 +2519,23 @@ class Project:
# Examine the local commits not in the remote. Find the # Examine the local commits not in the remote. Find the
# last one attributed to this user, if any. # last one attributed to this user, if any.
local_changes = self._revlist( revlist_args = [not_rev(revid), git_refs.HEAD]
not_rev(revid), git_refs.HEAD, format="%H %ce" shallow_oids: Set[str] = set()
) if not is_ancestor and upstream_gain and self._HasShallow():
if (
self._pre_fetch_revid
and self._pre_fetch_revid != revid
and _SameTrackedUpstream(branch.merge, self.revisionExpr)
):
revlist_args.append(not_rev(self._pre_fetch_revid))
shallow_oids = self._ReadShallowCommits()
local_changes = self._revlist(*revlist_args, format="%H %ce")
if shallow_oids:
local_changes = [
commit
for commit in local_changes
if commit.split(" ", 1)[0] not in shallow_oids
]
last_mine = None last_mine = None
cnt_mine = 0 cnt_mine = 0
for commit in local_changes: for commit in local_changes:
@@ -2541,7 +2595,7 @@ class Project:
if submodules: if submodules:
syncbuf.later2(self, _dosubmodules, not verbose) syncbuf.later2(self, _dosubmodules, not verbose)
syncbuf.later2(self, _docopyandlink, not verbose) syncbuf.later2(self, _docopyandlink, not verbose)
elif local_changes: elif local_changes or not is_ancestor:
try: try:
if reproject: if reproject:
self._ReprojectBranch( self._ReprojectBranch(
@@ -3207,6 +3261,15 @@ class Project:
revision=self.remote.revision, revision=self.remote.revision,
) )
clone_depth = 1 if shallow.lower() == "true" else None clone_depth = 1 if shallow.lower() == "true" else None
sync_tags = (
False
if (
clone_depth
and not self.manifest.IsMirror
and self.manifest.default.sync_tags is not True
)
else self.sync_tags
)
subproject = Project( subproject = Project(
manifest=self.manifest, manifest=self.manifest,
name=name, name=name,
@@ -3221,7 +3284,7 @@ class Project:
groups=self.groups, groups=self.groups,
sync_c=self.sync_c, sync_c=self.sync_c,
sync_s=self.sync_s, sync_s=self.sync_s,
sync_tags=self.sync_tags, sync_tags=sync_tags,
parent=self, parent=self,
clone_depth=clone_depth, clone_depth=clone_depth,
is_derived=True, is_derived=True,
@@ -3314,6 +3377,43 @@ class Project:
# There is no such persistent revision. We have to fetch it. # There is no such persistent revision. We have to fetch it.
return False return False
def _GetCloneDepth(self) -> Optional[int]:
"""Return configured shallow clone depth for this project, or None."""
return self.clone_depth or self.manifest.manifestProject.depth
def _GetPreFetchRevisionId(self) -> Optional[str]:
"""Return the checked-out branch's pre-fetch upstream commit ID."""
if not self.worktree or not os.path.exists(self.worktree):
return None
try:
cb = self.CurrentBranch
if not isinstance(cb, str) or not cb:
return None
branch = self.GetBranch(cb)
if not isinstance(branch.merge, str) or not branch.merge:
return None
local_merge = branch.LocalMerge
if not isinstance(local_merge, str) or not local_merge:
return None
if not git_config.IsId(local_merge) and self.bare_ref.is_loaded:
val = self.bare_ref.get(local_merge)
return val if isinstance(val, str) and val else None
resolved = self.bare_git.ResolveCommit(local_merge)
return resolved if isinstance(resolved, str) and resolved else None
except error.RepoError:
return None
def _ReadShallowCommits(self) -> Set[str]:
"""Return commit OIDs listed in this project's shallow file."""
if not self.gitdir:
return set()
shallow_path = os.path.join(self.gitdir, "shallow")
try:
with open(shallow_path, "r", encoding="utf-8") as fd:
return {line.strip() for line in fd if line.strip()}
except OSError:
return set()
def _HasShallow(self) -> bool: def _HasShallow(self) -> bool:
"""Check if this project has a shallow file in its gitdir.""" """Check if this project has a shallow file in its gitdir."""
return bool( return bool(
@@ -3602,7 +3702,7 @@ class Project:
verbose=False, verbose=False,
output_redir=None, output_redir=None,
alt_dir=None, alt_dir=None,
tags=True, tags: Optional[bool] = None,
prune=False, prune=False,
depth=None, depth=None,
submodules=False, submodules=False,
@@ -3617,9 +3717,12 @@ class Project:
# it will result in a shallow repository that cannot be cloned or # it will result in a shallow repository that cannot be cloned or
# fetched from. # fetched from.
# The repo project should also never be synced with partial depth. # The repo project should also never be synced with partial depth.
if self.manifest.IsMirror or self.relpath == ".repo/repo": if self.manifest.IsMirror or isinstance(self, RepoProject):
depth = None depth = None
if tags is None:
tags = not bool(depth)
if depth: if depth:
current_branch_only = True current_branch_only = True
@@ -3728,9 +3831,7 @@ class Project:
# large binaries and disable auto GC to prevent potential hangs. # large binaries and disable auto GC to prevent potential hangs.
# Check the configured depth because the `depth` argument might be None # Check the configured depth because the `depth` argument might be None
# if REPO_ALLOW_SHALLOW=0 converted it to a partial clone. # if REPO_ALLOW_SHALLOW=0 converted it to a partial clone.
effective_depth = ( effective_depth = self._GetCloneDepth()
self.clone_depth or self.manifest.manifestProject.depth
)
if effective_depth == 1 and git_command.git_require((2, 23, 0)): if effective_depth == 1 and git_command.git_require((2, 23, 0)):
cmd.append("--no-auto-gc") cmd.append("--no-auto-gc")
@@ -3790,9 +3891,7 @@ class Project:
str(("+refs/heads/*:") + remote.ToLocal("refs/heads/*")) str(("+refs/heads/*:") + remote.ToLocal("refs/heads/*"))
) )
# If using depth then we should not get all the tags since they may if not tags:
# be outside of the depth.
if not tags or depth:
cmd.append("--no-tags") cmd.append("--no-tags")
else: else:
cmd.append("--tags") cmd.append("--tags")
@@ -3987,9 +4086,7 @@ class Project:
return ok return ok
def _ApplyCloneBundle(self, initial=False, quiet=False, verbose=False): def _ApplyCloneBundle(self, initial=False, quiet=False, verbose=False):
if initial and ( if initial and self._GetCloneDepth():
self.manifest.manifestProject.depth or self.clone_depth
):
return False return False
remote = self.GetRemote() remote = self.GetRemote()
@@ -4696,9 +4793,7 @@ class Project:
# Disable auto-gc for depth=1 to prevent hangs during lazy fetches # Disable auto-gc for depth=1 to prevent hangs during lazy fetches
# inside git checkout for partial clones. # inside git checkout for partial clones.
effective_depth = ( effective_depth = self._GetCloneDepth()
self.clone_depth or self.manifest.manifestProject.depth
)
if effective_depth == 1: if effective_depth == 1:
self.config.SetBoolean("maintenance.auto", False) self.config.SetBoolean("maintenance.auto", False)
self.config.SetInt("gc.auto", 0) self.config.SetInt("gc.auto", 0)
@@ -6081,6 +6176,14 @@ class ManifestProject(MetaProject):
"""Whether we use smart sync by default.""" """Whether we use smart sync by default."""
return self.config.GetBoolean("repo.smartsync") return self.config.GetBoolean("repo.smartsync")
@property
def smart_sync_default(self) -> Optional[str]:
"""Checkout-level fallback smart sync policy (e.g. 'explicit')."""
val = self.config.GetString("repo.smartsyncdefault")
if val is None:
return None
return val.strip().lower() or None
@staticmethod @staticmethod
def _SmartSyncBranchKey(branch: str) -> str: def _SmartSyncBranchKey(branch: str) -> str:
"""Return the git config key for a branch's smart sync branch.""" """Return the git config key for a branch's smart sync branch."""
@@ -6112,6 +6215,20 @@ class ManifestProject(MetaProject):
"""Partial clone depth.""" """Partial clone depth."""
return self.config.GetInt("repo.depth") return self.config.GetInt("repo.depth")
@property
def manifest_depth(self) -> Optional[int]:
"""Shallow clone depth for the manifest repository."""
return self.config.GetInt("repo.manifestdepth")
def _GetCloneDepth(self) -> Optional[int]:
"""Return configured shallow clone depth for this manifest project."""
if self.clone_depth is not None:
return self.clone_depth if self.clone_depth > 0 else None
manifest_depth = self.manifest_depth
if manifest_depth is not None:
return manifest_depth if manifest_depth > 0 else None
return self.depth
@property @property
def clone_filter(self): def clone_filter(self):
"""The clone filter.""" """The clone filter."""
@@ -6201,6 +6318,7 @@ class ManifestProject(MetaProject):
current_branch_only=current_branch_only, current_branch_only=current_branch_only,
tags=tags, tags=tags,
depth=mp.depth, depth=mp.depth,
manifest_depth=mp.manifest_depth,
git_event_log=git_event_log, git_event_log=git_event_log,
manifest_name=spec.manifestName, manifest_name=spec.manifestName,
this_manifest_only=True, this_manifest_only=True,
@@ -6223,6 +6341,7 @@ class ManifestProject(MetaProject):
archive: Optional[bool] = False, archive: Optional[bool] = False,
partial_clone: Optional[bool] = None, partial_clone: Optional[bool] = None,
depth: Optional[int] = None, depth: Optional[int] = None,
manifest_depth: Optional[int] = None,
clone_filter: Optional[str] = "blob:none", clone_filter: Optional[str] = "blob:none",
partial_clone_exclude: Optional[str] = None, partial_clone_exclude: Optional[str] = None,
clone_bundle: Optional[bool] = None, clone_bundle: Optional[bool] = None,
@@ -6263,6 +6382,8 @@ class ManifestProject(MetaProject):
See git-archive. See git-archive.
partial_clone: a boolean, whether to perform a partial clone. partial_clone: a boolean, whether to perform a partial clone.
depth: an int, how deep of a shallow clone to create. depth: an int, how deep of a shallow clone to create.
manifest_depth: an int, how deep of a shallow manifest clone to
create (0 for full clone).
clone_filter: a string, filter to use with partial_clone. clone_filter: a string, filter to use with partial_clone.
partial_clone_exclude : a string, comma-delimeted list of project partial_clone_exclude : a string, comma-delimeted list of project
names to exclude from partial clone. names to exclude from partial clone.
@@ -6327,6 +6448,7 @@ class ManifestProject(MetaProject):
current_branch_only=current_branch_only, current_branch_only=current_branch_only,
tags=tags, tags=tags,
depth=depth, depth=depth,
manifest_depth=manifest_depth,
git_event_log=git_event_log, git_event_log=git_event_log,
manifest_name=manifest_name, manifest_name=manifest_name,
this_manifest_only=this_manifest_only, this_manifest_only=this_manifest_only,
@@ -6408,6 +6530,7 @@ class ManifestProject(MetaProject):
self.config.SetString("manifest.standalone", None) self.config.SetString("manifest.standalone", None)
self._ConfigureDepth(depth) self._ConfigureDepth(depth)
self._ConfigureManifestDepth(manifest_depth)
# Set the remote URL before the remote branch as we might need it below. # Set the remote URL before the remote branch as we might need it below.
if manifest_url: if manifest_url:
@@ -6702,6 +6825,7 @@ class ManifestProject(MetaProject):
current_branch_only=current_branch_only, current_branch_only=current_branch_only,
tags=tags, tags=tags,
depth=depth, depth=depth,
manifest_depth=manifest_depth,
git_event_log=git_event_log, git_event_log=git_event_log,
manifest_name=spec.manifestName, manifest_name=spec.manifestName,
this_manifest_only=False, this_manifest_only=False,
@@ -6759,3 +6883,15 @@ class ManifestProject(MetaProject):
# We store the depth in the main manifest project. # We store the depth in the main manifest project.
self.config.SetString("repo.depth", depth) self.config.SetString("repo.depth", depth)
def _ConfigureManifestDepth(self, manifest_depth: Optional[int]) -> None:
"""Configure the shallow clone depth for the manifest repository.
Args:
manifest_depth: Positive depth for a shallow manifest clone, 0 for
an explicit full clone, negative to clear, or None to leave
unchanged.
"""
if manifest_depth is not None:
value = str(manifest_depth) if manifest_depth >= 0 else None
self.config.SetString("repo.manifestdepth", value)
+2 -3
View File
@@ -328,11 +328,10 @@ def InitParser(parser: optparse.OptionParser) -> optparse.OptionParser:
group.add_option( group.add_option(
"--manifest-depth", "--manifest-depth",
type="int", type="int",
default=0, default=None,
metavar="DEPTH", metavar="DEPTH",
help="create a shallow clone of the manifest repo with " help="create a shallow clone of the manifest repo with "
"given depth (0 for full clone); see git clone " "given depth (0 for full clone); see git clone",
"(default: %default)",
) )
# Options that only affect manifest project, and not any of the projects # Options that only affect manifest project, and not any of the projects
+1 -1
View File
@@ -139,7 +139,6 @@ to update the working directory files.
# Normally this value is set when instantiating the project, but the # Normally this value is set when instantiating the project, but the
# manifest project is special and is created when instantiating the # manifest project is special and is created when instantiating the
# manifest which happens before we parse options. # manifest which happens before we parse options.
self.manifest.manifestProject.clone_depth = opt.manifest_depth
self.manifest.manifestProject.upstream = opt.manifest_upstream_branch self.manifest.manifestProject.upstream = opt.manifest_upstream_branch
clone_filter_for_depth = ( clone_filter_for_depth = (
"blob:none" if (_REPO_ALLOW_SHALLOW == "0") else None "blob:none" if (_REPO_ALLOW_SHALLOW == "0") else None
@@ -169,6 +168,7 @@ to update the working directory files.
current_branch_only=opt.current_branch_only, current_branch_only=opt.current_branch_only,
tags=opt.tags, tags=opt.tags,
depth=opt.depth, depth=opt.depth,
manifest_depth=opt.manifest_depth,
git_event_log=self.git_event_log, git_event_log=self.git_event_log,
manifest_name=opt.manifest_name, manifest_name=opt.manifest_name,
use_local_gitdirs=opt.use_local_gitdirs, use_local_gitdirs=opt.use_local_gitdirs,
+79 -21
View File
@@ -354,6 +354,7 @@ class _FetchOneResult(NamedTuple):
start (float): The starting time.time(). start (float): The starting time.time().
finish (float): The ending time.time(). finish (float): The ending time.time().
remote_fetched (bool): True if the remote was actually queried. remote_fetched (bool): True if the remote was actually queried.
pre_fetch_revid (Optional[str]): Pre-fetch commit hash for shallow sync.
""" """
success: bool success: bool
@@ -362,6 +363,7 @@ class _FetchOneResult(NamedTuple):
start: float start: float
finish: float finish: float
remote_fetched: bool remote_fetched: bool
pre_fetch_revid: Optional[str] = None
class _FetchResult(NamedTuple): class _FetchResult(NamedTuple):
@@ -1165,7 +1167,13 @@ later is required to fix a server side protocol bug.
finish = time.time() finish = time.time()
return _FetchOneResult( return _FetchOneResult(
success, errors, project_idx, start, finish, remote_fetched success,
errors,
project_idx,
start,
finish,
remote_fetched,
getattr(project, "_pre_fetch_revid", None),
) )
def _GetSyncProgressMessage(self): def _GetSyncProgressMessage(self):
@@ -1234,6 +1242,7 @@ later is required to fix a server side protocol bug.
for result in results: for result in results:
success = result.success success = result.success
project = projects[result.project_idx] project = projects[result.project_idx]
project._pre_fetch_revid = result.pre_fetch_revid
start = result.start start = result.start
finish = result.finish finish = result.finish
if success: if success:
@@ -1359,10 +1368,21 @@ later is required to fix a server side protocol bug.
Returns: Returns:
List of all projects that should be checked out. List of all projects that should be checked out.
""" """
pre_fetch_revids: Dict[Tuple[str, Optional[str]], str] = {}
def _record_pre_fetch_revids(projects: Iterable[Project]) -> None:
for project in projects:
revid = getattr(project, "_pre_fetch_revid", None)
if revid:
pre_fetch_revids.setdefault(
(project.gitdir, project.worktree), revid
)
try: try:
result = self._FetchParentFirst( result = self._FetchParentFirst(
all_projects, opt, err_event, ssh_proxy, errors all_projects, opt, err_event, ssh_proxy, errors
) )
_record_pre_fetch_revids(all_projects)
success = result.success success = result.success
fetched = result.projects fetched = result.projects
if not success: if not success:
@@ -1408,6 +1428,7 @@ later is required to fix a server side protocol bug.
result = self._FetchParentFirst( result = self._FetchParentFirst(
missing, opt, err_event, ssh_proxy, errors missing, opt, err_event, ssh_proxy, errors
) )
_record_pre_fetch_revids(missing)
success = result.success success = result.success
new_fetched = result.projects new_fetched = result.projects
if not success: if not success:
@@ -1417,6 +1438,10 @@ later is required to fix a server side protocol bug.
self._fetch_times.Save() self._fetch_times.Save()
self._local_sync_state.Save() self._local_sync_state.Save()
for project in all_projects:
project._pre_fetch_revid = pre_fetch_revids.get(
(project.gitdir, project.worktree)
)
return _FetchMainResult(all_projects) return _FetchMainResult(all_projects)
@classmethod @classmethod
@@ -2688,19 +2713,40 @@ later is required to fix a server side protocol bug.
) -> bool: ) -> bool:
"""Resolve opt.smart_sync from CLI flags, config, and manifest. """Resolve opt.smart_sync from CLI flags, config, and manifest.
Precedence: CLI flags > per-checkout settings > per-user settings > Precedence: CLI flags > repo.smartsync > sync.smartsync >
per-manifest settings. <default sync-smartsync> > repo.smartsyncdefault.
See docs/repoconfig.md and docs/smart-sync.md for details. See docs/repoconfig.md, docs/smart-sync.md, and
docs/internal-fs-layout.md for details.
Returns: Returns:
True if smart_sync was enabled implicitly by checkout or manifest True if smart_sync was enabled implicitly by checkout or manifest
default, False otherwise. Smart sync enabled via per-user settings default, False otherwise. Smart sync enabled via per-user settings
counts as an explicit user request, not implicit. or in a checkout with repo.smartsyncdefault=explicit counts as an
explicit request, not implicit.
""" """
checkout_pref = getattr(manifest.manifestProject, "smart_sync", None) checkout_pref = getattr(manifest.manifestProject, "smart_sync", None)
if not isinstance(checkout_pref, bool): if not isinstance(checkout_pref, bool):
checkout_pref = None checkout_pref = None
checkout_default = getattr(
manifest.manifestProject, "smart_sync_default", None
)
if not isinstance(checkout_default, str):
checkout_default = None
else:
checkout_default = checkout_default.strip().lower() or None
if checkout_default is not None and checkout_default != "explicit":
logger.warning(
"warning: ignoring unknown repo.smartsyncdefault "
'value "%s"',
checkout_default,
)
checkout_default = None
explicit_default = checkout_default == "explicit"
user_pref = git_config.RepoConfig.ForUser().GetBoolean("sync.smartsync") user_pref = git_config.RepoConfig.ForUser().GetBoolean("sync.smartsync")
manifest_pref = getattr(manifest.default, "sync_smartsync", None)
if not isinstance(manifest_pref, bool):
manifest_pref = None
default_allowed = ( default_allowed = (
opt.smart_sync is None opt.smart_sync is None
and not opt.smart_tag and not opt.smart_tag
@@ -2708,25 +2754,30 @@ later is required to fix a server side protocol bug.
and not opt.superproject_revision and not opt.superproject_revision
and not opt.local_only and not opt.local_only
) )
default_smart_sync = (
checkout_pref
if checkout_pref is not None
else getattr(manifest.default, "sync_smartsync", False) is True
)
implicit = (
default_allowed
and (checkout_pref is not None or user_pref is None)
and default_smart_sync
)
if opt.smart_sync is None: if opt.smart_sync is None:
if checkout_pref is not None: if not default_allowed:
opt.smart_sync = implicit
elif user_pref is False:
opt.smart_sync = False opt.smart_sync = False
elif user_pref is True: implicit = False
opt.smart_sync = default_allowed elif checkout_pref is not None:
opt.smart_sync = checkout_pref
implicit = checkout_pref and not explicit_default
elif user_pref is not None:
opt.smart_sync = user_pref
implicit = False
elif manifest_pref is not None:
opt.smart_sync = manifest_pref
implicit = manifest_pref and not explicit_default
elif explicit_default:
manifest_server = getattr(manifest, "manifest_server", None)
opt.smart_sync = isinstance(manifest_server, str) and bool(
manifest_server
)
implicit = False
else: else:
opt.smart_sync = implicit opt.smart_sync = False
implicit = False
else:
implicit = False
if ( if (
opt.manifest_server_username or opt.manifest_server_password opt.manifest_server_username or opt.manifest_server_password
@@ -2764,6 +2815,7 @@ later is required to fix a server side protocol bug.
and os.path.isfile(smart_sync_manifest_path) and os.path.isfile(smart_sync_manifest_path)
) )
cli_smart_sync = bool(opt.smart_sync or getattr(opt, "smart_tag", None))
implicit_smart_sync = self._ResolveSmartSyncOption(opt, manifest) implicit_smart_sync = self._ResolveSmartSyncOption(opt, manifest)
if opt.smart_sync or opt.smart_tag: if opt.smart_sync or opt.smart_tag:
@@ -2776,6 +2828,12 @@ later is required to fix a server side protocol bug.
) )
except (SmartSyncError, error.ManifestParseError) as e: except (SmartSyncError, error.ManifestParseError) as e:
if not implicit_smart_sync: if not implicit_smart_sync:
if not cli_smart_sync:
logger.error(
"hint: Smart Sync was enabled by default; "
"pass --no-smart-sync (or --head) to sync to "
"ToT instead."
)
raise raise
# The user did not ask for a smart sync, so failing to get a # The user did not ask for a smart sync, so failing to get a
# usable manifest from the server should not fail the sync. # usable manifest from the server should not fail the sync.
+239 -4
View File
@@ -337,26 +337,128 @@ def test_standalone_manifest(host: GitHost, client: RepoClient) -> None:
assert "cannot be re-initialized without --manifest-url/-u" in result.stderr assert "cannot be re-initialized without --manifest-url/-u" in result.stderr
@pytest.mark.parametrize("git_defaults", GIT_DEFAULTS_PARAMS)
def test_manifest_depth(host: GitHost, client: RepoClient) -> None: def test_manifest_depth(host: GitHost, client: RepoClient) -> None:
"""`init --manifest-depth` shallow-clones the manifest repo only.""" """`init --manifest-depth` persists across `sync` and re-`init`."""
foo = host.create_repo("platform/foo", {"f": "1"}) foo = host.create_repo("platform/foo", {"f": "1"})
foo.commit({"f": "2"}) foo.commit({"f": "2"})
bar = host.create_repo("platform/bar", {"b": "1"})
bar.commit({"b": "2"})
host.create_manifest(manifest_xml()) host.create_manifest(manifest_xml())
host.update_manifest(manifest_xml('<project name="platform/foo" />')) host.update_manifest(manifest_xml('<project name="platform/foo" />'))
client.init(host.manifest_url, "--manifest-depth=1") client.init(host.manifest_url, "--manifest-depth=1")
manifests = ".repo/manifests" manifests = ".repo/manifests"
assert client.config(manifests, "repo.manifestdepth") == "1"
assert client.is_shallow(manifests) assert client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "1" assert client.git(manifests, "rev-list", "--count", "HEAD") == "1"
# `--nmu` skips updating the manifest project, keeping it shallow while # Plain `repo sync` keeps the manifest shallow while syncing projects at
# syncing projects at full depth. # full depth.
client.sync("--nmu") client.sync()
assert client.is_shallow(manifests) assert client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "1"
assert not client.is_shallow("platform/foo") assert not client.is_shallow("platform/foo")
assert client.git("platform/foo", "rev-list", "--count", "HEAD") == "2" assert client.git("platform/foo", "rev-list", "--count", "HEAD") == "2"
# Advancing the remote manifest keeps `.repo/manifests` shallow without
# emitting bogus "discarding" warnings, and also succeeds when the manifest
# committer matches the client's user.email.
new_rev = host.update_manifest(
manifest_xml(
'<project name="platform/foo" />',
'<project name="platform/bar" />',
)
)
res = client.sync()
assert "discarding" not in res.output
assert client.head(manifests) == new_rev
assert client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "1"
assert not client.is_shallow("platform/bar")
assert client.git("platform/bar", "rev-list", "--count", "HEAD") == "2"
# Match the server harness committer email (`committer@example.com`) to
# ensure advancing a shallow manifest branch never tries to rebase a
# grafted shallow root.
client.git(manifests, "config", "user.email", "committer@example.com")
bar.commit({"b": "3"})
newer_rev = host.update_manifest(
manifest_xml('<project name="platform/bar" />')
)
res = client.sync()
assert "discarding" not in res.output
assert client.head(manifests) == newer_rev
assert client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "1"
assert (client.top / "platform/bar" / "b").read_text() == "3"
# Re-running `repo init` without `--manifest-depth` preserves the setting.
client.init(host.manifest_url, "-g", "all")
assert client.config(manifests, "repo.manifestdepth") == "1"
assert client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "1"
# Passing `--manifest-depth=0` unshallows the manifest repo and persists.
client.init(host.manifest_url, "--manifest-depth=0")
assert client.config(manifests, "repo.manifestdepth") == "0"
assert not client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "4"
client.sync()
assert not client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "4"
def test_depth_with_manifest_depth_zero(
host: GitHost, client: RepoClient
) -> None:
"""`init --depth=1 --manifest-depth=0` keeps only projects shallow."""
foo = host.create_repo("platform/foo", {"f": "1"})
foo.commit({"f": "2"})
host.create_manifest(manifest_xml())
host.update_manifest(manifest_xml('<project name="platform/foo" />'))
client.init(host.manifest_url, "--depth=1", "--manifest-depth=0")
manifests = ".repo/manifests"
assert not client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "2"
client.sync()
assert not client.is_shallow(manifests)
assert client.git(manifests, "rev-list", "--count", "HEAD") == "2"
assert client.is_shallow("platform/foo")
assert client.git("platform/foo", "rev-list", "--count", "HEAD") == "1"
def test_shallow_phased_sync_tracking_branch(
host: GitHost, client: RepoClient
) -> None:
"""`sync --no-interleaved` advances shallow depth>1 tracking branches."""
foo = host.create_repo("platform/foo", {"f": "1"})
foo.commit({"f": "2"})
foo.commit({"f": "3"})
host.create_manifest(manifest_xml('<project name="platform/foo" />'))
client.init(host.manifest_url, "--depth=2")
client.sync("--no-interleaved")
path = "platform/foo"
client.run("start", "topic", path)
client.git(path, "config", "user.email", "committer@example.com")
foo.commit({"f": "4"})
foo.commit({"f": "5"})
latest = foo.commit({"f": "6"})
res = client.sync("--no-interleaved")
assert "discarding" not in res.output
assert client.head(path) == latest
assert client.is_shallow(path)
assert client.git(path, "rev-list", "--count", "HEAD") == "2"
@contextlib.contextmanager @contextlib.contextmanager
def _manifest_server( def _manifest_server(
@@ -470,3 +572,136 @@ def test_smart_sync_branch(host: GitHost, client: RepoClient) -> None:
) )
assert res.returncode != 0 assert res.returncode != 0
assert "requires the manifest checkout to track a branch" in res.stderr assert "requires the manifest checkout to track a branch" in res.stderr
def test_smart_sync_default_explicit(
host: GitHost, client: RepoClient, tmp_path: Path
) -> None:
"""`repo.smartsyncdefault=explicit` enables explicit Smart Sync fallback."""
foo = host.create_repo("platform/foo", {"f": "v1"})
v1 = foo.rev_parse("main")
tot = foo.commit({"f": "tot"})
requests: List[Dict[str, Any]] = []
fail_server = False
def handle_v2(req: Dict[str, Any]) -> Dict[str, Any]:
requests.append(req)
if fail_server:
return {"success": False, "error_message": "server unavailable"}
return {
"success": True,
"manifest_xml": manifest_xml(
f'<project name="platform/foo" path="foo" revision="{v1}" />',
fetch=host.url,
),
}
with _manifest_server(handle_v2) as server_url:
manifest = host.create_manifest(
manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
)
)
manifest.commit(
{
"default.xml": manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
default=(
'remote="origin" revision="main" '
'sync-smartsync="false"'
),
)
},
branch="opt-out",
)
manifest.commit(
{
"default.xml": manifest_xml(
f'<manifest-server url="{server_url}" />',
'<project name="platform/foo" path="foo" />',
default=(
'remote="origin" revision="main" '
'sync-smartsync="true"'
),
)
},
branch="opt-in",
)
manifest.commit(
{
"default.xml": manifest_xml(
'<project name="platform/foo" path="foo" />'
)
},
branch="no-server",
)
client.init(host.manifest_url)
client.git(
".repo/manifests", "config", "repo.smartsyncdefault", "explicit"
)
# Enables explicit Smart Sync when <manifest-server> is present.
client.sync()
assert len(requests) == 1
assert "best_effort" not in requests[-1]
assert client.head("foo") == v1
# Fails hard with a hint instead of falling back to ToT on error.
fail_server = True
res = client.sync(check=False)
assert res.returncode != 0
assert "--no-smart-sync" in res.stderr
assert len(requests) == 2
assert "best_effort" not in requests[-1]
# Explicit CLI -s failure does not emit the default-enabled hint.
res = client.sync("-s", check=False)
assert res.returncode != 0
assert "--no-smart-sync" not in res.stderr
assert len(requests) == 3
# <default sync-smartsync="false"/> opts out while keeping -s usable.
client.init(host.manifest_url, "-b", "opt-out")
client.sync()
assert len(requests) == 3
assert client.head("foo") == tot
fail_server = False
client.sync("-s")
assert len(requests) == 4
assert client.head("foo") == v1
# <default sync-smartsync="true"/> is also treated as explicit.
client.init(host.manifest_url, "-b", "opt-in")
fail_server = True
res = client.sync(check=False)
assert res.returncode != 0
assert "--no-smart-sync" in res.stderr
assert len(requests) == 5
assert "best_effort" not in requests[-1]
# Per-user sync.smartsync=false overrides repo.smartsyncdefault.
client.init(host.manifest_url, "-b", "main")
cfg_dir = tmp_path / "repoconfig"
(cfg_dir / ".repoconfig").mkdir(parents=True)
(cfg_dir / ".repoconfig" / "config").write_text(
"[sync]\n\tsmartsync = false\n"
)
saved_env = dict(client.env)
client.env["REPO_CONFIG_DIR"] = str(cfg_dir)
try:
client.sync()
finally:
client.env = saved_env
assert len(requests) == 5
assert client.head("foo") == tot
# Without <manifest-server>, sync falls through to regular ToT.
client.init(host.manifest_url, "-b", "no-server")
client.sync()
assert len(requests) == 5
assert client.head("foo") == tot
+165
View File
@@ -292,3 +292,168 @@ def test_partial_clone_two_phase_sync(
assert (client.top / path / "small").read_text() == "s2" assert (client.top / path / "small").read_text() == "s2"
assert client.has_object(path, s2_blob) assert client.has_object(path, s2_blob)
assert host.requested_repos(inc_requests) == {"platform/foo"} assert host.requested_repos(inc_requests) == {"platform/foo"}
@pytest.mark.parametrize("git_defaults", GIT_DEFAULTS_PARAMS)
def test_clone_depth_allow_shallow_zero_skips_tags(
host: GitHost, client: RepoClient
) -> None:
"""`REPO_ALLOW_SHALLOW=0` keeps `--no-tags` on `clone-depth` projects.
Non-`clone-depth` projects still fetch tags by default, and an explicit
`repo sync --tags` still fetches tags when requested.
"""
llvm, llvm_old_blob = create_with_big_history(host, "platform/llvm")
llvm.tag("v1", "main")
off_branch = llvm.commit({"release.bin": BIG + "rel"}, branch="release")
llvm.tag("llvmorg-23.1.0", off_branch)
foo = host.create_repo("platform/foo", {"f": "1"})
foo.tag("foo-v1", "main")
foo_rel = foo.commit({"f": "rel"}, branch="release")
foo.tag("foo-v2", foo_rel)
opt_in = host.create_repo("platform/opt-in", {"o": "1"})
opt_in.tag("opt-v1", "main")
opt_rel = opt_in.commit({"o": "rel"}, branch="release")
opt_in.tag("opt-v2", opt_rel)
host.create_manifest(
manifest_xml(
'<project name="platform/llvm" path="llvm" clone-depth="1" />',
'<project name="platform/foo" path="foo" />',
'<project name="platform/opt-in" path="opt-in" '
'clone-depth="2" sync-tags="true" />',
)
)
client.env["REPO_ALLOW_SHALLOW"] = "0"
client.init(host.manifest_url)
assert client.sync("-c").stderr == ""
client.env.pop("REPO_ALLOW_SHALLOW")
assert not client.is_shallow("llvm")
assert client.config("llvm", "extensions.partialclone") == "origin"
assert client.config("llvm", FILTER_KEY) == "blob:none"
assert not client.has_object("llvm", llvm_old_blob)
assert not client.has_object("llvm", off_branch)
assert client.tags("llvm") == set()
assert client.tags("foo") == {"foo-v1", "foo-v2"}
assert client.tags("opt-in") == {"opt-v1", "opt-v2"}
# Incremental sync after a new branch commit and a new off-branch tag keeps
# skipping tags on the clone-depth partial clone.
new_tip = llvm.commit({"small": "s2"})
off_branch_2 = llvm.commit({"release.bin": BIG + "rel2"}, branch="release")
llvm.tag("llvmorg-23.1.1", off_branch_2)
assert client.sync("-c").stderr == ""
assert client.head("llvm") == new_tip
assert not client.has_object("llvm", off_branch_2)
assert client.tags("llvm") == set()
# Explicit `--tags` still overrides the clone-depth default.
assert client.sync("-c", "--tags", "llvm").stderr == ""
assert client.tags("llvm") == {
"v1",
"llvmorg-23.1.0",
"llvmorg-23.1.1",
}
def test_clone_depth_converted_partial_clone_skips_tags(
host: GitHost, client: RepoClient
) -> None:
"""Converted partial-clone checkouts without `shallow` keep `--no-tags`."""
llvm, _ = create_with_big_history(host, "platform/llvm")
off_branch = llvm.commit({"release.bin": BIG + "rel"}, branch="release")
llvm.tag("llvmorg-23.1.0", off_branch)
host.create_manifest(
manifest_xml(
'<project name="platform/llvm" path="llvm" clone-depth="1" />'
)
)
client.init(host.manifest_url, "--partial-clone")
assert client.sync("-c").stderr == ""
assert client.is_shallow("llvm")
assert client.tags("llvm") == set()
# Simulate a checkout whose shallow boundary was removed during partial
# clone conversion/compaction (and without repo.partialclone set globally).
(client.repodir / "projects/llvm.git/shallow").unlink()
client.git(".repo/manifests", "config", "--unset", "repo.partialclone")
new_tip = llvm.commit({"small": "s2"})
llvm.tag("llvmorg-23.1.1", off_branch)
assert client.sync("-c").stderr == ""
assert client.head("llvm") == new_tip
assert not client.is_shallow("llvm")
assert not client.has_object("llvm", off_branch)
assert client.tags("llvm") == set()
def test_clone_depth_partial_clone_tag_revision(
host: GitHost, client: RepoClient
) -> None:
"""Tag-pinned `clone-depth` partial clones fetch only the pinned tag."""
llvm, _ = create_with_big_history(host, "platform/llvm")
llvm.git("tag", "-a", "-m", "pinned release", "v1.0", "main")
off_branch = llvm.commit({"release.bin": BIG + "rel"}, branch="release")
llvm.tag("v2.0", off_branch)
host.create_manifest(
manifest_xml(
'<project name="platform/llvm" path="llvm" '
'clone-depth="1" revision="refs/tags/v1.0" />'
)
)
client.env["REPO_ALLOW_SHALLOW"] = "0"
client.init(host.manifest_url)
assert client.sync("-c").stderr == ""
client.env.pop("REPO_ALLOW_SHALLOW")
assert client.head("llvm") == llvm.rev_parse("v1.0^{commit}")
assert client.tags("llvm") == {"v1.0"}
assert not client.has_object("llvm", off_branch)
def test_init_depth_allow_shallow_zero_defaults_sync_tags_false(
host: GitHost, client: RepoClient
) -> None:
"""`repo init --depth` with `REPO_ALLOW_SHALLOW=0` defaults `--no-tags`."""
foo, _ = create_with_big_history(host, "platform/foo")
off_branch = foo.commit({"release.bin": BIG + "rel"}, branch="release")
foo.tag("v1.0", off_branch)
opt_in = host.create_repo("platform/opt-in", {"o": "1"})
opt_in.tag("opt-v1", "main")
host.create_manifest(
manifest_xml(
'<project name="platform/foo" path="foo" />',
'<project name="platform/opt-in" path="opt-in" sync-tags="true" />',
)
)
client.env["REPO_ALLOW_SHALLOW"] = "0"
client.init(host.manifest_url, "--depth=2")
assert client.sync("-c").stderr == ""
client.env.pop("REPO_ALLOW_SHALLOW")
assert not client.is_shallow("foo")
assert client.config("foo", FILTER_KEY) == "blob:none"
assert client.tags("foo") == set()
assert client.tags("opt-in") == {"opt-v1"}
# An explicit `<default sync-tags="true" />` overrides the depth heuristic.
host.create_manifest(
'<manifest><remote name="origin" fetch=".." />'
'<default remote="origin" revision="refs/heads/main" '
'sync-tags="true" />'
'<project name="platform/foo" path="foo" clone-depth="1" />'
'<project name="platform/opt-in" path="opt-in" />'
"</manifest>\n"
)
assert client.sync("-c").stderr == ""
assert client.tags("foo") == {"v1.0"}
+4
View File
@@ -193,6 +193,10 @@ def test_two_phase_sync_superproject(host: GitHost, client: RepoClient) -> None:
(["-c", "--no-tags"], "", False), (["-c", "--no-tags"], "", False),
(["-c"], 'sync-tags="false"', False), (["-c"], 'sync-tags="false"', False),
(["-c", "--tags"], 'sync-tags="false"', True), (["-c", "--tags"], 'sync-tags="false"', True),
(["-c"], 'clone-depth="2"', False),
(["-c"], 'clone-depth="2" sync-tags="false"', False),
(["-c"], 'clone-depth="2" sync-tags="true"', True),
(["-c", "--tags"], 'clone-depth="2"', True),
], ],
) )
def test_tags( def test_tags(
+161 -2
View File
@@ -427,7 +427,8 @@ class TestXmlManifest:
manifest = repo_client.get_xml_manifest( manifest = repo_client.get_xml_manifest(
"<manifest><default /></manifest>" "<manifest><default /></manifest>"
) )
assert manifest.default.sync_smartsync is False assert manifest.default.sync_smartsync is None
assert manifest.ToXml().toxml() == '<?xml version="1.0" ?><manifest/>'
manifest = repo_client.get_xml_manifest( manifest = repo_client.get_xml_manifest(
'<manifest><default sync-smartsync="true" /></manifest>' '<manifest><default sync-smartsync="true" /></manifest>'
@@ -442,7 +443,10 @@ class TestXmlManifest:
'<manifest><default sync-smartsync="false" /></manifest>' '<manifest><default sync-smartsync="false" /></manifest>'
) )
assert manifest.default.sync_smartsync is False assert manifest.default.sync_smartsync is False
assert manifest.ToXml().toxml() == '<?xml version="1.0" ?><manifest/>' assert (
manifest.ToXml().toxml() == '<?xml version="1.0" ?>'
'<manifest><default sync-smartsync="false"/></manifest>'
)
def test_clear_override(self, repo_client: RepoClient) -> None: def test_clear_override(self, repo_client: RepoClient) -> None:
"""Check ClearOverride reverts to the default manifest.""" """Check ClearOverride reverts to the default manifest."""
@@ -813,6 +817,161 @@ class TestProjectElement:
"</manifest>" "</manifest>"
) )
def test_sync_tags_defaults_and_clone_depth(
self, repo_client: RepoClient
) -> None:
"""Check sync-tags defaults with clone-depth, <default>, and --depth."""
manifest = repo_client.get_xml_manifest(
"""
<manifest>
<remote name="default-remote" fetch="http://localhost" />
<default remote="default-remote" revision="refs/heads/main" />
<project name="plain" />
<project name="explicit-on" sync-tags="true" />
<project name="explicit-off" sync-tags="false" />
<project name="depth-one" clone-depth="1" />
<project name="depth-five" clone-depth="5" />
<project name="depth-opt-in" clone-depth="2" sync-tags="true" />
<project name="depth-opt-out" clone-depth="2" sync-tags="false" />
</manifest>
"""
)
by_name = {p.name: p for p in manifest.projects}
assert manifest.default.sync_tags is None
assert by_name["plain"].sync_tags is True
assert by_name["explicit-on"].sync_tags is True
assert by_name["explicit-off"].sync_tags is False
assert by_name["depth-one"].sync_tags is False
assert by_name["depth-five"].sync_tags is False
assert by_name["depth-opt-in"].sync_tags is True
assert by_name["depth-opt-out"].sync_tags is False
serialized = sort_attributes(manifest.ToXml().toxml())
assert (
serialized == '<?xml version="1.0" ?><manifest>'
'<remote fetch="http://localhost" name="default-remote"/>'
'<default remote="default-remote" revision="refs/heads/main"/>'
'<project clone-depth="5" name="depth-five"/>'
'<project clone-depth="1" name="depth-one"/>'
'<project clone-depth="2" name="depth-opt-in" sync-tags="true"/>'
'<project clone-depth="2" name="depth-opt-out" sync-tags="false"/>'
'<project name="explicit-off" sync-tags="false"/>'
'<project name="explicit-on" sync-tags="true"/>'
'<project name="plain"/>'
"</manifest>"
)
reparsed = repo_client.get_xml_manifest(serialized)
assert {p.name: p.sync_tags for p in reparsed.projects} == {
p.name: p.sync_tags for p in manifest.projects
}
# <default sync-tags="false"> propagates to all projects unless
# overridden with sync-tags="true", and round-trips through ToXml().
default_off = repo_client.get_xml_manifest(
"""
<manifest>
<remote name="default-remote" fetch="http://localhost" />
<default remote="default-remote" revision="refs/heads/main"
sync-tags="false" />
<project name="plain" />
<project name="opt-in" sync-tags="true" />
<project name="depth-one" clone-depth="1" />
</manifest>
"""
)
assert default_off.default.sync_tags is False
default_off_map = {p.name: p.sync_tags for p in default_off.projects}
assert default_off_map == {
"plain": False,
"opt-in": True,
"depth-one": False,
}
default_off_xml = sort_attributes(default_off.ToXml().toxml())
assert (
default_off_xml == '<?xml version="1.0" ?><manifest>'
'<remote fetch="http://localhost" name="default-remote"/>'
'<default remote="default-remote" revision="refs/heads/main" '
'sync-tags="false"/>'
'<project clone-depth="1" name="depth-one"/>'
'<project name="opt-in" sync-tags="true"/>'
'<project name="plain"/>'
"</manifest>"
)
reparsed_default_off = repo_client.get_xml_manifest(default_off_xml)
assert {
p.name: p.sync_tags for p in reparsed_default_off.projects
} == default_off_map
# <default sync-tags="true"> overrides the clone-depth / --depth
# heuristic unless a project explicitly sets sync-tags="false", and
# round-trips through ToXml().
default_on = repo_client.get_xml_manifest(
"""
<manifest>
<remote name="default-remote" fetch="http://localhost" />
<default remote="default-remote" revision="refs/heads/main"
sync-tags="true" />
<project name="plain" />
<project name="depth-one" clone-depth="1" />
<project name="depth-opt-out" clone-depth="1" sync-tags="false" />
</manifest>
"""
)
default_on.manifestProject.config.SetString("repo.depth", "3")
default_on.Unload()
assert default_on.default.sync_tags is True
default_on_map = {p.name: p.sync_tags for p in default_on.projects}
assert default_on_map == {
"plain": True,
"depth-one": True,
"depth-opt-out": False,
}
default_on_xml = sort_attributes(default_on.ToXml().toxml())
assert (
default_on_xml == '<?xml version="1.0" ?><manifest>'
'<remote fetch="http://localhost" name="default-remote"/>'
'<default remote="default-remote" revision="refs/heads/main" '
'sync-tags="true"/>'
'<project clone-depth="1" name="depth-one"/>'
'<project clone-depth="1" name="depth-opt-out" sync-tags="false"/>'
'<project name="plain"/>'
"</manifest>"
)
reparsed_default_on = repo_client.get_xml_manifest(default_on_xml)
assert {
p.name: p.sync_tags for p in reparsed_default_on.projects
} == default_on_map
# `repo init --depth` also defaults non-mirror project sync-tags to
# false, while preserving mirror tag syncing.
depth_manifest = repo_client.get_xml_manifest(
"""
<manifest>
<remote name="default-remote" fetch="http://localhost" />
<default remote="default-remote" revision="refs/heads/main" />
<project name="plain" />
<project name="opt-in" sync-tags="true" />
</manifest>
"""
)
depth_manifest.manifestProject.config.SetString("repo.depth", "3")
depth_manifest.Unload()
assert {p.name: p.sync_tags for p in depth_manifest.projects} == {
"plain": False,
"opt-in": True,
}
depth_manifest.repoProject.config.SetString(
"remote.origin.url", "http://localhost/repo"
)
depth_manifest.manifestProject.config.SetString(
"remote.origin.url", "http://localhost/manifests"
)
depth_manifest.manifestProject.config.SetBoolean("repo.mirror", True)
depth_manifest.Unload()
by_mirror = {p.name: p.sync_tags for p in depth_manifest.projects}
assert by_mirror["plain"] is True
assert by_mirror["opt-in"] is True
def test_trailing_slash(self, repo_client: RepoClient) -> None: def test_trailing_slash(self, repo_client: RepoClient) -> None:
"""Check handling of trailing slashes in attributes.""" """Check handling of trailing slashes in attributes."""
+326
View File
@@ -1978,6 +1978,12 @@ class ManifestPropertiesFetchedCorrectly(unittest.TestCase):
fakeproj.config.SetBoolean("repo.smartsync", False) fakeproj.config.SetBoolean("repo.smartsync", False)
self.assertFalse(fakeproj.smart_sync) self.assertFalse(fakeproj.smart_sync)
self.assertIsNone(fakeproj.smart_sync_default)
fakeproj.config.SetString("repo.smartsyncdefault", "Explicit")
self.assertEqual(fakeproj.smart_sync_default, "explicit")
fakeproj.config.SetString("repo.smartsyncdefault", None)
self.assertIsNone(fakeproj.smart_sync_default)
fakeproj.config.SetBoolean("repo.partialclone", False) fakeproj.config.SetBoolean("repo.partialclone", False)
self.assertFalse(fakeproj.partial_clone) self.assertFalse(fakeproj.partial_clone)
@@ -1987,6 +1993,29 @@ class ManifestPropertiesFetchedCorrectly(unittest.TestCase):
fakeproj.config.SetString("repo.depth", "invalid_depth") fakeproj.config.SetString("repo.depth", "invalid_depth")
self.assertEqual(fakeproj.depth, None) self.assertEqual(fakeproj.depth, None)
self.assertIsNone(fakeproj.manifest_depth)
fakeproj._ConfigureManifestDepth(2)
self.assertEqual(fakeproj.manifest_depth, 2)
self.assertEqual(fakeproj._GetCloneDepth(), 2)
# None leaves the persisted setting untouched.
fakeproj._ConfigureManifestDepth(None)
self.assertEqual(fakeproj.manifest_depth, 2)
# 0 explicitly configures a full manifest clone even if repo.depth
# is set.
fakeproj._ConfigureDepth(5)
fakeproj._ConfigureManifestDepth(0)
self.assertEqual(fakeproj.manifest_depth, 0)
self.assertIsNone(fakeproj._GetCloneDepth())
# Negative values clear repo.manifestdepth so repo.depth applies.
fakeproj._ConfigureManifestDepth(-1)
self.assertIsNone(fakeproj.manifest_depth)
self.assertEqual(fakeproj._GetCloneDepth(), 5)
fakeproj._ConfigureDepth(-1)
self.assertIsNone(fakeproj._GetCloneDepth())
fakeproj.config.SetString("repo.clonefilter", "blob:limit=10M") fakeproj.config.SetString("repo.clonefilter", "blob:limit=10M")
self.assertEqual(fakeproj.clone_filter, "blob:limit=10M") self.assertEqual(fakeproj.clone_filter, "blob:limit=10M")
@@ -3295,6 +3324,8 @@ class SyncOptimizationTests(unittest.TestCase):
os.path.join(tempdir, ".git"), os.path.join(tempdir, ".git"),
tempdir, tempdir,
) )
manifest.manifestProject = proj
_ = proj.depth
proj.revisionExpr = sha proj.revisionExpr = sha
proj.upstream = None proj.upstream = None
proj._CheckForImmutableRevision = mock.MagicMock(return_value=False) proj._CheckForImmutableRevision = mock.MagicMock(return_value=False)
@@ -4599,6 +4630,93 @@ class ReprojectCmdTests(unittest.TestCase):
proj._Reproject.assert_not_called() proj._Reproject.assert_not_called()
proj.work_git.UpdateRef.assert_not_called() proj.work_git.UpdateRef.assert_not_called()
def test_sync_local_half_shallow_advance_skips_rebase_and_discard(
self,
) -> None:
"""Shallow tracking branches reset cleanly without rebasing old base."""
with utils_for_test.TempGitTree() as tempdir:
proj = self._get_synced_project(
tempdir,
head=self.HEAD_ID,
branch="default",
upstream_gain=[self.REVID],
)
proj.manifest.manifestProject.reproject_cmd = None
proj.GetBranch = mock.MagicMock(
return_value=self._tracking_branch(name="default", merge="main")
)
proj.work_git.merge_base.side_effect = error.GitError("shallow")
proj.WasPublished = mock.MagicMock(return_value=None)
proj._HasShallow = mock.MagicMock(return_value=True)
proj._ReadShallowCommits = mock.MagicMock(
return_value={self.HEAD_ID, self.REVID}
)
proj._pre_fetch_revid = self.HEAD_ID
def _shallow_revlist(*args: Any, **kwargs: Any) -> List[str]:
if kwargs.get("format"):
if project.not_rev(self.HEAD_ID) in args:
return []
return [f"{self.HEAD_ID} me@example.com"]
if "--count" in args:
return ["1"]
return [self.REVID]
proj._revlist = mock.MagicMock(side_effect=_shallow_revlist)
syncbuf = project.SyncBuffer(proj.config)
syncbuf.out = io.StringIO()
proj.Sync_LocalHalf(syncbuf)
self.assertTrue(syncbuf.Finish())
self.assertNotIn("discarding", syncbuf.out.getvalue())
proj._Rebase.assert_not_called()
proj._FastForward.assert_not_called()
proj._ResetHard.assert_called_once_with(self.REVID)
def test_sync_local_half_shallow_rebases_only_local_commits(self) -> None:
"""Shallow tracking branches still rebase genuine local commits."""
local_id = "9999999999999999999999999999999999999999"
with utils_for_test.TempGitTree() as tempdir:
proj = self._get_synced_project(
tempdir,
head=local_id,
branch="topic",
upstream_gain=[self.REVID],
)
proj.manifest.manifestProject.reproject_cmd = None
proj.GetBranch = mock.MagicMock(
return_value=self._tracking_branch(name="topic", merge="main")
)
proj.work_git.merge_base.side_effect = error.GitError("shallow")
proj.WasPublished = mock.MagicMock(return_value=None)
proj._HasShallow = mock.MagicMock(return_value=True)
proj._ReadShallowCommits = mock.MagicMock(
return_value={self.HEAD_ID, self.REVID}
)
proj._pre_fetch_revid = self.HEAD_ID
def _shallow_revlist(*args: Any, **kwargs: Any) -> List[str]:
if kwargs.get("format"):
if project.not_rev(self.HEAD_ID) in args:
return [f"{local_id} me@example.com"]
return [
f"{local_id} me@example.com",
f"{self.HEAD_ID} me@example.com",
]
if "--count" in args:
return ["1"]
return [self.REVID]
proj._revlist = mock.MagicMock(side_effect=_shallow_revlist)
syncbuf = project.SyncBuffer(proj.config)
proj.Sync_LocalHalf(syncbuf)
self.assertTrue(syncbuf.Finish())
proj._Rebase.assert_called_once_with(
upstream=f"{local_id}^1", onto=self.REVID
)
proj._ResetHard.assert_not_called()
def test_sync_local_half_rejects_a_nested_project(self) -> None: def test_sync_local_half_rejects_a_nested_project(self) -> None:
"""Test a submodule or nested project fails before any checkout.""" """Test a submodule or nested project fails before any checkout."""
with utils_for_test.TempGitTree() as tempdir: with utils_for_test.TempGitTree() as tempdir:
@@ -6201,3 +6319,211 @@ def test_manifest_project_get_merge_branch_checkout(
assert mp.GetMergeBranch() == expected_all assert mp.GetMergeBranch() == expected_all
assert mp.GetMergeBranch(heads_only=True) == expected_heads_only assert mp.GetMergeBranch(heads_only=True) == expected_heads_only
assert manifest.branch == expected_all assert manifest.branch == expected_all
class CloneDepthPartialCloneTagsTests(unittest.TestCase):
"""Check tag syncing and depth filters on depth-configured projects."""
def _get_project(
self,
tempdir: str,
clone_depth: Optional[int] = 1,
manifest_depth: Optional[int] = None,
sync_tags: Optional[bool] = None,
) -> project.Project:
proj = _create_mock_project(
tempdir,
revisionExpr="refs/heads/main",
depth=manifest_depth,
)
proj.clone_depth = clone_depth
if sync_tags is None:
sync_tags = not bool(clone_depth or manifest_depth)
proj.sync_tags = sync_tags
proj.manifest.globalConfig.GetString.return_value = None
proj._InitGitDir = mock.MagicMock()
proj._InitRemote = mock.MagicMock()
proj._InitMRef = mock.MagicMock()
proj._ApplyCloneBundle = mock.MagicMock(return_value=False)
proj._RemoteFetch = mock.MagicMock(return_value=True)
return proj
def _sync_kwargs(
self, proj: project.Project, **kwargs: object
) -> Dict[str, Any]:
proj._RemoteFetch.reset_mock()
res = proj.Sync_NetworkHalf(clone_bundle=False, **kwargs)
self.assertTrue(res.success)
proj._RemoteFetch.assert_called_once()
return proj._RemoteFetch.call_args.kwargs
def test_clone_filter_for_depth_keeps_filter_and_no_tags_across_syncs(
self,
) -> None:
"""clone_filter_for_depth keeps filter and --no-tags across syncs."""
with utils_for_test.TempGitTree() as tempdir:
proj = self._get_project(tempdir, clone_depth=1)
for is_new in (True, False):
fetch_kwargs = self._sync_kwargs(
proj,
is_new=is_new,
clone_filter_for_depth="blob:none",
)
self.assertIsNone(fetch_kwargs["depth"])
self.assertEqual("blob:none", fetch_kwargs["clone_filter"])
self.assertFalse(fetch_kwargs["tags"])
def test_explicit_sync_tags_and_cli_tags_override_clone_depth_default(
self,
) -> None:
"""Explicit sync-tags="true" or --tags fetches tags."""
with utils_for_test.TempGitTree() as tempdir:
opt_in_proj = self._get_project(
tempdir, clone_depth=2, sync_tags=True
)
fetch_kwargs = self._sync_kwargs(
opt_in_proj,
is_new=False,
clone_filter_for_depth="blob:none",
)
self.assertTrue(fetch_kwargs["tags"])
cli_proj = self._get_project(tempdir, clone_depth=2)
cli_kwargs = self._sync_kwargs(
cli_proj,
is_new=True,
tags=True,
clone_filter_for_depth="blob:none",
)
self.assertTrue(cli_kwargs["tags"])
def test_partial_clone_without_depth_keeps_tags(self) -> None:
"""Regular partial-clone projects without depth still get tags."""
with utils_for_test.TempGitTree() as tempdir:
proj = self._get_project(tempdir, clone_depth=None)
fetch_kwargs = self._sync_kwargs(
proj,
is_new=True,
clone_filter="blob:none",
)
self.assertTrue(fetch_kwargs["tags"])
def test_derived_shallow_submodule_defaults_sync_tags_false(self) -> None:
"""Derived submodules with shallow=true default sync_tags to False."""
with utils_for_test.TempGitTree() as tempdir:
parent = _create_mock_project(tempdir, revisionExpr="main")
parent.sync_tags = True
parent.manifest.IsMirror = False
parent.manifest.paths = {}
parent.manifest.GetSubprojectName.side_effect = [
"proj/sub1",
"proj/sub2",
]
parent.manifest.GetSubprojectPaths.side_effect = [
(
"proj/sub1",
f"{tempdir}/sub1",
f"{tempdir}/s1.git",
f"{tempdir}/s1.git",
),
(
"proj/sub2",
f"{tempdir}/sub2",
f"{tempdir}/s2.git",
f"{tempdir}/s2.git",
),
]
with mock.patch.object(
project.Project,
"_GetSubmodules",
return_value=[
("a" * 40, "sub1", "https://example.com/s1", "true"),
("b" * 40, "sub2", "https://example.com/s2", ""),
],
):
subs = parent.GetDerivedSubprojects()
self.assertEqual(2, len(subs))
self.assertEqual(1, subs[0].clone_depth)
self.assertFalse(subs[0].sync_tags)
self.assertIsNone(subs[1].clone_depth)
self.assertTrue(subs[1].sync_tags)
parent.manifest.default.sync_tags = True
parent.manifest.GetSubprojectName.side_effect = ["proj/sub1"]
parent.manifest.GetSubprojectPaths.side_effect = [
(
"proj/sub1",
f"{tempdir}/sub1",
f"{tempdir}/s1.git",
f"{tempdir}/s1.git",
),
]
with mock.patch.object(
project.Project,
"_GetSubmodules",
return_value=[
("a" * 40, "sub1", "https://example.com/s1", "true"),
],
):
subs_default_on = parent.GetDerivedSubprojects()
self.assertEqual(1, len(subs_default_on))
self.assertTrue(subs_default_on[0].sync_tags)
def test_meta_projects_depth_and_tags(self) -> None:
"""RepoProject never uses depth; ManifestProject skips tags on depth."""
with utils_for_test.TempGitTree() as tempdir:
manifest = mock.MagicMock()
manifest.IsMirror = False
manifest.CloneBundle = False
manifest.manifestProject.depth = 1
manifest.globalConfig.GetString.return_value = None
repo_proj = project.RepoProject(
manifest,
"repo",
os.path.join(tempdir, ".git"),
tempdir,
)
repo_proj.relpath = "custom/repo"
repo_proj._InitGitDir = mock.MagicMock()
repo_proj._InitRemote = mock.MagicMock()
repo_proj._InitMRef = mock.MagicMock()
repo_proj._RemoteFetch = mock.MagicMock(return_value=True)
repo_kwargs = self._sync_kwargs(
repo_proj,
is_new=True,
clone_filter_for_depth="blob:none",
)
self.assertIsNone(repo_kwargs["depth"])
self.assertIsNone(repo_kwargs["clone_filter"])
self.assertTrue(repo_kwargs["tags"])
manifest_proj = project.ManifestProject(
manifest,
"manifests",
os.path.join(tempdir, ".git"),
tempdir,
)
manifest_proj._ConfigureDepth(1)
manifest_proj._InitGitDir = mock.MagicMock()
manifest_proj._InitRemote = mock.MagicMock()
manifest_proj._InitMRef = mock.MagicMock()
manifest_proj._RemoteFetch = mock.MagicMock(return_value=True)
mp_kwargs = self._sync_kwargs(
manifest_proj,
is_new=True,
clone_filter_for_depth="blob:none",
)
self.assertIsNone(mp_kwargs["depth"])
self.assertEqual("blob:none", mp_kwargs["clone_filter"])
self.assertFalse(mp_kwargs["tags"])
mp_opt_in = self._sync_kwargs(
manifest_proj,
is_new=True,
tags=True,
clone_filter_for_depth="blob:none",
)
self.assertTrue(mp_opt_in["tags"])
+19
View File
@@ -31,6 +31,8 @@ from subcmds import init
["--head"], ["--head"],
["--smart-sync-branch=git_main-warmup"], ["--smart-sync-branch=git_main-warmup"],
["--smart-sync-branch="], ["--smart-sync-branch="],
["--manifest-depth=0"],
["--manifest-depth=1"],
), ),
) )
def test_cli_parser_good(argv: List[str]) -> None: def test_cli_parser_good(argv: List[str]) -> None:
@@ -58,6 +60,23 @@ def test_cli_smart_sync_branch_value(
assert opts.smart_sync_branch == expected assert opts.smart_sync_branch == expected
@pytest.mark.parametrize(
"argv,expected",
(
([], None),
(["--manifest-depth=0"], 0),
(["--manifest-depth=2"], 2),
),
)
def test_manifest_depth_option(
argv: List[str], expected: Optional[int]
) -> None:
"""Check --manifest-depth defaults to None so re-init preserves config."""
cmd = init.Init()
opts, _ = cmd.OptionParser.parse_args(argv)
assert opts.manifest_depth == expected
@pytest.mark.parametrize( @pytest.mark.parametrize(
"argv", "argv",
( (
+216
View File
@@ -652,6 +652,124 @@ def test_user_config_smart_sync(
assert implicit == expected_implicit assert implicit == expected_implicit
@pytest.mark.parametrize(
"argv, config_smart_sync, user_pref, sync_smartsync_manifest, "
"manifest_server, expected_smart_sync, expected_implicit",
[
# Fallback: enabled iff <manifest-server> is set, always explicit.
([], None, None, None, "http://localhost/ms", True, False),
([], None, None, None, None, False, False),
([], None, None, None, "", False, False),
# Manifest sync-smartsync overrides repo.smartsyncdefault; true is
# upgraded to explicit, false opts out even with <manifest-server>.
([], None, None, False, "http://localhost/ms", False, False),
([], None, None, True, "http://localhost/ms", True, False),
([], None, None, True, None, True, False),
# Per-user sync.smartsync overrides manifest and repo.smartsyncdefault.
([], None, False, None, "http://localhost/ms", False, False),
([], None, False, True, "http://localhost/ms", False, False),
([], None, True, False, None, True, False),
# repo.smartsync overrides user/manifest; true is upgraded to explicit.
([], True, False, False, None, True, False),
([], False, True, True, "http://localhost/ms", False, False),
# CLI flags and target-selecting flags override everything.
(
["--no-smart-sync"],
True,
True,
True,
"http://localhost/ms",
False,
False,
),
(["--head"], None, None, None, "http://localhost/ms", False, False),
(["-s"], False, False, False, None, True, False),
(
["-t", "tag123"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(
["-m", "other.xml"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(
["--superproject-revision=abc"],
None,
None,
None,
"http://localhost/ms",
False,
False,
),
(["-l"], None, None, None, "http://localhost/ms", False, False),
(["--nmu"], None, None, None, "http://localhost/ms", True, False),
],
)
def test_checkout_smart_sync_default_explicit(
argv: List[str],
config_smart_sync: Optional[bool],
user_pref: Optional[bool],
sync_smartsync_manifest: Optional[bool],
manifest_server: Optional[str],
expected_smart_sync: bool,
expected_implicit: bool,
) -> None:
"""Tests repo.smartsyncdefault=explicit precedence and explicitness."""
manifest = mock.MagicMock()
manifest.default.sync_smartsync = sync_smartsync_manifest
manifest.manifest_server = manifest_server
manifest.manifestProject.smart_sync = config_smart_sync
manifest.manifestProject.smart_sync_default = "explicit"
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = user_pref
cmd = sync.Sync(manifest=manifest)
opts, args = cmd.OptionParser.parse_args(argv)
cmd.ValidateOptions(opts, args)
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
implicit = cmd._ResolveSmartSyncOption(opts, manifest)
assert opts.smart_sync == expected_smart_sync
assert implicit == expected_implicit
@pytest.mark.parametrize("bad_value", ["bogus", "implicit", "off"])
def test_checkout_smart_sync_default_unknown_warns(bad_value: str) -> None:
"""Unknown repo.smartsyncdefault values log a warning and are ignored."""
manifest = mock.MagicMock()
manifest.default.sync_smartsync = None
manifest.manifest_server = "http://localhost/manifestserver"
manifest.manifestProject.smart_sync = None
manifest.manifestProject.smart_sync_default = bad_value
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = None
cmd = sync.Sync(manifest=manifest)
opts, args = cmd.OptionParser.parse_args([])
cmd.ValidateOptions(opts, args)
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
with mock.patch.object(sync.logger, "warning") as mock_warn:
implicit = cmd._ResolveSmartSyncOption(opts, manifest)
mock_warn.assert_called_once()
assert opts.smart_sync is False
assert implicit is False
@pytest.mark.parametrize( @pytest.mark.parametrize(
"value, expected_smart_sync", "value, expected_smart_sync",
[("true", True), ("false", False), ("yes", True), ("no", False)], [("true", True), ("false", False), ("yes", True), ("no", False)],
@@ -1028,6 +1146,7 @@ class FakeProject:
self.UseReprojectCmd = False self.UseReprojectCmd = False
self.sync_s = False self.sync_s = False
self.Exists = False self.Exists = False
self._pre_fetch_revid: Optional[str] = None
self.manifest = mock.MagicMock() self.manifest = mock.MagicMock()
self.manifest.GetProjectsWithName.return_value = [self] self.manifest.GetProjectsWithName.return_value = [self]
self.config = mock.MagicMock() self.config = mock.MagicMock()
@@ -1311,6 +1430,60 @@ class FetchParentFirst(unittest.TestCase):
) )
class FetchMain(unittest.TestCase):
def test_preserves_pre_fetch_revid_across_manifest_reload(self) -> None:
cmd = sync.Sync()
cmd._fetch_times = mock.Mock()
cmd._local_sync_state = mock.Mock()
p_a = FakeProject("a")
p_b = FakeProject("b")
reloads = 0
def fake_get_projects(*_args: object, **_kwargs: object) -> List[Any]:
nonlocal reloads
reloads += 1
# Return fresh FakeProject instances on each manifest reload, adding
# a newly discovered project on the first reload.
return [FakeProject("a"), FakeProject("b"), FakeProject("sub")]
revids_by_path = {"a": "1" * 40, "sub": "2" * 40}
def fake_fetch_parent_first(
projects: List[FakeProject], *_args: object
) -> sync._FetchResult:
for proj in projects:
proj._pre_fetch_revid = revids_by_path.get(proj.relpath)
return sync._FetchResult(True, {p.gitdir for p in projects})
opt = mock.Mock(
network_only=False,
groups="",
recurse_submodules=False,
this_manifest_only=False,
)
err_event = mock.Mock()
err_event.is_set.return_value = False
with mock.patch.object(cmd, "_ReloadManifest"), mock.patch.object(
cmd, "GetProjects", side_effect=fake_get_projects
):
with mock.patch.object(
cmd, "_FetchParentFirst", side_effect=fake_fetch_parent_first
):
res = cmd._FetchMain(
opt, [], [p_a, p_b], err_event, None, mock.Mock(), []
)
self.assertEqual(reloads, 2)
by_path = {p.relpath: p._pre_fetch_revid for p in res.all_projects}
self.assertEqual(
by_path,
{"a": "1" * 40, "b": None, "sub": "2" * 40},
)
class WithoutProjects(unittest.TestCase): class WithoutProjects(unittest.TestCase):
def test_drops_the_unwanted_projects(self) -> None: def test_drops_the_unwanted_projects(self) -> None:
p_a = FakeProject("a") p_a = FakeProject("a")
@@ -1998,6 +2171,49 @@ class SyncCommand(unittest.TestCase):
self.cmd.Execute(self.opt, []) self.cmd.Execute(self.opt, [])
mock_setup.assert_called_once() mock_setup.assert_called_once()
def test_checkout_smart_sync_default_explicit_error(self) -> None:
"""Ensure repo.smartsyncdefault=explicit fails hard with a hint."""
self.manifest.default.sync_smartsync = None
self.manifest.manifest_server = "http://localhost/manifestserver"
self.manifest.manifestProject.smart_sync_default = "explicit"
self.opt.smart_sync = None
self.opt.mp_update = False
user_cfg = mock.MagicMock()
user_cfg.GetBoolean.return_value = None
with mock.patch.object(
git_config.RepoConfig, "ForUser", return_value=user_cfg
):
with mock.patch.object(
self.cmd,
"_SmartSyncSetup",
side_effect=sync.SmartSyncError("target not found"),
) as mock_setup:
with mock.patch.object(sync.logger, "error") as mock_error:
with self.assertRaises(sync.SmartSyncError):
self.cmd.Execute(self.opt, [])
mock_setup.assert_called_once_with(
self.opt,
mock.ANY,
self.manifest,
best_effort=False,
)
mock_error.assert_called_once()
self.assertIn("--no-smart-sync", mock_error.call_args[0][0])
def test_cli_smart_sync_error_no_default_hint(self) -> None:
"""Ensure explicit CLI -s failures do not print the default hint."""
self.opt.smart_sync = True
self.opt.mp_update = False
with mock.patch.object(
self.cmd,
"_SmartSyncSetup",
side_effect=sync.SmartSyncError("target not found"),
):
with mock.patch.object(sync.logger, "error") as mock_error:
with self.assertRaises(sync.SmartSyncError):
self.cmd.Execute(self.opt, [])
mock_error.assert_not_called()
def test_implicit_smart_sync_unparsable_manifest(self) -> None: def test_implicit_smart_sync_unparsable_manifest(self) -> None:
"""Ensure an unparsable smart sync manifest falls back to ToT.""" """Ensure an unparsable smart sync manifest falls back to ToT."""
self.manifest.default.sync_smartsync = True self.manifest.default.sync_smartsync = True