diff --git a/docs/internal-fs-layout.md b/docs/internal-fs-layout.md index 2db833f76..9928d0926 100644 --- a/docs/internal-fs-layout.md +++ b/docs/internal-fs-layout.md @@ -181,6 +181,7 @@ User controlled settings are initialized when running `repo init`. | 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.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 `` is set (below CLI, `repo.smartsync`, `sync.smartsync`, and `sync-smartsync`) and treats default Smart Syncs as explicit | | repo.\.smartsyncbranch | `--smart-sync-branch` | Server branch to query when [Smart Sync](./smart-sync.md)ing `` | | repo.submodules | `--submodules` | Sync git submodules | | repo.superproject | `--use-superproject` | Sync [superproject] | diff --git a/docs/manifest-format.md b/docs/manifest-format.md index aa4a5107d..75f039436 100644 --- a/docs/manifest-format.md +++ b/docs/manifest-format.md @@ -242,7 +242,9 @@ 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 `` is defined). ### Element manifest-server diff --git a/docs/smart-sync.md b/docs/smart-sync.md index 279595cdf..210d6d152 100644 --- a/docs/smart-sync.md +++ b/docs/smart-sync.md @@ -245,6 +245,11 @@ explicit target or manifest source (such as `-t`/`--smart-tag`, `-m`/`--manifest-name` or `--superproject-revision`) will also disable the 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 +`` available for explicit `-s`/`--smart-sync` and +`-t`/`--smart-tag` invocations. + Users can override this manifest default on their workstation with the `sync.smartsync` user setting; see [Per-user default](#Per_user-default-sync_smartsync) below. diff --git a/man/repo-manifest.1 b/man/repo-manifest.1 index 5a7e45aa3..d83c82934 100644 --- a/man/repo-manifest.1 +++ b/man/repo-manifest.1 @@ -346,7 +346,9 @@ set. Project elements lacking a `sync\-tags` attribute of their own will use thi value if specified; otherwise projects default to false when depth is set on a non\-mirror checkout, and true otherwise. .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 `` is defined). .PP Element manifest\-server .PP diff --git a/manifest_xml.py b/manifest_xml.py index 222be5253..39aed64b5 100644 --- a/manifest_xml.py +++ b/manifest_xml.py @@ -159,7 +159,7 @@ class _Default: sync_c = False sync_s = False sync_tags = None - sync_smartsync = False + sync_smartsync = None def __eq__(self, other): if not isinstance(other, _Default): @@ -658,9 +658,11 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md if d.sync_tags is not None: have_default = True 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 - e.setAttribute("sync-smartsync", "true") + e.setAttribute( + "sync-smartsync", "true" if d.sync_smartsync else "false" + ) if have_default: root.appendChild(e) root.appendChild(doc.createTextNode("")) @@ -1814,7 +1816,7 @@ https://gerrit.googlesource.com/git-repo/+/HEAD/docs/manifest-format.md d.sync_c = XmlBool(node, "sync-c", False) d.sync_s = XmlBool(node, "sync-s", False) d.sync_tags = XmlBool(node, "sync-tags") - d.sync_smartsync = XmlBool(node, "sync-smartsync", False) + d.sync_smartsync = XmlBool(node, "sync-smartsync") return d def _ParseNotice(self, node): diff --git a/project.py b/project.py index bbe449daf..8f4f3244a 100644 --- a/project.py +++ b/project.py @@ -6176,6 +6176,14 @@ class ManifestProject(MetaProject): """Whether we use smart sync by default.""" 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 def _SmartSyncBranchKey(branch: str) -> str: """Return the git config key for a branch's smart sync branch.""" diff --git a/subcmds/sync.py b/subcmds/sync.py index 660dbe100..f53648da2 100644 --- a/subcmds/sync.py +++ b/subcmds/sync.py @@ -2713,19 +2713,40 @@ later is required to fix a server side protocol bug. ) -> bool: """Resolve opt.smart_sync from CLI flags, config, and manifest. - Precedence: CLI flags > per-checkout settings > per-user settings > - per-manifest settings. - See docs/repoconfig.md and docs/smart-sync.md for details. + Precedence: CLI flags > repo.smartsync > sync.smartsync > + > repo.smartsyncdefault. + See docs/repoconfig.md, docs/smart-sync.md, and + docs/internal-fs-layout.md for details. Returns: True if smart_sync was enabled implicitly by checkout or manifest 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) if not isinstance(checkout_pref, bool): 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") + manifest_pref = getattr(manifest.default, "sync_smartsync", None) + if not isinstance(manifest_pref, bool): + manifest_pref = None default_allowed = ( opt.smart_sync is None and not opt.smart_tag @@ -2733,25 +2754,30 @@ later is required to fix a server side protocol bug. and not opt.superproject_revision 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 checkout_pref is not None: - opt.smart_sync = implicit - elif user_pref is False: + if not default_allowed: opt.smart_sync = False - elif user_pref is True: - opt.smart_sync = default_allowed + implicit = False + 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: - opt.smart_sync = implicit + opt.smart_sync = False + implicit = False + else: + implicit = False if ( opt.manifest_server_username or opt.manifest_server_password @@ -2789,6 +2815,7 @@ later is required to fix a server side protocol bug. 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) if opt.smart_sync or opt.smart_tag: @@ -2801,6 +2828,12 @@ later is required to fix a server side protocol bug. ) except (SmartSyncError, error.ManifestParseError) as e: 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 # The user did not ask for a smart sync, so failing to get a # usable manifest from the server should not fail the sync. diff --git a/tests/e2e/test_init_sync.py b/tests/e2e/test_init_sync.py index 6c6a57a2d..2973cc987 100644 --- a/tests/e2e/test_init_sync.py +++ b/tests/e2e/test_init_sync.py @@ -572,3 +572,136 @@ def test_smart_sync_branch(host: GitHost, client: RepoClient) -> None: ) assert res.returncode != 0 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'', + fetch=host.url, + ), + } + + with _manifest_server(handle_v2) as server_url: + manifest = host.create_manifest( + manifest_xml( + f'', + '', + ) + ) + manifest.commit( + { + "default.xml": manifest_xml( + f'', + '', + default=( + 'remote="origin" revision="main" ' + 'sync-smartsync="false"' + ), + ) + }, + branch="opt-out", + ) + manifest.commit( + { + "default.xml": manifest_xml( + f'', + '', + default=( + 'remote="origin" revision="main" ' + 'sync-smartsync="true"' + ), + ) + }, + branch="opt-in", + ) + manifest.commit( + { + "default.xml": manifest_xml( + '' + ) + }, + branch="no-server", + ) + + client.init(host.manifest_url) + client.git( + ".repo/manifests", "config", "repo.smartsyncdefault", "explicit" + ) + + # Enables explicit Smart Sync when 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 + + # 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 + + # 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 , 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 diff --git a/tests/test_manifest_xml.py b/tests/test_manifest_xml.py index 58202b265..65240342e 100644 --- a/tests/test_manifest_xml.py +++ b/tests/test_manifest_xml.py @@ -427,7 +427,8 @@ class TestXmlManifest: manifest = repo_client.get_xml_manifest( "" ) - assert manifest.default.sync_smartsync is False + assert manifest.default.sync_smartsync is None + assert manifest.ToXml().toxml() == '' manifest = repo_client.get_xml_manifest( '' @@ -442,7 +443,10 @@ class TestXmlManifest: '' ) assert manifest.default.sync_smartsync is False - assert manifest.ToXml().toxml() == '' + assert ( + manifest.ToXml().toxml() == '' + '' + ) def test_clear_override(self, repo_client: RepoClient) -> None: """Check ClearOverride reverts to the default manifest.""" diff --git a/tests/test_project.py b/tests/test_project.py index edcf04d07..bab4c8d30 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -1978,6 +1978,12 @@ class ManifestPropertiesFetchedCorrectly(unittest.TestCase): fakeproj.config.SetBoolean("repo.smartsync", False) 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) self.assertFalse(fakeproj.partial_clone) diff --git a/tests/test_subcmds_sync.py b/tests/test_subcmds_sync.py index fef29fe1e..7ec6218cb 100644 --- a/tests/test_subcmds_sync.py +++ b/tests/test_subcmds_sync.py @@ -652,6 +652,124 @@ def test_user_config_smart_sync( 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 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 . + ([], 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( "value, expected_smart_sync", [("true", True), ("false", False), ("yes", True), ("no", False)], @@ -2053,6 +2171,49 @@ class SyncCommand(unittest.TestCase): self.cmd.Execute(self.opt, []) 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: """Ensure an unparsable smart sync manifest falls back to ToT.""" self.manifest.default.sync_smartsync = True