tbb-commits
Threads by month
- ----- 2026 -----
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- 1 participants
- 21411 discussions
[Git][tpo/applications/mullvad-browser][mullvad-browser-155.0a1-17.0-1] 62 commits: fixup! BB 44711: Hide unwanted setting controls in Base Browser.
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch mullvad-browser-155.0a1-17.0-1 at The Tor Project / Applications / Mullvad Browser
Commits:
45b107a6 by Henry Wilkes at 2026-11-05T10:04:54+01:00
fixup! BB 44711: Hide unwanted setting controls in Base Browser.
BB 44831: Hide the search suggestions private browsing banner.
- - - - -
2dec5297 by Pier Angelo Vendrame at 2026-11-05T10:05:04+01:00
Bug 2059465 - Disable screen orientation locking on Windows with RFP on. r=timhuang
Differential Revision: https://phabricator.services.mozilla.com/D315311
- - - - -
87c96105 by Henry Wilkes at 2026-11-05T10:05:11+01:00
BB 45211: Settings UI for protections from third party applications.
- - - - -
fa16c63e by Henry Wilkes at 2026-11-05T10:05:25+01:00
fixup! Base Browser strings
BB 45211: Add strings for protections from third party applications.
- - - - -
1bbbdb27 by Pier Angelo Vendrame at 2026-11-05T10:05:32+01:00
fixup! BB 42583: Modify moz-support-link for Base Browser.
MB 566: Fix manual links.
- - - - -
1f5c085d by Henry Wilkes at 2026-11-05T10:05:42+01:00
fixup! BB 43902: Modify the new sidebar for Base Browser.
BB 45169: Allow the history item in the sidebar, but hide it by default.
- - - - -
5c5a730f by Henry Wilkes at 2026-11-05T10:05:54+01:00
fixup! BB 44711: Hide unwanted setting controls in Base Browser.
BB 45209: Replace "Account and sync" with "Profiles".
- - - - -
e0c1f0d3 by Henry Wilkes at 2026-11-05T10:05:55+01:00
fixup! Base Browser strings
BB 45209: Replace "Account and sync" with "Profiles".
- - - - -
119573bc by Henry Wilkes at 2026-11-05T10:05:55+01:00
fixup! Firefox preference overrides.
BB 45214: Disable megalist (contextual password manager).
- - - - -
586216b3 by Beatriz Rizental at 2026-11-05T10:06:05+01:00
fixup! BB 42728: Modify ./mach lint to skip unused linters
Bug 45224: Enable Rust linters
- - - - -
c849d883 by Pier Angelo Vendrame at 2026-11-05T10:06:14+01:00
fixup! Firefox preference overrides.
BB 44511&45228: Review some urlbar prefs.
- - - - -
9ac22ec5 by Henry Wilkes at 2026-11-05T10:07:17+01:00
fixup! BB 40925: Implemented the Security Level component
BB 45201: Move security level settings to the settings config.
- - - - -
d41be655 by Henry Wilkes at 2026-11-05T10:07:18+01:00
fixup! Base Browser strings
BB 45201: Update security level setting strings.
- - - - -
4b7c0b67 by Henry Wilkes at 2026-11-05T10:08:00+01:00
BB 45201: Customize moz- input widgets for Base Browser.
- - - - -
44fdede0 by Henry Wilkes at 2026-11-05T10:08:01+01:00
fixup! BB 31575: Disable Firefox Home (Activity Stream)
BB 44830: Drop the "home" setting group.
- - - - -
cf755e22 by Henry Wilkes at 2026-11-05T10:08:26+01:00
fixup! BB 41369: Improve Firefox language settings for multi-lingual packages
BB 45195: Change the subcategory for the language notification.
- - - - -
79e21a0f by Henry Wilkes at 2026-11-05T10:08:33+01:00
fixup! BB 41454: Move focus after calling openPreferences for a sub-category.
BB 43640: Modify the focus handling to work with the new settings
redesign.
- - - - -
bc69a800 by Henry Wilkes at 2026-11-05T10:08:51+01:00
fixup! Firefox preference overrides.
BB 45208: Enable the settings redesign.
- - - - -
677f8d2b by Pier Angelo Vendrame at 2026-11-05T10:08:52+01:00
Bug 2063031 - Spoof video PiP size under RFP. r=media-playback-reviewers,kpatenio,alwu,tjr
Differential Revision: https://phabricator.services.mozilla.com/D318184
- - - - -
e8611272 by Pier Angelo Vendrame at 2026-11-05T10:08:52+01:00
Bug 2059471: Do not spoof screen orientation when it is locked. r=tjr
Differential Revision: https://phabricator.services.mozilla.com/D315317
- - - - -
20ab59a5 by Pier Angelo Vendrame at 2026-11-05T10:08:58+01:00
fixup! Firefox preference overrides.
BB 45243: Disable taskbar tabs.
- - - - -
942e10bc by Sylvestre Ledru at 2026-11-05T10:09:04+01:00
Bug 2075120 - Bump rumdl to 0.1.96 since 0.1.91 is no longer on PyPI r=dao
rumdl 0.1.91 was removed from PyPI upstream, so the lint and python-test
virtualenvs can no longer be created. 0.1.96 is the nearest published
release and reports no new errors in-tree.
Differential Revision: https://phabricator.services.mozilla.com/D328750
- - - - -
066a2824 by Beatriz Rizental at 2026-11-05T10:09:55+01:00
fixup! BB 45171: Disable split view.
Bug 44431: Disable about:opentabs
- - - - -
87f015eb by Pier Angelo Vendrame at 2026-11-05T10:10:22+01:00
fixup! Firefox preference overrides.
BB 45278: Disable WebXR as a defense-in-depth.
- - - - -
c437c5e8 by Beatriz Rizental at 2026-11-05T10:10:26+01:00
fixup! Firefox preference overrides.
Bug 45133: Disable browser.toolbars.share-button.enabled
- - - - -
dd862d7a by Pier Angelo Vendrame at 2026-11-05T10:10:39+01:00
fixup! Firefox preference overrides.
BB 45133: Add a missing semicolon.
- - - - -
0d9897e4 by Pier Angelo Vendrame at 2026-11-05T10:11:27+01:00
BB 41108: Remove privileged macOS installation
- - - - -
8ab3ccfb by Pier Angelo Vendrame at 2026-11-05T10:11:38+01:00
fixup! Firefox preference overrides.
TB 45276: Deprecate the Android-specific pref file.
We are importing our main preference file anyway, which has higher
visibility to all devs.
- - - - -
2e297c74 by Pier Angelo Vendrame at 2026-11-05T10:11:45+01:00
fixup! Firefox preference overrides.
BB 45073: Pref review, part 1: 000-tor-browser.js.
- - - - -
ea2cc526 by Henry Wilkes at 2026-11-05T10:12:00+01:00
fixup! BB 41930: Remove the UI to customize accept_languages.
TB 45177: Remove websiteSpoofEnglishControl.
- - - - -
b585ef17 by Pier Angelo Vendrame at 2026-11-05T10:12:00+01:00
fixup! Base Browser's .mozconfigs.
BB 45336: Add --disable-proxy-direct-failover.
- - - - -
7401e2d1 by Henry Wilkes at 2026-11-05T10:12:01+01:00
BB 45249: Remove the duplicate "Verified by" from the old site identity panel.
- - - - -
40756bb3 by Henry Wilkes at 2026-11-05T10:12:09+01:00
fixup! Firefox preference overrides.
BB 45338: Lock browser.smartwindow.enabled.
- - - - -
7c5d4714 by Pier Angelo Vendrame at 2026-11-05T10:12:15+01:00
fixup! Firefox preference overrides.
BB 44815: Disable harmful addon URL blocking.
- - - - -
46b72932 by Henry Wilkes at 2026-11-05T10:12:22+01:00
fixup! BB 18905: Hide unwanted items from help menu
BB 45288: Show "share ideas" menu item again.
- - - - -
367da6a5 by Beatriz Rizental at 2026-11-05T10:12:29+01:00
fixup! BB 43243: Modify mozharness scripts for Base Browser
Bug 45334: Haver marionette harness accept multiple tags
- - - - -
0f86021b by Pier Angelo Vendrame at 2026-11-05T10:12:34+01:00
fixup! Firefox preference overrides.
BB 45080: Disable the reporting API.
- - - - -
e01d3c6b by Pier Angelo Vendrame at 2026-11-05T10:13:50+01:00
fixup! Firefox preference overrides.
BB 45073: 140-153 preference review.
- - - - -
e827b65f by Beatriz Rizental at 2026-11-05T10:14:02+01:00
fixup! Firefox preference overrides.
Bug 44284: Never show promotional vertical pinned tabs dialog
- - - - -
23031296 by Pier Angelo Vendrame at 2026-11-05T10:14:09+01:00
fixup! BB 41369: Improve Firefox language settings for multi-lingual packages
BB 45360: Move our language setting customization to the new design.
- - - - -
c61416fc by Beatriz Rizental at 2026-11-05T10:14:26+01:00
fixup! BB 31740: Remove some unnecessary RemoteSettings instances
Bug 44154: Keep RemoteSettings instances required for testing, when testing
- - - - -
d3f68db7 by Beatriz Rizental at 2026-11-05T10:14:26+01:00
fixup! BB 42730: Patch RemoteSettings to use only local dumps as a data source
Bug 44154: Implement tests to verify correctness of patch
- - - - -
38f2ff8d by Beatriz Rizental at 2026-11-05T10:15:03+01:00
fixup! BB 44711: Hide unwanted setting controls in Base Browser.
Bug 576: Hide more unwanted stuff from settings
- - - - -
05c3be6f by Beatriz Rizental at 2026-11-05T10:15:51+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: Disable HTTPS-only mode when running mochitests
- - - - -
9f7cc882 by Beatriz Rizental at 2026-11-05T10:15:58+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: Upstream geckoiew's own manifest requests
ACCESS_NETWORK_STATE. Tor Browser comments that line
out so geckoview doesn't ask for network-state access,
but the test app needs it. So we add it back.
- - - - -
99b08f6c by Beatriz Rizental at 2026-11-05T10:16:04+01:00
fixup! Firefox preference overrides.
Bug 44820: Add note about prefs modified for mochitests
- - - - -
9a4bde6c by Pier Angelo Vendrame at 2026-11-05T10:16:08+01:00
fixup! BB 42084: Ensure English spoofing works even if preferences are set out of order.
BB 44341: Unregister the intl.accept_languages observer.
- - - - -
c2748365 by Beatriz Rizental at 2026-11-05T10:16:15+01:00
fixup! BB 41695: Warn on window maximization without letterboxing in RFPHelper module
Keep the original window sizes in a module-level WeakMap keyed by window,
instead of in a _rfpOriginalSize expando on the chrome window. Browser chrome
tests fail when a test leaves unexpected properties on the window.
- - - - -
63f2641b by Beatriz Rizental at 2026-11-05T10:16:16+01:00
fixup! BB 42443: Shrink window to match letterboxing size when the emtpy area is clicked.
Make shrinkToLetterbox an RFPHelper method that takes the window, instead
of attaching it to every chrome window. Browser chrome tests fail when a
test leaves unexpected properties on the window.
- - - - -
dd2f00f9 by Beatriz Rizental at 2026-11-05T10:16:16+01:00
fixup! BB 41919: Letterboxing, add temporarily visible web content-size indicator on window resizing.
Keep the letterboxing status timeouts in a module-level WeakMap keyed by
window, instead of in a _letterboxingStatusTimeout expando on the chrome
window. Browser chrome tests fail when a test leaves unexpected properties on
the window.
- - - - -
e63c5fe8 by Beatriz Rizental at 2026-11-05T10:16:16+01:00
fixup! BB 41581: Hide NoScript extension's toolbar button by default.
The widget is created once per browser window, so the extensions.hideNoScript
pref observer was added for every window and never removed. It kept each
closed window alive until shutdown. Remove it when the window unloads.
- - - - -
5a7f1774 by Beatriz Rizental at 2026-11-05T10:16:16+01:00
fixup! BB 9173: Change the default Firefox profile directory to be relative.
Clear the cached gDataDirPortable in DoShutdown, as is done for the other
cached directories. Otherwise its nsIFile is only released by static
destructors, after the leak checker runs, and every test run reports a
48 byte leak.
- - - - -
bd30b8cb by Beatriz Rizental at 2026-11-05T10:16:27+01:00
fixup! BB 43535: Enable tests
This reverts commit e42d7f1136aa55573c01c91a87dec69bbfbdb529.
- - - - -
6ac5b27f by Beatriz Rizental at 2026-11-05T10:16:32+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: The mochitest harness built the testing-common resource
mapping as "file:///" + testingModulesDir. On Linux and macOS
testingModulesDir is already an absolute path, so this produced
"file:////home/...", which content processes fail to load from.
- - - - -
1c662ac2 by Beatriz Rizental at 2026-11-05T10:16:47+01:00
BB 45308: Implement ./mach yeet command
./mach yeet is the Tor Project version of try -- but much simpler.
- - - - -
9e532124 by Beatriz Rizental at 2026-11-05T10:17:06+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet auth
- - - - -
c4b58a81 by Beatriz Rizental at 2026-11-05T10:17:07+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet's upload step
Uploads a local file to the configured build server's public_html
over scp.
- - - - -
83801b71 by Beatriz Rizental at 2026-11-05T10:17:08+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet remote's CI trigger
- - - - -
fd175014 by Beatriz Rizental at 2026-11-05T10:17:18+01:00
fixup! BB 45308: Implement ./mach yeet command
Address review comments
- - - - -
574c02d3 by Beatriz Rizental at 2026-11-05T10:17:19+01:00
fixup! BB 45308: Implement ./mach yeet command
Attend more review comments.
- - - - -
403573ac by Beatriz Rizental at 2026-11-05T10:17:33+01:00
fixup! BB 45120: Add tests for Tor Browser
Bug 44820: Upstream geckoiew's own manifest requests
ACCESS_NETWORK_STATE. Tor Browser comments that line
out so geckoview doesn't ask for network-state access,
but the test app needs it. So we add it back.
- - - - -
33610b92 by Pier Angelo Vendrame at 2026-11-05T10:17:40+01:00
fixup! BB 41108: Remove privileged macOS installation
BB 45240 (fix): Move also an include under ifdef
- - - - -
82 changed files:
- .gitignore
- browser/app/moz.build
- browser/app/profile/001-base-profile.js
- browser/base/content/browser-menubar.inc.xhtml
- browser/base/content/browser-siteIdentity.js
- browser/base/content/languageNotification.js
- browser/components/about/AboutRedirector.cpp
- browser/components/about/components.conf
- browser/components/extensions/parent/ext-browserAction.js
- browser/components/preferences/config/about-firefox.mjs
- browser/components/preferences/config/account-sync.mjs
- browser/components/preferences/config/languages.mjs
- browser/components/preferences/config/privacy.mjs
- + browser/components/preferences/config/protections-from-apps.mjs
- browser/components/preferences/config/search.mjs
- browser/components/preferences/config/tabs-browsing.mjs
- browser/components/preferences/findInPage.js
- browser/components/preferences/jar.mn
- browser/components/preferences/main.inc.xhtml
- browser/components/preferences/main.js
- browser/components/preferences/preferences.js
- browser/components/preferences/preferences.xhtml
- browser/components/preferences/privacy.inc.xhtml
- browser/components/preferences/privacy.js
- − browser/components/securitylevel/SecurityLevelUIUtils.sys.mjs
- + browser/components/securitylevel/config/security-level.mjs
- browser/components/securitylevel/content/securityLevel.js
- + browser/components/securitylevel/content/securityLevelDialog.css
- browser/components/securitylevel/content/securityLevelDialog.js
- browser/components/securitylevel/content/securityLevelDialog.xhtml
- − browser/components/securitylevel/content/securityLevelPreferences.css
- − browser/components/securitylevel/content/securityLevelPreferences.inc.xhtml
- browser/components/securitylevel/jar.mn
- browser/components/securitylevel/moz.build
- + browser/components/securitylevel/widgets/security-level-description.css
- + browser/components/securitylevel/widgets/security-level-description.mjs
- + browser/components/securitylevel/widgets/security-level-display.css
- + browser/components/securitylevel/widgets/security-level-display.mjs
- browser/components/sidebar/SidebarManager.sys.mjs
- browser/components/sidebar/browser-sidebar.js
- browser/config/mozconfigs/base-browser
- browser/config/mozconfigs/base-browser-android
- dom/base/ScreenOrientation.cpp
- dom/media/PictureInPictureWindow.cpp
- dom/media/PictureInPictureWindow.h
- dom/media/mediaelement/HTMLVideoElement.cpp
- dom/media/mediaelement/HTMLVideoElement.h
- mobile/android/geckoview/src/androidTest/AndroidManifest.xml
- mobile/android/test_runner/src/main/AndroidManifest.xml
- python/mach/mach/command_util.py
- python/mozlint/mozlint/cli.py
- python/sites/lint.txt
- python/sites/python-test.txt
- services/settings/dumps/main/moz.build
- services/settings/remote-settings.sys.mjs
- + services/settings/test/unit/test_remote_settings_base_browser.js
- services/settings/test/unit/xpcshell.toml
- testing/mochitest/runtests.py
- testing/mozharness/scripts/marionette.py
- testing/specialpowers/api.js
- toolkit/components/pictureinpicture/tests/browser.toml
- + toolkit/components/pictureinpicture/tests/browser_resistFingerprinting.js
- toolkit/components/resistfingerprinting/RFPHelper.sys.mjs
- toolkit/content/widgets/lit-utils.mjs
- toolkit/content/widgets/moz-support-link/moz-support-link.mjs
- toolkit/locales/en-US/toolkit/global/base-browser.ftl
- toolkit/moz.build
- toolkit/xre/MacRunFromDmgUtils.mm
- toolkit/xre/nsXREDirProvider.cpp
- tools/moz.build
- + tools/yeet/__init__.py
- + tools/yeet/auth.py
- + tools/yeet/common.py
- + tools/yeet/mach_commands.py
- + tools/yeet/remote.py
- + tools/yeet/tests/python/conftest.py
- + tools/yeet/tests/python/python.toml
- + tools/yeet/tests/python/test_auth.py
- + tools/yeet/tests/python/test_common.py
- + tools/yeet/tests/python/test_remote.py
- + tools/yeet/tests/python/test_upload.py
- + tools/yeet/upload.py
The diff was not included because it is too large.
View it on GitLab: https://gitlab.torproject.org/tpo/applications/mullvad-browser/-/compare/33…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/mullvad-browser/-/compare/33…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 4 commits: fixup! Tor Browser localization migration scripts.
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
ddde8dc5 by Henry Wilkes at 2026-11-05T10:02:53+01:00
fixup! Tor Browser localization migration scripts.
TB 45433: Change the script to be more versatile for test runs.
Instead of passing in a python module name for the recipe, you now pass
in the file path to the recipe script.
You can now change the reference directory with the
--reference-directory argument, which is useful for testing scripts
before the changes have reached the translation repository.
- - - - -
96461bbb by Henry Wilkes at 2026-11-05T10:02:53+01:00
fixup! Tor Browser localization migration scripts.
TB 45433: Refactor the WeblateMetadata class.
We are stricter about checking the return types from the weblate API,
and making sure it doesn't make requests to unexpected URLs.
We also limit the components to the browser components, and we slightly
alter the `is_translated` public method.
- - - - -
355374f4 by Henry Wilkes at 2026-11-05T10:02:53+01:00
fixup! Tor Browser localization migration scripts.
TB 45433: Add type hints to the script.
- - - - -
a9456739 by Henry Wilkes at 2026-11-05T10:02:54+01:00
fixup! Tor Browser localization migration scripts.
TB 45433: Update the migrate.py documentation.
- - - - -
1 changed file:
- tools/torbrowser/l10n/migrate.py
Changes:
=====================================
tools/torbrowser/l10n/migrate.py
=====================================
@@ -1,58 +1,252 @@
"""
-Migration script for running migration recipes.
+Migration script for running Tor Browser migration recipes.
-Requires the mozilla fluent.migrate package (available with pip).
+Based on the Firefox migration script, adapted for Tor Browser. See
+https://firefox-source-docs.mozilla.org/l10n/migrations/ for more context and
+information on how to write the migration recipes.
-NOTE: This will likely send queries to the weblate API as part of the run.
-Weblate may have a query limit of 100 requests per day for unauthorised users.
+## Concepts
+
++ String. Here, when we say "string", it refers to a piece of text that can be
+ translated. In practice, you can think of it as a being defined by a triple:
+ a file path relative to a locale's directory, an ID, and some content. For
+ example `("./tor-browser.ftl", "my-id", "my-id =\\n .label=Content")`.
+ When a string is translated the file path and ID stay the same, whilst the
+ translatable part of the content can vary.
++ Reference files. These are the en-US source Fluent files that contain the
+ *manual* string changes made by a developer. For most migrations, there is
+ only one reference file.
++ Migration recipe. A collection of instructions that take some string inputs
+ and transforms them into new strings. These are meant to mirror the manual
+ changes that were made in the reference files, in a way that can be applied
+ to any locale.
++ Translation repository. This refers to a local copy of the `translation`
+ repository (https://gitlab.torproject.org/tpo/translation) This repository
+ contains a different branch for different collections of strings. For
+ Tor Browser we usually use `tor-browser`, `base-browser` and
+ `fenix-torbrowserstringsxml`. Each branch will contain an `en-US` directory,
+ which contains the "source" files for translators to translate. These source
+ files are taken from the `tor-browser` repository. The branches also contain
+ a directory for each locale that is to be translated, in a file structure that
+ reflects the source `en-US` directory. This is where the migration script will
+ write changes to the translated files.
+
+
+## Usage
+
+You will likely want to run this with `./mach python`, so that it uses the
+`fluent.migrate` and `fluent.syntax` packages provided with the `tor-browser`
+repository.
+
+For example, you might run this as
-Based on the firefox migration script, adapted for tor browser. See
-https://firefox-source-docs.mozilla.org/l10n/migrations/ for more context and
-information on how to write the migration recipes.
+```
+ ./mach python migrate.py --translation-git /home/user/translation --locales 'es-ES sr' ./migrations/bug-xxxx-my-migration-recipe.py
+```
+
+Here `/home/user/translation` is a local translation repository with one of its
+branches checked out (see below). This will run the migration recipe given in
+`./migrations/bug-xxxx-my-migration-recipe.py` for the `es-ES` and `sr`
+sub-directories within the `translation/` directory.
+
+### Changing the reference location
+
+You can optionally run the script with `--reference_directory` to read the
+reference en-US files from somewhere other than the `translation` directory.
+This can be useful when your manual changes have yet to reach the translation
+repository, so you want to point the script to read the reference from the
+`tor-browser` working directory instead. E.g.
+
+```
+ --reference-directory /home/user/tor-browser/toolkit/locales/en-US/toolkit/global/
+```
+
+
+## Recipes
+
+Migration recipes are meant to mirror some manual change that was made to the
+en-US source strings, in a way that can be reproduced in another locale.
+### Example 1
-Usage with an example:
+For this example, a developer wants to remove the string content from
+`old-strings.properties`:
-We have some en-US file "updated.ftl" in the tor-browser repository that we have
-added new strings to. Some of these strings are copies or concatenations of some
-already existing strings in a `.dtd`, `.properties` or `.ftl` file (including
-strings within "updated.ftl").
+```
+my.old.string=Some string content
+my.old.title=This is the tooltip
+```
+
+And add them to `tor-browser.ftl` instead, as:
-So we also write a migration recipe in
-`./l10n_migrations/bug-xxxx-my-migration-recipe.py`
-which includes a `migrate(ctx)` method. This method takes the old strings and
-create new Messages or Terms for "updated.ftl" using `ctx.add_transforms`. These
-should match what was already done manually in "updated.ftl".
+```
+my-new-string = Some string content
+ .title = This is the tooltip
+```
+
+For the en-US source strings, the developer simply deletes the two lines in the
+`old-strings.properties` file (or the whole file, if these are the last two).
+And they manually write in the content of `my-new-string` to `tor-browser.ftl`.
+These manual changes will then eventually reach the `translation` repository to
+be translated.
+
+But to save translators making the same manual changes, or re-translating, the
+developer can write a migration recipe that mirror's their manual changes. In
+this case, this migration recipe would contain:
+
+```
+ctx.add_transforms(
+ "tor-browser.ftl", # The path to write to.
+ "tor-browser.ftl", # The path to the reference file.
+ transforms_from(
+ \"\"\"
+my-new-string = { COPY(path, "my.old.string") }
+ .title = { COPY(path, "my.old.title") }
+\"\"\",
+ path="old-strings.properties", # The path to read from.
+ ),
+)
+```
+
+Note, the first argument of `add_transforms` is the target path, which is
+`tor-browser.ftl` in this case. This means that the migration script will try to
+write the resulting `my-new-string` to the locale's `./tor-browser.ftl` file.
+For example, to `translation/es-ES/tor-browser.ftl`.
+
+The second argument refers to the *reference* path. In almost all cases the
+reference file will have the same name and path as the target path, but it has a
+different role. Here the path is relative to the reference directory, which
+contains the en-US source files. In this case, by default this means that
+`translation/en-US/tor-browser.ftl` will act as the reference, but the exact
+path could be changed with the `--reference-directory` argument. The existing
+`my-new-string` will be read from this file to confirm that the migration
+recipe produces the correct result.
+
+The file `old-strings.properties` is used as an input. This means that the
+existing strings in the locale's `old-strings.properties` file will be read to
+construct the new string `my-new-string`. For example, it will be read from
+`translation/es-ES/old-strings.properties`.
+
+The `COPY` acts like a Fluent function, which asks the transformation to copy
+the content from the translated string directly.
+
+### Example 2
+
+For this example, a developer wants to swap a string in `tor-browser.ftl` from:
+
+```
+my-old-string2 = Some string content
+ .title = This is the tooltip
+```
+
+to
+
+```
+my-new-string2 =
+ .label = Some string content
+ .title = This is the tooltip
+```
-Then we copy the en-US file to our local translation repository, say at
-`/home/user/translation/en-US/updated.ftl`. The en-US file is needed as a
-reference during migration to know where in the new file the new Messages or
-Terms should be placed. Moreover, the migration can be verified against the
-en-US file to ensure it is working as intended.
+The developer removes `my-old-string2` from the file and adds `my-new-string2`
+instead. This manual change will then eventually reach the `translation`
+repository for `my-new-string2` to be translated.
-Then we run the migration for individual locales:
+The developer also writes a migration recipe to mirror this change:
```
- python migrate_l10n.py --translation-git /home/user/translation --locales 'es-ES sr' l10n_migrations.bug-xxxx-my-migration-recipe
+ctx.add_transforms(
+ "tor-browser.ftl",
+ "tor-browser.ftl",
+ transforms_from(
+ \"\"\"
+my-new-string2 =
+ .label = { COPY_PATTERN(path, "my-old-string2") }
+ .title = { COPY_PATTERN(path, "my-old-string2.title") }
+\"\"\",
+ path="tor-browser.ftl",
+ ),
+)
```
-This will first run a mock migration using the en-US localization files. This is
-to help ensure that the migration will work as intended. I.e. if we ran the
-migration recipe for en-US, using it as both the source of old strings and as a
-reference, then each transformation using these old strings should produce a
-Message or Term that is identical to the one in the reference file.
+Note that in this case the locale's `tor-browser.ftl` file is being used as both
+the input and the output.
+
+Note that for a Fluent-to-Fluent migration we use `COPY_PATTERN` rather than
+`COPY`. The second argument provides an ID that either point's to the
+Fluent Messages' value (roughly, the text content) by giving the Message's ID,
+or one of its attributes by adding a corresponding suffix to the ID.
+
+### Other examples
+
+Migration recipes can support a lot more, including more advanced
+transformations like removing or replacing HTML tags from content. There are
+some existing recipes in the `./migrations` directory that can be used as a
+reference.
+
+
+## translation directory
+
+In most cases, you will just need to check out a `translation` branch that
+contains the translated strings used by the migration recipe, as well as the
+Fluent file that will be written to. Usually, this will be a branch based on
+the origin/upstream `tor-browser` or `base-browser` branches.
+
+However, if the migration recipe requires source files that are in a different
+branch to the Fluent file that is being written to, then you will need to
+manually copy those files into the working directory before running the script.
+
+
+## Script procedure
-Then this will run `migrate(ctx)` for the es-ES and sr locales. Some of the
-transformations will not be completed for a locale if that locale does not
-contain a translated version of the old strings the transformation requires
-(because there is no string to copy).
+### Test en-US migration
-If one of the old strings is from a `.dtd` or `.properties` file, this will
-check whether they are marked as translated on weblate using its API. This
-prevents copying "placeholder" en-US values into the locale's fluent files.
+The script will first run a test migration using the en-US strings. It will run
+the migration using the files from `translation/en-US/` as the input. In the
+previous example 1, this will read `my.old.string` and `my.old.title` from
+`translation/en-US/old-strings.properties`. And in example 2, this will read
+`my-old-string2` from `translation/en-US/tor-browser.ftl`.
-Any warnings or errors will be logged to stderr in the console.
+If any of the input strings are missing, this indicates that there is likely a
+mistake in the recipe or the translation directory and the script will be
+aborted without running the migration for the other locales.
+
+Otherwise, it then compares the result of this migration with the strings found
+in the reference files. In the previous example 1, this will read the entry for
+`my-new-string` from `<reference-dir>/tor-browser.ftl`, where `<reference-dir>`
+is `translation/en-US/` unless `--reference-directory` is given to use a
+different directory. If the reference entry for `my-new-string` differs from the
+entry that the recipe automatically produced, then this indicates that there is
+a mistake in the recipe and the script will be aborted.
+
+### Locale migrations
+
+If the test migration passed, then the recipe will be re-run for each of the
+specified locales. If the locale is missing some strings or files that a single
+transformation requires, then that transformation will be skipped and the
+corresponding entry won't be written to the Fluent file. Otherwise the new
+entries will be appended to the existing Fluent files.
+
+#### Non-Fluent strings and Weblate queries
+
+Some non-Fluent formats, like DTD and properties, will fill untranslated strings
+with the source en-US content. And we don't want these untranslated strings to
+be used for migrations. There is no metadata within the files to determine this,
+and simply being the same as the en-US string is not a reliable indicator.
+
+So for these strings the script will additionally make a remote query to the
+Weblate API to fetch the metadata that indicates whether the string is
+considered translated or not. If a transformation requires a string that is
+marked as untranslated, it will be skipped.
+
+NOTE: The Weblate metadata is not always reliable, so you should still manually
+review the changes.
+
+NOTE: When testing before, the Weblate API was limited to 100 requests per day
+per IP address for unauthorised users. If this becomes an issue you may want to
+run the migrations in limited batches of locales with new IP addresses. Or, you
+can create a Weblate account and change this script to pass an authorisation
+token with the request.
"""
import argparse
@@ -63,142 +257,299 @@ import logging
import os
import sys
import urllib.request
+from collections.abc import Iterator
+from typing import Any, NamedTuple, Protocol, cast
from fluent.migrate.context import MigrationContext
from fluent.migrate.errors import EmptyLocalizationError, UnreadableReferenceError
from fluent.syntax import ast, parse, serialize
-def in_red(string):
+def in_red(string: str) -> str:
"""
Wrap a string so that it is shown as red in the console.
+ :param string: The string to wrap.
+ :returns: The wrapped string.
"""
return f"\x1b[1;91m{string}\x1b[0m"
+def assert_keys(
+ check_dict: dict[Any, Any], expected_keys: tuple[str, ...], url: str
+) -> None:
+ """
+ Verify that the dictionary contains *at least* the expected keys,
+ otherwise this throws.
+ :param check_dict: The dictionary to check.
+ :param url: The url where the dictionary was fetched from.
+ """
+ for key in expected_keys:
+ if key not in check_dict:
+ raise ValueError(f"Missing '{key}' in response for {url}")
+
+
+class WeblateUnit:
+ """
+ Represents a Weblate "unit": roughly corresponds to a translated string.
+
+ See https://docs.weblate.org/en/latest/api.html#units.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("context", "translated"), url)
+ string_id = data["context"]
+ translated = data["translated"]
+ if not isinstance(string_id, str):
+ raise ValueError(f"Unexpected 'context' type in response for {url}")
+ if not isinstance(translated, bool):
+ raise ValueError(f"Unexpected 'translated' type in response for {url}")
+
+ self.string_id = string_id
+ self.translated = translated
+
+
+class WeblateTranslation:
+ """
+ Represents a Weblate "translation": roughly corresponds to the translation
+ of a file for a given locale/language.
+
+ See https://docs.weblate.org/en/latest/api.html#translations.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("filename", "units_list_url"), url)
+ locale_path = data["filename"]
+ units_url = data["units_list_url"]
+ if not isinstance(locale_path, str):
+ raise ValueError(f"Unexpected 'filename' type in response for {url}")
+ if not isinstance(units_url, str):
+ raise ValueError(f"Unexpected 'units_list_url' type in response for {url}")
+
+ self.locale_path = locale_path
+ self.units_url = units_url
+ # The units, indexed by their string ID. Lazy-loaded and `None` whilst
+ # unfilled.
+ self.units: None | dict[str, WeblateUnit] = None
+
+
+class WeblateComponent:
+ """
+ Represents a Weblate "component": roughly corresponds to a source (en-US)
+ file that can be translated.
+
+ See https://docs.weblate.org/en/latest/api.html#components.
+ And https://docs.weblate.org/en/latest/user/basic.html.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("template", "translations_url", "branch"), url)
+ template_path = data["template"]
+ translations_url = data["translations_url"]
+ branch = data["branch"]
+ if not isinstance(template_path, str):
+ raise ValueError(f"Unexpected 'template' type in response for {url}")
+ if not isinstance(translations_url, str):
+ raise ValueError(
+ f"Unexpected 'translations_url' type in response for {url}"
+ )
+ if not isinstance(branch, str):
+ raise ValueError(f"Unexpected 'branch' type in response for {url}")
+
+ self.branch = branch
+ # The path to the source (en-US) file.
+ self.template_path = template_path
+ # The URL to fetch the component's translations from.
+ self.translations_url = translations_url
+ # The translations data, indexed by the locale file paths. Lazy-loaded
+ # and `None` whilst unfilled.
+ self.translations: None | dict[str, WeblateTranslation] = None
+
+
class WeblateMetadata:
"""
- Manages and fetches string metadata from weblate.
+ Manages and fetches string metadata from Weblate.
"""
- def __init__(self):
+ # The translation branches that we expect to be used for Weblate.
+ _BROWSER_BRANCHES = ["tor-browser", "base-browser", "fenix-torbrowserstringsxml"]
+ _WEBLATE_API_URL = "https://hosted.weblate.org/api/"
+ _WEBLATE_API_TOR_COMPONENTS_URL = _WEBLATE_API_URL + "projects/tor/components/"
+
+ def __init__(self) -> None:
+ """
+ Create a new instance for fetching Weblate metadata.
+ """
self.logger = logging.getLogger("weblate-metadata")
self.logger.setLevel(logging.INFO)
- # The _components property will be lazy-loaded with weblate data.
- #
- # On weblate, for monolingual formats, the component will have a
- # "template" file, which matches the en-US file path in the
- # "translation" git repo. So we can find a component through a matching
- # template.
- #
- # Each translation in that component will have a "filename" that will
- # match the locale's file path in the "translation" git repo. So we can
- # find a translation through a matching filename.
- #
- # Each translation can be queried for its units, including metadata.
- # Each unit's "context" will match the string's id in the corresponding
- # file.
- #
- # Expect the final structure to be:
- # {
- # template: {
- # "translations-url": str, # Used for API translations query.
- # "translations": {
- # filename: {
- # "units-url": str, # Used for API units query.
- # "units": {
- # context: {
- # "translated": bool,
- # },
- # },
- # },
- # },
- # },
- # }
- self._components = None
-
- def _get_weblate_response(self, url):
+ # The _components property will be lazy-loaded with Weblate data.
+ self._components: dict[str, WeblateComponent] | None = None
+
+ def _get_weblate_response(self, url: str) -> Any:
+ """
+ Make a single query to Weblate.
+ :param url: The URL to fetch.
+ :returns: The JSON response.
+ """
+ if not url.startswith(self._WEBLATE_API_URL):
+ raise ValueError(f"Unexpected URL request: {url}")
+
weblate_request = urllib.request.Request(
url,
# NOTE: can set the request header:
# "Authorization": "Token WEBLATE_TOKEN"
- # to get around rate-limiting
+ # to get around rate-limiting.
+ # NOTE: We empty the User-Agent to override the default
+ # value of "Python-urllib/{major}.{minor}".
headers={"User-Agent": ""},
)
- with urllib.request.urlopen(weblate_request, timeout=20) as response:
+ with urllib.request.urlopen(weblate_request) as response:
return json.load(response)
- def _get_from_weblate(self, url):
- ret = []
+ def _get_from_weblate(self, url: str) -> list[dict[Any, Any]]:
+ """
+ Fetch a list of results from Weblate.
+ :param url: The initial URL to fetch a response from.
+ :returns: The returned list of results.
+ """
+ ret: list[dict[Any, Any]] = []
while url:
response = self._get_weblate_response(url)
+ if not isinstance(response, dict):
+ raise ValueError(f"Unexpected response type for {url}")
+ assert_keys(response, ("results", "next"), url)
+
+ res_val = response["results"]
+ if not isinstance(res_val, list):
+ raise ValueError(f"Unexpected 'results' type for {url}")
+ for res_item in res_val:
+ if not isinstance(res_item, dict):
+ raise ValueError(f"Unexpected 'results' item type for {url}")
+ ret.append(res_item)
+
# Continue to fetch the next page, if it is present.
- # Expect the "next" url to be empty
+ # Expect the "next" url to be null
# or the same url with "?page=2", etc.
- url = response["next"]
- ret.extend(response["results"])
+ next_val = response["next"]
+ if next_val is not None and not isinstance(next_val, str):
+ raise ValueError(f"Unexpected 'next' type in response for {url}")
+ url = "" if next_val is None else next_val
return ret
- def _get_components(self):
+ def _get_components(self) -> dict[str, WeblateComponent]:
+ """
+ Get all the Tor Browser Weblate components.
+
+ We identify each Weblate component by its template path: the en-US
+ file path in the translation repository.
+
+ NOTE: We assume that the template path uniquely identifies the
+ component, even though this is not guaranteed in general by Weblate.
+
+ :returns: A dictionary of components, indexed by their en-US template
+ path.
+ """
+ url = self._WEBLATE_API_TOR_COMPONENTS_URL
if self._components is None:
self._components = {
- comp["template"]: {
- "translations": None,
- "translations-url": comp["translations_url"],
- }
- for comp in self._get_from_weblate(
- "https://hosted.weblate.org/api/projects/tor/components/"
+ comp.template_path: comp
+ for comp in (
+ WeblateComponent(data, url) for data in self._get_from_weblate(url)
)
- if comp["template"]
+ if comp.template_path and comp.branch in self._BROWSER_BRANCHES
}
return self._components
- def _get_translations(self, template):
- component = self._get_components().get(template, None)
+ def _get_translations(
+ self, template_path: str
+ ) -> dict[str, WeblateTranslation] | None:
+ """
+ Get the Weblate translations for a given Weblate component.
+
+ We identify each translation by its file path: the locale-specific path
+ that the translated file is written to.
+
+ :param template_path: The component's en-US template path.
+ :returns: A dictionary of translations, indexed by their locale file
+ paths. Or `None` if no components were found.
+ """
+ component = self._get_components().get(template_path, None)
if not component:
- self.logger.warning(f"No component in weblate for {template}.")
+ self.logger.warning(f"No component in Weblate for {template_path}.")
return None
- if component["translations"] is None:
- component["translations"] = {
- trans["filename"]: {
- "units": None,
- "units-url": trans["units_list_url"],
- }
- for trans in self._get_from_weblate(component["translations-url"])
+ if component.translations is None:
+ url = component.translations_url
+ component.translations = {
+ trans.locale_path: trans
+ for trans in (
+ WeblateTranslation(data, url)
+ for data in self._get_from_weblate(url)
+ )
}
- return component["translations"]
+ return component.translations
+
+ def _get_units(
+ self, template_path: str, locale_path: str
+ ) -> dict[str, WeblateUnit] | None:
+ """
+ Get the Weblate units for a given Weblate translation.
+
+ We identify each unit by its string ID.
- def _get_units(self, template, file):
- translation_dict = self._get_translations(template)
+ :param template_path: The containing component's en-US template path.
+ :param locale_path: The translation's locale file path.
+ :returns: A dictionary of units, indexed by their string ID. Or `None`
+ if no translations could be found.
+ """
+ translation_dict = self._get_translations(template_path)
if translation_dict is None:
return None
- translation = translation_dict.get(file, None)
+ translation = translation_dict.get(locale_path, None)
if translation is None:
- self.logger.warning(f"No translation in weblate for {file}.")
+ self.logger.warning(f"No translation in Weblate for {locale_path}.")
return None
- if translation["units"] is None:
- translation["units"] = {
- unit["context"]: {
- "translated": unit["translated"],
- }
- for unit in self._get_from_weblate(translation["units-url"])
+ if translation.units is None:
+ url = translation.units_url
+ translation.units = {
+ unit.string_id: unit
+ for unit in (
+ WeblateUnit(data, url) for data in self._get_from_weblate(url)
+ )
}
- return translation["units"]
+ return translation.units
- def is_translated(self, template_path, locale_path, string_id):
+ def is_translated(self, file_path: str, locale: str, string_id: str) -> bool:
"""
- Whether the given string is marked as translated on weblate.
+ Test whether the given string is marked as translated on Weblate.
+
+ :param file_path: The file to check the translation of, relative to the
+ locale's directory.
+ :param locale: The locale to check for.
+ :param string_id: The ID of the string to check.
"""
+ template_path = os.path.join("en-US", file_path)
+ locale_path = os.path.join(locale, file_path)
unit_dict = self._get_units(template_path, locale_path)
if unit_dict is None:
return False
unit = unit_dict.get(string_id, None)
if unit is None:
- self.logger.warning(f"No unit in weblate for {locale_path}:{string_id}.")
+ self.logger.warning(f"No unit in Weblate for {locale_path}:{string_id}.")
return False
- return unit["translated"]
+ return unit.translated
class TorBrowserMigrationContext(MigrationContext):
@@ -206,12 +557,18 @@ class TorBrowserMigrationContext(MigrationContext):
Extension which adds some extra methods to use for tor-browser.
"""
- def __init__(self, locale, reference_dir, localization_dir):
+ def __init__(self, locale: str, reference_dir: str, localization_dir: str) -> None:
super().__init__(locale, reference_dir, localization_dir)
- def _fluent_keys(self, resource):
+ def _fluent_keys(self, resource: ast.Resource) -> Iterator[str]:
+ """
+ Generate all the keys within a Fluent resource, where a key is an
+ identifier for a Term, a Message, a Term attribute, or a Message
+ attribute.
+ :yield: The Fluent keys.
+ """
# ast.Resource, want to extract all Message and Term identifiers, as
- # well as their
+ # well as their attributes.
for entry in resource.body:
if not isinstance(entry, (ast.Term, ast.Message)):
continue
@@ -223,12 +580,13 @@ class TorBrowserMigrationContext(MigrationContext):
for attr in entry.attributes:
yield f"{key}.{attr.id.name}"
- def tb_get_available_strings(self):
+ def tb_get_available_strings(self) -> set[tuple[str, str]]:
"""
- Return all the (path, string_id) pairs for all loaded localization
+ Get all the (path, string_id) pairs for all loaded localization
resources.
+ :returns: The string pairs.
"""
- all_strings = set()
+ all_strings: set[tuple[str, str]] = set()
# ctx.localization_resources is a dict containing all the loaded
# localization_resources that have been added during add_transforms.
# { localization_path: resource }
@@ -237,14 +595,13 @@ class TorBrowserMigrationContext(MigrationContext):
all_strings.update((path, key) for key in self._fluent_keys(resource))
else:
# dictionary of { identifies: value } in legacy resource.
- # For tor-browser,
- # Only include references that differ from the en-US strings.
all_strings.update((path, key) for key in resource.keys())
return all_strings
- def tb_get_missing_resources(self):
+ def tb_get_missing_resources(self) -> set[str]:
"""
- Return the missing localization resources.
+ Get the missing localization resources.
+ :returns: The set of resource paths.
"""
return set(
path
@@ -253,25 +610,51 @@ class TorBrowserMigrationContext(MigrationContext):
if path not in self.localization_resources
)
- def tb_get_transform(self, target_path, transform_id):
+ def tb_get_transform(
+ self, target_path: str, transform_id: str
+ ) -> ast.Message | ast.Term | None:
"""
- Find the transformation node with the given id for the given path.
+ Find a transformation node.
+ :param target_path: The target path of the transformation.
+ :param transform_id: The ID of the transformation, AKA the string ID.
+ :returns: The matching transformation node, or `None` if there is no
+ match.
"""
for node in self.transforms[target_path]:
if node.id.name == transform_id:
return node
return None
- def tb_get_reference_entry(self, target_path, entry_id):
+ def tb_get_reference_entry(
+ self, target_path: str, transform_id: str
+ ) -> ast.Message | ast.Term | None:
"""
- Find the reference node that would be used for the given id and path.
+ Find a reference Message or Term for a given transformation.
+ :param target_path: The target path of the transformation.
+ :param transform_id: The ID of the transformation, AKA the string ID.
+ :returns: The matching reference entry for the transformation, or `None`
+ if there is no match.
"""
for entry in self.reference_resources[target_path].body:
- if isinstance(entry, (ast.Term, ast.Message)) and entry.id.name == entry_id:
+ if (
+ isinstance(entry, (ast.Term, ast.Message))
+ and entry.id.name == transform_id
+ ):
return entry.clone()
return None
+class RecipeModule(Protocol):
+ def migrate(self, context: MigrationContext) -> None: ...
+
+
+class FluentSyntaxError(NamedTuple):
+ path: str
+ message: str
+ line: int
+ sample: str
+
+
class TorBrowserMigrator:
"""
Performs a tor-browser migration.
@@ -279,26 +662,38 @@ class TorBrowserMigrator:
def __init__(
self,
- en_US_dir,
- locale_dirs,
- migrate_module,
- weblate_metadata,
- ):
+ en_US_ref_dir: str,
+ en_US_target_dir: str,
+ locale_dirs: dict[str, str],
+ recipe_module: RecipeModule,
+ weblate_metadata: WeblateMetadata,
+ ) -> None:
+ """
+ :param en_US_ref_dir: The path to the en-US directory where reference
+ Fluent entries for the recipe can be found.
+ :param en_US_target_dir: The path to the en-US directory where existing
+ strings used by the recipe can be found.
+ :param locale_dirs: The collection of locales to run the migrations for.
+ :param recipe_module: The python module that contains the recipe
+ instructions.
+ :param weblate_metadata: The object to fetch Weblate metadata from.
+ """
self.logger = logging.getLogger("tor-browser-migrator")
self.logger.setLevel(logging.INFO)
- self.en_US_dir = en_US_dir
+ self.en_US_ref_dir = en_US_ref_dir
+ self.en_US_target_dir = en_US_target_dir
self.locale_dirs = locale_dirs
- self.migrate_module = migrate_module
+ self.recipe_module = recipe_module
self.weblate_metadata = weblate_metadata
- def run(self):
+ def run(self) -> None:
"""
Run the migration.
"""
if not self._check_en_US_resources():
sys.exit(1)
- fluent_errors = []
+ fluent_errors: list[FluentSyntaxError] = []
for locale, locale_dir in self.locale_dirs.items():
if locale == "en-US":
print("", file=sys.stderr)
@@ -316,12 +711,18 @@ class TorBrowserMigrator:
"Migration does not need to be run again, but the following "
"syntax errors should be fixed manually.\n"
+ "\n".join(
- f"{in_red(full_path)}: line {line}: {message}: [[{sample}]]"
- for full_path, message, line, sample in fluent_errors
+ f"{in_red(err.path)}: line {err.line}: {err.message}: [[{err.sample}]]"
+ for err in fluent_errors
)
)
- def _run_locale(self, locale, locale_dir):
+ def _run_locale(self, locale: str, locale_dir: str) -> list[FluentSyntaxError]:
+ """
+ Run a migration for a given locale.
+ :param locale: The name of the locale.
+ :param locale_dir: The path to the locale's directory.
+ :returns: A list of Fluent errors in the written files.
+ """
print("\n\n", file=sys.stderr)
self.logger.info(f"Migrating '{in_red(locale)}' locale\n")
@@ -358,7 +759,7 @@ class TorBrowserMigrator:
available_strings = ctx.tb_get_available_strings()
wrote_file = False
- errors = []
+ errors: list[FluentSyntaxError] = []
for target_path, reference in ctx.reference_resources.items():
translated_ids = [
@@ -422,13 +823,13 @@ class TorBrowserMigrator:
break
# Strings in legacy formats might have an entry in the file
# that is just a copy of the en-US strings.
- # For these we want to check the weblate metadata to ensure
+ # For these we want to check the Weblate metadata to ensure
# it is a translated string.
if not path.endswith(
".ftl"
) and not self.weblate_metadata.is_translated(
- os.path.join("en-US", path),
- os.path.join(locale, path),
+ path,
+ locale,
string_id,
):
can_transform = False
@@ -436,7 +837,7 @@ class TorBrowserMigrator:
f"Skipping transform {target_path}:{transform_id} "
f"for '{locale}' locale because the string "
f"{path}:{string_id} has not been translated on "
- "weblate."
+ "Weblate."
)
break
if not can_transform:
@@ -463,7 +864,9 @@ class TorBrowserMigrator:
wrote_file = True
# Collect any fluent parsing errors from the newly written file.
errors.extend(
- (full_path, message, line, sample)
+ FluentSyntaxError(
+ path=full_path, message=message, line=line, sample=sample
+ )
for message, line, sample in self._fluent_errors(full_content)
)
@@ -471,27 +874,42 @@ class TorBrowserMigrator:
self.logger.info(f"No files written for '{locale}' locale.")
return errors
- def _fluent_errors(self, fluent):
+ def _fluent_errors(self, fluent_content: str) -> Iterator[tuple[str, int, str]]:
"""
- Verify that the given fluent string can be parsed correctly.
+ Parse the given content as a Fluent file and generate all the syntax
+ errors.
+ :param fluent_content: The file content to parse.
+ :yield: Each encountered Fluent syntax error as a triple of the message,
+ the line number, and a sample.
"""
- resource = parse(fluent)
+ resource = parse(fluent_content)
for entry in resource.body:
if not isinstance(entry, ast.Junk):
continue
for annotation in entry.annotations:
- line = fluent[0 : annotation.span.start].count("\n") + 1
- sample_start = max(annotation.span.start - 15, 0)
- sample = "…" + fluent[sample_start : sample_start + 30] + "…"
- yield annotation.message, line, sample
-
- def _get_migration_context(self, locale, locale_dir):
- prev_missing_resources = set()
+ start = 0
+ if annotation.span:
+ start = annotation.span.start
+ line = fluent_content[0:start].count("\n") + 1
+ sample_start = max(start - 15, 0)
+ sample = "…" + fluent_content[sample_start : sample_start + 30] + "…"
+ yield annotation.message or "", line, sample
+
+ def _get_migration_context(
+ self, locale: str, locale_dir: str
+ ) -> TorBrowserMigrationContext:
+ """
+ Create a new migration context.
+ :param locale: The name of the locale.
+ :param locale_dir: The directory path for the locale.
+ :returns: The new context.
+ """
+ prev_missing_resources: set[str] = set()
while True:
- ctx = TorBrowserMigrationContext(locale, self.en_US_dir, locale_dir)
+ ctx = TorBrowserMigrationContext(locale, self.en_US_ref_dir, locale_dir)
try:
- self.migrate_module.migrate(ctx)
+ self.recipe_module.migrate(ctx)
except EmptyLocalizationError:
# This case will be handled by missing_resources below.
# NOTE: At the time of writing, add_transforms only throws if
@@ -543,20 +961,28 @@ class TorBrowserMigrator:
# before localization_resources was fully populated.
prev_missing_resources = missing_resources
- def _remove_if_empty(self, path):
+ def _remove_if_empty(self, path: str) -> None:
+ """
+ Remove a file if it is empty.
+ :param path: The path to remove.
+ """
if os.stat(path).st_size:
self.logger.warning(f"{path} is no longer empty. Not deleting.")
return
os.remove(path)
- def _check_en_US_resources(self):
- # We pass in the en-US directory as the localization directory, as well
- # as the reference directory.
- ctx = TorBrowserMigrationContext("en-US", self.en_US_dir, self.en_US_dir)
+ def _check_en_US_resources(self) -> bool:
+ """
+ Verify that the migration recipe works as expected using en-US strings.
+ :returns: Whether the recipe worked as expected.
+ """
+ ctx = TorBrowserMigrationContext(
+ "en-US", self.en_US_ref_dir, self.en_US_target_dir
+ )
have_error = False
try:
- self.migrate_module.migrate(ctx)
+ self.recipe_module.migrate(ctx)
except EmptyLocalizationError:
# Handle with localization_resources check.
# NOTE: This throwing may have prevented further add_transforms from
@@ -566,7 +992,9 @@ class TorBrowserMigrator:
have_error = True
except UnreadableReferenceError:
# Reference filename is printed before this.
- self.logger.error("Missing an en-US reference file.")
+ self.logger.error(
+ "Missing an en-US reference file. Is --reference-directory correct?"
+ )
return False
# Check each transform would create the same entry in the target as the
@@ -602,7 +1030,8 @@ class TorBrowserMigrator:
reference_entry = ctx.tb_get_reference_entry(target_path, transform_id)
if reference_entry is None:
self.logger.error(
- f"Missing en-US reference entry for transform {transform_name}"
+ f"Missing en-US reference entry for transform {transform_name}. "
+ "Is --reference-directory correct?"
)
have_error = True
continue
@@ -625,9 +1054,50 @@ class TorBrowserMigrator:
return not have_error
+def main(recipe_path: str, translation_dir: str, locales: str, ref_dir: str) -> None:
+ """
+ The main method.
+ :param recipe_path: The path to the recipe script.
+ :param translation_dir: The path to the translation repository directory.
+ :param locales: The locales to run the recipe for, separated by spaces.
+ :param ref_dir: The path to the reference directory.
+ """
+ if not os.path.isfile(recipe_path):
+ print(f"{in_red(recipe_path)} is not a file.", file=sys.stderr)
+ sys.exit(1)
+
+ recipe_module_spec = importlib.util.spec_from_file_location("_recipe", recipe_path)
+ recipe_module = cast(
+ RecipeModule, importlib.util.module_from_spec(recipe_module_spec)
+ )
+ recipe_module_spec.loader.exec_module(recipe_module)
+
+ def check_dir(path: str) -> str:
+ if not os.path.isdir(path):
+ print(f"{in_red(path)} is not a directory.", file=sys.stderr)
+ sys.exit(1)
+ return path
+
+ translation_dir = check_dir(translation_dir)
+ en_US_target_dir = check_dir(os.path.join(translation_dir, "en-US"))
+ en_US_ref_dir = en_US_target_dir if ref_dir is None else check_dir(ref_dir)
+
+ TorBrowserMigrator(
+ en_US_ref_dir,
+ en_US_target_dir,
+ {
+ locale: check_dir(os.path.join(translation_dir, locale))
+ for locale in (l.strip() for l in locales.split(" "))
+ if locale
+ },
+ recipe_module,
+ WeblateMetadata(),
+ ).run()
+
+
parser = argparse.ArgumentParser(
description="Run a tor-browser localization migration. "
- "See documentation within migrate_l10n.py."
+ "See documentation within migrate.py."
)
parser.add_argument(
"--translation-git",
@@ -638,35 +1108,30 @@ parser.add_argument(
parser.add_argument(
"--locales",
required=True,
- metavar="<locale1> <locale2> ...",
- help="Set of locales to restrict the migration to, separated by space.",
+ metavar="'<locale1> <locale2> ...'",
+ help="Set of locales to run the migration for, separated by space.",
)
parser.add_argument(
- "migration",
- help="Migration to run, given as a python module. "
- 'E.g. "l10n_migrations.my-migration-script".',
+ "--reference-directory",
+ metavar="<dir>",
+ help="Location of the en-US directory that contains the reference changes "
+ "that the recipe corresponds to. E.g. if the recipe constructs the string "
+ "`my-new-string` in `./tor-browser.ftl`, it should point to a directory "
+ "that contains the en-US `tor-browser.ftl` with `my-new-string` already "
+ "within it. Defaults to the `en-US/` sub-directory within the "
+ "translation-git directory.",
+)
+parser.add_argument(
+ "recipe",
+ help="The path to the migration recipe to run.",
)
parsed_args = parser.parse_args()
-
-def check_dir(path):
- if not os.path.isdir(path):
- print(f"{in_red(path)} is not a directory.", file=sys.stderr)
- sys.exit(1)
- return path
-
-
-translation_dir = check_dir(os.path.abspath(parsed_args.translation_git))
-
-TorBrowserMigrator(
- check_dir(os.path.join(translation_dir, "en-US")),
- {
- locale: check_dir(os.path.join(translation_dir, locale))
- for locale in (l.strip() for l in parsed_args.locales.split(" "))
- if locale
- },
- importlib.import_module(parsed_args.migration),
- WeblateMetadata(),
-).run()
+main(
+ parsed_args.recipe,
+ parsed_args.translation_git,
+ parsed_args.locales,
+ parsed_args.reference_directory,
+)
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/a7d877…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/a7d877…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser] Pushed new tag tor-browser-155.0a1-17.0-1-build2
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed new tag tor-browser-155.0a1-17.0-1-build2 at The Tor Project / Applications / Tor Browser
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/tree/tor-brows…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] fixup! BB 41108: Remove privileged macOS installation
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
a7d87792 by Pier Angelo Vendrame at 2026-11-05T09:54:54+01:00
fixup! BB 41108: Remove privileged macOS installation
BB 45240 (fix): Move also an include under ifdef
- - - - -
1 changed file:
- toolkit/xre/MacRunFromDmgUtils.mm
Changes:
=====================================
toolkit/xre/MacRunFromDmgUtils.mm
=====================================
@@ -32,8 +32,10 @@
# include "nsUpdateDriver.h"
#endif
+#ifndef BASE_BROWSER_VERSION
// Exported from toolkit/mozapps/dmgInstallHelper
-#import "dmgInstallProtocol.h"
+# import "dmgInstallProtocol.h"
+#endif
#ifndef MOZ_RUNINIT
# define MOZ_RUNINIT __attribute__((annotate("moz_global_var")))
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a7d8779…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a7d8779…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 13 commits: BB 45308: Implement ./mach yeet command
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
89980175 by Beatriz Rizental at 2026-11-05T08:37:09+01:00
BB 45308: Implement ./mach yeet command
./mach yeet is the Tor Project version of try -- but much simpler.
- - - - -
7bf6dbd8 by Beatriz Rizental at 2026-11-05T08:37:09+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet auth
- - - - -
fd82e86b by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet's upload step
Uploads a local file to the configured build server's public_html
over scp.
- - - - -
6c312932 by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet remote's CI trigger
- - - - -
cdd4f1f1 by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Address review comments
- - - - -
48a32237 by Beatriz Rizental at 2026-11-05T08:37:11+01:00
fixup! BB 45308: Implement ./mach yeet command
Attend more review comments.
- - - - -
f661f0d7 by Pier Angelo Vendrame at 2026-11-05T08:37:11+01:00
fixup! TB 42669: [android] Use custom no-op app-services
- - - - -
adc63271 by Pier Angelo Vendrame at 2026-11-05T08:37:11+01:00
fixup! [android] Modify build system
- - - - -
6353e646 by Beatriz Rizental at 2026-11-05T08:37:11+01:00
fixup! TB 41089: Add tor-browser build scripts + Makefile to tor-browser
This reverts commit 5f43c88992e4b69ac03c5e40aeba08fe8d0bd56e.
- - - - -
1ce02a42 by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! TB 43564: Modify ./mach bootstrap for Tor Browser
Move NoScript gitignore statement to this commit
- - - - -
d95babfc by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! BB 45120: Add tests for Tor Browser
Bug 44820: Upstream geckoiew's own manifest requests
ACCESS_NETWORK_STATE. Tor Browser comments that line
out so geckoview doesn't ask for network-state access,
but the test app needs it. So we add it back.
- - - - -
1aaee7aa by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! TB 43817: Add tests for Tor Browser
Disable Fenix unit tests by default, since most of them
don't work in Tor Browser (some don't even compile). An
allowlist in the Fenix build.gradle controls which unit
tests are compiled and run, so they can be re-enabled as
they get fixed. When the allowlist is empty, the unit test
compile and test tasks are skipped entirely.
Also add a trivial SanityTest, enabled in the allowlist,
to make sure the unit test pipeline works.
- - - - -
ac3d0ae7 by Henry Wilkes at 2026-11-05T08:37:13+01:00
fixup! TB 41600: Add a tor circuit display panel.
TB 45398: Move tor circuit button into the identity box.
- - - - -
30 changed files:
- .gitignore
- browser/base/content/navigator-toolbox.inc.xhtml
- browser/themes/shared/identity-block/identity-block.css
- mobile/android/fenix/app/build.gradle
- + mobile/android/fenix/app/src/test/java/org/mozilla/fenix/torbrowser/SanityTest.kt
- mobile/android/geckoview/src/androidTest/AndroidManifest.xml
- python/mach/mach/command_util.py
- tools/moz.build
- − tools/torbrowser/Makefile
- − tools/torbrowser/browser-self-sign-macos.sh
- − tools/torbrowser/build.sh
- − tools/torbrowser/clobber.sh
- − tools/torbrowser/config.sh
- − tools/torbrowser/deploy.sh
- − tools/torbrowser/fetch.sh
- − tools/torbrowser/ide.sh
- − tools/torbrowser/jslint.sh
- − tools/torbrowser/prepare-tests.sh
- + tools/yeet/__init__.py
- + tools/yeet/auth.py
- + tools/yeet/common.py
- + tools/yeet/mach_commands.py
- + tools/yeet/remote.py
- + tools/yeet/tests/python/conftest.py
- + tools/yeet/tests/python/python.toml
- + tools/yeet/tests/python/test_auth.py
- + tools/yeet/tests/python/test_common.py
- + tools/yeet/tests/python/test_remote.py
- + tools/yeet/tests/python/test_upload.py
- + tools/yeet/upload.py
Changes:
=====================================
.gitignore
=====================================
@@ -430,14 +430,9 @@ CLAUDE.local.md
# lint-ignore-next-line: git-only
/*.json.gz
-# Ignore binary base of Tor Browser
-.binaries
+# GitLab project and token saved by `mach yeet auth`
+/.yeet.json
-# Other files modified at build time
-mobile/android/.experimenter.json
-
-# Tor libraries for local builds
-mobile/android/fenix/tools/nimbus-fml
-mobile/android/fenix/app/tor-expert-bundle.aar
+# Symlink to NoScript .xpi. It lives in MOZBUILD, but needs to be symlinked
+# to this path so it's added to the APK.
mobile/android/fenix/app/src/main/assets/extensions/{73a6fe31-595d-460b-a920-fcc0f8843232}.xpi
-
=====================================
browser/base/content/navigator-toolbox.inc.xhtml
=====================================
@@ -193,19 +193,6 @@
<image id="remote-control-icon"/>
</box>
- <!-- We follow the surrounding code and use a
- - <xul:box role="button"> rather than a more semantic
- - <html:button>, <xul:button> or <xul:toolbarbutton> -->
- <box id="tor-circuit-button"
- role="button"
- class="identity-box-button"
- align="center"
- data-l10n-id="tor-circuit-urlbar-button"
- urlbar-slot="site-info"
- hidden="true">
- <image id="tor-circuit-button-icon"/>
- </box>
-
<box
id="trust-icon-container"
align="center"
@@ -247,6 +234,17 @@
class="identity-box"
pageproxystate="invalid"
urlbar-slot="site-info">
+ <!-- We follow the surrounding code and use a
+ - <xul:box role="button"> rather than a more semantic
+ - <html:button>, <xul:button> or <xul:toolbarbutton> -->
+ <box id="tor-circuit-button"
+ role="button"
+ class="identity-box-button"
+ align="center"
+ data-l10n-id="tor-circuit-urlbar-button"
+ hidden="true">
+ <image id="tor-circuit-button-icon"/>
+ </box>
<!-- Shown when trustPanel.featureGate is off, or for
chromeUI/extensionPage where tracker blocking never runs, so we
never update `data-l10n-args`. -->
=====================================
browser/themes/shared/identity-block/identity-block.css
=====================================
@@ -7,7 +7,6 @@
#tracking-protection-icon-container,
#identity-box,
#trust-icon-container,
-#tor-circuit-button,
#urlbar-label-box {
height: var(--urlbar-basic-component-size);
}
@@ -33,7 +32,9 @@
/* And don't show the identity icon box in this case,
just permissions indication */
- > #identity-icon-box {
+ /* Hide the tor circuit when the identity box is also hidden.
+ * tor-browser#45398. */
+ > :is(#identity-icon-box, #tor-circuit-button) {
display: none;
}
}
=====================================
mobile/android/fenix/app/build.gradle
=====================================
@@ -717,6 +717,39 @@ protobuf {
}
}
+// Unit tests are disabled by default because most of them don't work in Tor Browser.
+// Add source path patterns here (e.g. 'org/mozilla/fenix/home/**') to re-enable them
+// as they get fixed. Only the listed tests (plus the shared helpers) are compiled and run.
+// When the list is empty, unit tests are neither compiled nor run.
+def enabledUnitTests = [
+ 'org/mozilla/fenix/torbrowser/**',
+]
+def unitTestHelpers = [
+ 'org/mozilla/fenix/helpers/**',
+]
+
+tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
+ if (name.contains("UnitTest")) {
+ if (enabledUnitTests) {
+ // The task already has default include patterns, so we can only narrow it down with excludes.
+ def allowed = new org.gradle.api.tasks.util.PatternSet()
+ .include((enabledUnitTests + unitTestHelpers).collect { "**/$it" })
+ .asSpec
+ exclude { !it.directory && !allowed.isSatisfiedBy(it) }
+ } else {
+ enabled = false
+ }
+ }
+}
+
+tasks.withType(Test).configureEach {
+ if (enabledUnitTests) {
+ include enabledUnitTests
+ } else {
+ enabled = false
+ }
+}
+
if (project.hasProperty("coverage")) {
tasks.withType(Test).configureEach {
jacoco.includeNoLocationClasses = true
=====================================
mobile/android/fenix/app/src/test/java/org/mozilla/fenix/torbrowser/SanityTest.kt
=====================================
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+package org.mozilla.fenix.torbrowser
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class SanityTest {
+ @Test
+ fun `one plus one is two`() {
+ assertEquals(2, 1 + 1)
+ }
+}
=====================================
mobile/android/geckoview/src/androidTest/AndroidManifest.xml
=====================================
@@ -4,6 +4,7 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
=====================================
python/mach/mach/command_util.py
=====================================
@@ -296,6 +296,7 @@ MACH_COMMANDS = {
"xpcshell-test": MachCommandReference(
"testing/xpcshell/mach_commands.py", ["test"]
),
+ "yeet": MachCommandReference("tools/yeet/mach_commands.py"),
}
=====================================
tools/moz.build
=====================================
@@ -75,4 +75,5 @@ PYTHON_UNITTEST_MANIFESTS += [
"lint/test/python.toml",
"tryselect/test/python.toml",
"update-packaging/test/python.toml",
+ "yeet/tests/python/python.toml",
]
=====================================
tools/torbrowser/Makefile deleted
=====================================
@@ -1,72 +0,0 @@
-.DEFAULT_GOAL := all
-
-# https://stackoverflow.com/questions/18136918/how-to-get-current-relative-di…
-mkfile_path := "$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))"
-
-DEV_ROOT = "$(mkfile_path)/../.."
-BINARIES = "$(DEV_ROOT)/.binaries"
-ARCHITECTURE = "$(shell uname -m)"
-
-# Correct the architecture naming for ARM to match what mozilla has
-ifeq ($(ARCHITECTURE), "arm64")
- ARCHITECTURE = "aarch64"
-endif
-
-ifeq ($(ARCHITECTURE), "aarch64")
- LINUX_VENDOR = "unknown"
-else
- LINUX_VENDOR = "pc"
-endif
-
-# Define build output path based on the platform.
-ifeq ("$(shell uname)", "Darwin")
- BUILD_OUTPUT = "$(DEV_ROOT)/obj-$(ARCHITECTURE)-apple-darwin$(shell uname -r)"
-else
- BUILD_OUTPUT = "$(DEV_ROOT)/obj-$(ARCHITECTURE)-$(LINUX_VENDOR)-linux-gnu"
-endif
-
-# Define the run command based on the platform.
-ifeq ("$(shell uname)", "Darwin")
- RUN_CMD := cd "$(BINARIES)/Tor Browser.app/Contents/MacOS/" && ./firefox --purgecaches
-else
- RUN_CMD := "$(BINARIES)/dev/Browser/start-tor-browser" -v --purgecaches $(ARGS)
-endif
-
-config:
- ./config.sh $(DEV_ROOT)
-
-ide-vscode:
- ./ide.sh vscode $(DEV_ROOT)
-
-ide-eclipse:
- ./ide.sh eclipse $(DEV_ROOT)
-
-ide-visualstudio:
- ./ide.sh visualstudio $(DEV_ROOT)
-
-fetch:
- ./fetch.sh $(BINARIES)
-
-build:
- ./build.sh $(DEV_ROOT)
-
-deploy:
- ./deploy.sh $(BINARIES) $(BUILD_OUTPUT)
-
-prepare-tests:
- ./prepare-tests.sh $(BINARIES) $(BUILD_OUTPUT)
-
-all: build deploy
-
-run:
- $(RUN_CMD)
-
-jslint:
- ./jslint.sh $(DEV_ROOT) $(JS)
-
-clobber:
- ./clobber.sh $(DEV_ROOT)
-
-clean:
- rm -rf $(BUILD_OUTPUT)
-
=====================================
tools/torbrowser/browser-self-sign-macos.sh deleted
=====================================
@@ -1,110 +0,0 @@
-#!/bin/bash
-
-CERTNAME=my-codesign-cert-tor
-BROWSERPATH=.
-
-if [ $# -ge 1 ]
-then
- BROWSERPATH=$1
-fi
-
-
-security find-certificate -c $CERTNAME > /dev/null
-
-if [ $? -ne 0 ]
-then
- echo ""
- echo "ERROR: Self Signing Certificate not found, please create:"
- echo " 1. In the Keychain Access app on your Mac, choose Keychain Access > Certificate Assistant > Create a Certificate."
- echo " 2. Enter the name '$CERTNAME' for the certificate"
- echo " 3. Choose an identity type: Self Signed Root"
- echo " 4. Certificate Type > Code Signing"
- echo " 5. Check 'Let me override defaults' & click Continue."
- echo " 6. Enter a unique Serial Number. (123 is fine)"
- echo " 7. Enter a big Validity Period (days), like 3560 & click Continue."
- echo " 8. Fill in your personal information & click Continue."
- echo " 9. Accept defaults for the rest of the dialog boxes. (Continue several times)"
- echo " 10. Certificate Created! Click Done."
- echo ""
- echo "For additional help see:"
- echo " https://support.apple.com/en-ca/guide/keychain-access/kyca8916/mac"
- echo " https://stackoverflow.com/questions/58356844/what-are-the-ways-or-technolog…"
-
- echo ""
- read -n 1 -r -s -p $'Press enter to launch "Keychain Access"...\n'
- open /System/Applications/Utilities/Keychain\ Access.app
-
- exit -1
-fi
-
-echo "Found $CERTNAME, looking for browser to sign..."
-
-if [ ! -f "$BROWSERPATH/XUL" ]
-then
- TESTPATH="$BROWSERPATH/Contents/MacOS"
- if [ -f "$TESTPATH/XUL" ]
- then
- BROWSERPATH=$TESTPATH
- else
- echo "Error: browser files not detected in $BROWSERPATH!"
- echo " This script needs to be run in the 'Contents/MacOS' directory of a SomeBrowser.app directory"
- exit -1
- fi
-fi
-
-echo "Mozilla based browser found, signing..."
-echo ' Will be asked for password to certificate for all the things that need to be signed. Click "Always Allow" to automate'
-
-cd "$BROWSERPATH"
-
-codesign -s $CERTNAME *.dylib
-codesign -s $CERTNAME plugin-container.app
-
-if [ -d Tor ]
-then
- codesign -s $CERTNAME Tor/PluggableTransports/*
- codesign -s $CERTNAME Tor/libevent-2.1.7.dylib
- if [ -f Tor/tor.real ]
- then
- codesign -s $CERTNAME Tor/tor.real
- fi
- if [ -f Tor/tor ]
- then
- codesign -s $CERTNAME Tor/tor
- fi
-fi
-
-codesign -s $CERTNAME XUL
-
-if [ -d updater.app ]
-then
- codesign -s $CERTNAME updater.app
-fi
-
-# mullvadbrowser
-if [ -f mullvadbrowser ]
-then
- codesign -s $CERTNAME mullvadbrowser
-fi
-
-# BB or TB
-if [ -f firefox ]
-then
- codesign -s $CERTNAME firefox
-fi
-
-echo ""
-echo "Browser signing step done!"
-echo ""
-
-echo "App still needs one more override to be easily opened with double click in Finder"
-echo "Alternatively you can right click it, select 'Open' and then select 'Open' from the override popup"
-echo "Or to enable it to be double clicked to open perform the following"
-echo ""
-echo "Double click the app and select either 'Ok' or 'Cancel' from the warning popup depending on which you get (Do Not 'Move to Trash')"
-echo 'Go to Preferences -> Security & Privacy and click on padlock to allow changes. '
-echo ' Then in "Allow appications downloaded from" select either:'
-echo ' - App Store and identified developers'
-echo ' - Anywhere'
-echo ' Below that may be a notice about your specific app saying it was blocked because it was not from an identified developer. Click "Open Anyways" and "Open"'
-
=====================================
tools/torbrowser/build.sh deleted
=====================================
@@ -1,15 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach build
-
-if [ -z "$LOCALES" ]; then
- ./mach build stage-package
-else
- export MOZ_CHROME_MULTILOCALE=$LOCALES
- # No quotes on purpose
- ./mach package-multi-locale --locales en-US $MOZ_CHROME_MULTILOCALE
- AB_CD=multi ./mach build stage-package
-fi
=====================================
tools/torbrowser/clobber.sh deleted
=====================================
@@ -1,6 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach clobber
=====================================
tools/torbrowser/config.sh deleted
=====================================
@@ -1,6 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach configure
=====================================
tools/torbrowser/deploy.sh deleted
=====================================
@@ -1,43 +0,0 @@
-#!/bin/bash
-set -e
-
-BINARIES="$1"
-BUILD_OUTPUT="$2"
-SCRIPT_DIR="$(realpath "$(dirname "$0")")"
-
-RESDIR="$BUILD_OUTPUT/dist/firefox"
-if [ "$(uname)" = "Darwin" ]; then
- RESDIR="$RESDIR/Tor Browser.app/Contents/Resources"
-fi
-
-# Repackage the manual
-# rm -rf $BUILD_OUTPUT/_omni
-# mkdir $BUILD_OUTPUT/_omni
-# unzip $BINARIES/dev/Browser/browser/omni.ja -d $BUILD_OUTPUT/_omni
-# cd $BUILD_OUTPUT/_omni && zip -Xmr $RESDIR/browser/omni.ja chrome/browser/content/browser/manual
-# rm -rf $BUILD_OUTPUT/_omni
-
-if [ "$(uname)" = "Darwin" ]; then
-
- # copy binaries
- cp -r "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/* "$BINARIES/Tor Browser.app/Contents/"
- rm -rf "$BINARIES/TorBrowser-Data/Browser/Caches/*.default/startupCache"
-
- # Self sign the Binaries
- cd "$BINARIES/Tor Browser.app/Contents/MacOS"
- "$SCRIPT_DIR/browser-self-sign-macos.sh"
-
-else
-
- # backup the startup script
- mv "$BINARIES/dev/Browser/firefox" "$BINARIES/dev/Browser/firefox.bak"
-
- # copy binaries
- cp -r "$RESDIR/"* "$BINARIES/dev/Browser"
- rm -rf "$BINARIES/dev/Browser/TorBrowser/Data/Browser/profile.default/startupCache"
-
- # shuffle firefox bin around and restore script to match a real deployment
- mv "$BINARIES/dev/Browser/firefox" "$BINARIES/dev/Browser/firefox.real"
- mv "$BINARIES/dev/Browser/firefox.bak" "$BINARIES/dev/Browser/firefox"
-
-fi
=====================================
tools/torbrowser/fetch.sh deleted
=====================================
@@ -1,40 +0,0 @@
-#!/bin/sh
-set -e
-
-BINARIES_DIR="$1"
-
-# download the current downloads.json
-wget https://aus1.torproject.org/torbrowser/update_3/alpha/downloads.json
-# get url for latest alpha linux package
-TOR_BROWSER_VERSION=$(grep -Eo "\"version\"\s*:\s*\"[0-9.a]+\"" downloads.json | grep -Eo "[0-9.a]+")
-if [ "$(uname)" = "Darwin" ]; then
- TOR_BROWSER_PACKAGE="tor-browser-macos-${TOR_BROWSER_VERSION}.dmg"
- else
- TOR_BROWSER_PACKAGE="tor-browser-linux-$(uname -m)-${TOR_BROWSER_VERSION}.tar.xz"
-fi
-TOR_BROWSER_PACKAGE_URL="https://dist.torproject.org/torbrowser/${TOR_BROWSER_VERSION}/${TOR_BROWSER…"
-
-# remove download manifest
-rm downloads.json
-
-# clear out previous tor-browser and previous package
-rm -rf "${BINARIES_DIR}"
-rm -f "${TOR_BROWSER_PACKAGE}"
-
-# download
-wget "${TOR_BROWSER_PACKAGE_URL}"
-mkdir -p "${BINARIES_DIR}"
-
-# and extract
-if [ "$(uname)" = "Darwin" ]
- then
- hdiutil attach "${TOR_BROWSER_PACKAGE}"
- cp -R "/Volumes/Tor Browser Alpha/Tor Browser Alpha.app" "${BINARIES_DIR}/Tor Browser.app"
- hdiutil detach "/Volumes/Tor Browser Alpha"
- else
- tar -xf "${TOR_BROWSER_PACKAGE}" -C "${BINARIES_DIR}"
- mv "${BINARIES_DIR}/tor-browser" "${BINARIES_DIR}/dev"
-fi
-
-# Final cleanup
-rm -f "${TOR_BROWSER_PACKAGE}"
=====================================
tools/torbrowser/ide.sh deleted
=====================================
@@ -1,7 +0,0 @@
-#!/bin/bash
-set -e
-IDE=$1
-DEV_ROOT=$2
-
-cd $DEV_ROOT
-./mach ide $IDE
=====================================
tools/torbrowser/jslint.sh deleted
=====================================
@@ -1,7 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-JS_FILE=$2
-
-cd $DEV_ROOT
-./mach lint -l eslint --fix $JS_FILE
=====================================
tools/torbrowser/prepare-tests.sh deleted
=====================================
@@ -1,25 +0,0 @@
-#!/bin/sh
-set -e
-
-BINARIES="$1"
-BUILD_OUTPUT="$2"
-
-if [ ! -d "$BUILD_OUTPUT" ]; then
- echo "Error: $BUILD_OUTPUT directory does not exist."
- echo "Make sure to run `mach ./build` or `make -C tools/torbrowser build`."
- exit 1
-fi
-
-if [ ! -d "$BINARIES" ]; then
- echo "Error: $BINARIES directory does not exist."
- echo "Make sure to run `make -C tools/torbrowser fetch`."
- exit 1
-fi
-
-if [ "$(uname)" = "Darwin" ]; then
- cp -r "$BINARIES/Tor Browser.app/Contents/MacOS/Tor" "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/MacOS
- cp -r "$BINARIES/Tor Browser.app/Contents/Resources/fonts" "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/Resources
-else
- cp -r "$BINARIES/dev/Browser/fonts" "$BUILD_OUTPUT/dist/bin"
- cp -r "$BINARIES/dev/Browser/TorBrowser" "$BUILD_OUTPUT/dist/bin"
-fi
=====================================
tools/yeet/__init__.py
=====================================
@@ -0,0 +1,3 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
=====================================
tools/yeet/auth.py
=====================================
@@ -0,0 +1,264 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import os
+import subprocess
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+from yeet.common import (
+ CANONICAL_GITLAB_PROJECT,
+ CANONICAL_GITLAB_REPO_NAME,
+ DEFAULT_SSH_HOST,
+ GITLAB_API_BASE,
+ TERM,
+ YEET_CONFIG_FILENAME,
+ prompt,
+)
+
+
+def _resolve_project(raw_username):
+ """Build a fork project path out of a GitLab username. Raises ValueError
+ if it's empty or the canonical repo's own namespace.
+ """
+ username = raw_username.strip()
+ if not username:
+ raise ValueError("A GitLab username is required.")
+
+ project = f"{username}/{CANONICAL_GITLAB_REPO_NAME}"
+ if project.lower() == CANONICAL_GITLAB_PROJECT.lower():
+ raise ValueError(
+ "That's the canonical repo's namespace, not a fork. Use your "
+ "own GitLab username instead."
+ )
+
+ return project
+
+
+def _prompt_fork():
+ print()
+ print(
+ TERM.yellow(
+ f"""`mach yeet remote` runs against your own fork of
+{CANONICAL_GITLAB_PROJECT}, never against the canonical repo
+directly -- that keeps CI runs off the shared project.
+
+If you haven't forked it yet, fork it first at:
+ https://gitlab.torproject.org/{CANONICAL_GITLAB_PROJECT}/-/forks/new
+
+Keep your fork up to date too. An outdated fork's .gitlab-ci.yml may be missing
+pieces this command relies on, so pipelines could fail or come back empty."""
+ )
+ )
+ print()
+
+ while True:
+ try:
+ return _resolve_project(prompt("Your GitLab username: "))
+ except ValueError as e:
+ print(TERM.red(f"ERROR! {e}"))
+
+
+def _gitlab_token_instructions(project):
+ return f"""
+Now you need a pipeline trigger token for your fork:
+ {project}
+
+This is NOT a personal access token -- it's specific to this one project, and
+it's the only kind that can actually run CI jobs here (their rules require it):
+
+ 1. Go to https://gitlab.torproject.org/{project}/-/settings/ci_cd#js-pipeline-trigge…
+ 2. Expand "Pipeline trigger tokens" and add a new one.
+ 3. Paste the token below.
+
+The project and token will be saved to {YEET_CONFIG_FILENAME} at the root of the repository
+and are not committed to it.
+""".strip()
+
+
+def _print_ssh_instructions():
+ print()
+ print(
+ TERM.yellow(
+ f"""`mach yeet` also uploads to and runs commands on a build server over SSH
+({DEFAULT_SSH_HOST} by default). Uploaded files are served from your
+account's public_html there, at:
+ https://<host>/~<username>
+
+Anything special about the connection -- port, jump host, a hardware key's
+PKCS11 provider, agent forwarding -- belongs in your ~/.ssh/config, not here:
+we just shell out to `ssh`. Whatever already works on your command line works
+for `mach yeet` too."""
+ )
+ )
+ print()
+
+
+def _prompt_ssh_host():
+ return prompt(f"SSH host [{DEFAULT_SSH_HOST}]: ").strip() or DEFAULT_SSH_HOST
+
+
+def _prompt_ssh_username(ssh_host):
+ while True:
+ username = prompt(f"Your username on {ssh_host}: ").strip()
+ if username:
+ return username
+ print(TERM.red("ERROR! Username cannot be empty."))
+
+
+def _prompt_token():
+ while True:
+ token = prompt("GitLab token: ", secret=True).strip()
+ if token:
+ return token
+ print(TERM.red("ERROR! Token cannot be empty."))
+
+
+def _verify_ssh(target):
+ """Try an actual SSH connection. stdin is /dev/null so ssh can't swallow
+ input buffered for us; its touch/PIN/passphrase prompts go through
+ /dev/tty and still reach the user.
+ """
+ try:
+ result = subprocess.run(
+ ["ssh", target, "true"],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ except FileNotFoundError:
+ print()
+ print(TERM.red("ERROR! No `ssh` binary found on PATH."))
+ return False
+ return result.returncode == 0
+
+
+def _verify_auth(project, token):
+ """Check that `project`/`token` are accepted by GitLab, without
+ actually triggering a pipeline.
+
+ GitLab authenticates the trigger token before validating the rest of
+ the request, so posting to the trigger endpoint without the required
+ `ref` param never queues a pipeline: a valid token/project combination
+ gets rejected with 400 (missing ref) instead, while an invalid token
+ or unknown project is rejected with 401/404 before `ref` is even
+ looked at.
+ """
+ url = f"{GITLAB_API_BASE}/projects/{urllib.parse.quote(project, safe='')}/trigger/pipeline"
+ data = urllib.parse.urlencode({"token": token}).encode()
+ request = urllib.request.Request(url, data=data, method="POST")
+ try:
+ with urllib.request.urlopen(request):
+ pass
+ except urllib.error.HTTPError as e:
+ return e.code == 400
+ else:
+ return True
+
+
+def run(command_context, **kwargs):
+ gitlab_username = kwargs.get("gitlab_username")
+ if gitlab_username is not None:
+ try:
+ project = _resolve_project(gitlab_username)
+ except ValueError as e:
+ print(TERM.red(f"ERROR! --gitlab-username: {e}"))
+ return 1
+ else:
+ project = _prompt_fork()
+
+ gitlab_token = kwargs.get("gitlab_token")
+ if gitlab_token is not None:
+ token = gitlab_token.strip()
+ if not token:
+ print()
+ print(TERM.red("ERROR! --gitlab-token was empty."))
+ return 1
+ else:
+ print()
+ print(_gitlab_token_instructions(project))
+ print()
+ token = _prompt_token()
+
+ verify = kwargs.get("verify", True)
+ if verify:
+ print()
+ print("Verifying credentials with GitLab...")
+ try:
+ verified = _verify_auth(project, token)
+ except urllib.error.URLError as e:
+ print()
+ print(TERM.red(f"ERROR! Could not reach GitLab: {e}"))
+ return 1
+
+ if not verified:
+ print()
+ print(
+ TERM.red(
+ "ERROR! GitLab rejected that project/token combination. "
+ "Double-check the fork name and the trigger token."
+ )
+ )
+ return 1
+ print(TERM.green("Credentials verified."))
+
+ ssh_host = kwargs.get("ssh_host")
+ ssh_username = kwargs.get("ssh_username")
+ if ssh_host is None or ssh_username is None:
+ _print_ssh_instructions()
+
+ if ssh_host is not None:
+ ssh_host = ssh_host.strip()
+ if not ssh_host:
+ print()
+ print(TERM.red("ERROR! --ssh-host was empty."))
+ return 1
+ else:
+ ssh_host = _prompt_ssh_host()
+
+ if ssh_username is not None:
+ ssh_username = ssh_username.strip()
+ if not ssh_username:
+ print()
+ print(TERM.red("ERROR! --ssh-user was empty."))
+ return 1
+ else:
+ ssh_username = _prompt_ssh_username(ssh_host)
+
+ if verify:
+ ssh_target = f"{ssh_username}@{ssh_host}"
+ print()
+ print(f"Verifying SSH access to {ssh_target}...")
+ if not _verify_ssh(ssh_target):
+ print()
+ print(
+ TERM.red(
+ f"ERROR! Could not SSH into {ssh_target}. Make sure you "
+ "can `ssh` there yourself first."
+ )
+ )
+ return 1
+ print(TERM.green("SSH access verified."))
+
+ tokens_path = Path(command_context.topsrcdir) / YEET_CONFIG_FILENAME
+ file_desc = os.open(
+ tokens_path, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=0o600
+ )
+ with open(file_desc, "w") as f:
+ json.dump(
+ {
+ "project": project,
+ "token": token,
+ "ssh_host": ssh_host,
+ "ssh_user": ssh_username,
+ },
+ f,
+ )
+ os.chmod(tokens_path, 0o600)
+
+ print()
+ print(TERM.green(f"Saved to {tokens_path}"))
+ return 0
=====================================
tools/yeet/common.py
=====================================
@@ -0,0 +1,66 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import getpass
+import json
+import sys
+from pathlib import Path
+
+from mozterm import Terminal
+
+TERM = Terminal()
+
+GITLAB_API_BASE = "https://gitlab.torproject.org/api/v4"
+
+# The canonical repo. `mach yeet remote` must never target this directly --
+# only a fork of it, so CI runs don't pile up on the shared project.
+CANONICAL_GITLAB_NAMESPACE = "tpo/applications"
+CANONICAL_GITLAB_REPO_NAME = "tor-browser-bundle-testsuite"
+CANONICAL_GITLAB_PROJECT = f"{CANONICAL_GITLAB_NAMESPACE}/{CANONICAL_GITLAB_REPO_NAME}"
+
+# Project and token saved by `mach yeet auth`.
+YEET_CONFIG_FILENAME = ".yeet.json"
+
+# The default server `mach yeet` uploads to and runs commands on over SSH.
+# Uploaded files are served from the user's public_html on it.
+DEFAULT_SSH_HOST = "tb-build-03.torproject.org"
+
+
+def prompt(message, secret=False):
+ """Read a line of user input, first discarding anything typed before the
+ prompt appeared so stray keystrokes aren't taken as the answer.
+ """
+ if sys.stdin.isatty():
+ try:
+ import termios
+
+ termios.tcflush(sys.stdin, termios.TCIFLUSH)
+ except ImportError:
+ pass
+ if secret:
+ return getpass.getpass(message)
+ return input(message)
+
+
+def confirm(message):
+ """Ask a yes/no question, defaulting to no, until a valid answer is given."""
+ while True:
+ answer = prompt(f"{message} [y/N]: ").strip().lower()
+ if answer in ("y", "yes"):
+ return True
+ if answer in ("", "n", "no"):
+ return False
+ print(TERM.red("ERROR! Please answer 'y' or 'n'."))
+
+
+def read_config(topsrcdir):
+ """Read the project/token/ssh_* config saved by `mach yeet auth`, or
+ None if it hasn't been run yet.
+ """
+ config_path = Path(topsrcdir) / YEET_CONFIG_FILENAME
+ if not config_path.is_file():
+ return None
+
+ with open(config_path) as f:
+ return json.load(f)
=====================================
tools/yeet/mach_commands.py
=====================================
@@ -0,0 +1,141 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from mach.decorators import Command, CommandArgument, SubCommand # noqa: I001
+
+from yeet import remote
+
+
+@Command(
+ "yeet",
+ category="ci",
+ description="TODO: build / test remotely from the current state of the repo.",
+)
+def yeet(command_context):
+ # TODO: this will be the main "yeet" command -- push, build and (maybe)
+ # test remotely from the current state of the local repo, rather than
+ # requiring an already-published build like `yeet remote` does.
+ pass
+
+
+@SubCommand(
+ "yeet",
+ "remote",
+ description="Trigger a tor-browser-bundle-testsuite CI job against an "
+ "already-published build, for a single platform.",
+)
+@CommandArgument(
+ "--platform",
+ default=None,
+ choices=remote.PLATFORMS,
+ help="Platform to test. Prompted for if not provided.",
+)
+@CommandArgument(
+ "--channel",
+ default=None,
+ choices=remote.ANDROID_CHANNELS,
+ help="Android build channel/flavor to install (only used with "
+ "--platform android_x86_64). Prompted for if not provided.",
+)
+@CommandArgument(
+ "installer_url",
+ help="URL of the installer to test, or a local file path to upload first.",
+)
+@CommandArgument(
+ "--sha256sums-url", default=None, help="URL of the build's sha256sums file."
+)
+@CommandArgument(
+ "--artifacts-url",
+ default=None,
+ help="URL of the build's artifacts directory. Inferred from the "
+ "in-tree browser version and --platform if not provided.",
+)
+@CommandArgument(
+ "--mozharness-url",
+ default=None,
+ help="URL of the mozharness.zip to use. Inferred from the in-tree "
+ "browser version and --platform if not provided.",
+)
+@CommandArgument(
+ "--version",
+ default=None,
+ help="Browser version to use when inferring --artifacts-url and "
+ "--mozharness-url. Defaults to the in-tree version "
+ "(browser/config/version.txt).",
+)
+@CommandArgument(
+ "--ref",
+ default="main",
+ help="tor-browser-bundle-testsuite ref to run on. Must have a "
+ ".gitlab-ci.yml, which the default branch may not.",
+)
+@CommandArgument(
+ "--tag",
+ dest="tags",
+ action="append",
+ default=None,
+ help="Test tag to filter tests by (can be passed multiple times, e.g. "
+ "--tag tor --tag base-browser). Defaults to '--tag tor --tag base-browser'.",
+)
+@CommandArgument(
+ "--dry-run",
+ action="store_true",
+ default=False,
+ help="Print the curl command instead of triggering the pipeline.",
+)
+@CommandArgument(
+ "--yes",
+ "-y",
+ dest="assume_yes",
+ action="store_true",
+ default=False,
+ help="Upload a local installer without asking for confirmation.",
+)
+def yeet_remote(command_context, **kwargs):
+ # With action="append", argparse appends to a non-None default instead of
+ # replacing it, so the default tags are applied here only if none were given.
+ if kwargs["tags"] is None:
+ kwargs["tags"] = ["tor", "base-browser"]
+ return remote.run(command_context, **kwargs)
+
+
+@SubCommand(
+ "yeet",
+ "auth",
+ description="Save a GitLab project and access token for running CI jobs.",
+)
+@CommandArgument(
+ "--no-verify",
+ dest="verify",
+ action="store_false",
+ help="Skip checking the GitLab and SSH credentials before saving them.",
+)
+@CommandArgument(
+ "--gitlab-username",
+ default=None,
+ help="GitLab username to use, skipping that prompt.",
+)
+@CommandArgument(
+ "--gitlab-token",
+ default=None,
+ help=(
+ "GitLab pipeline trigger token to use, skipping that prompt. Note "
+ "this may end up in your shell history."
+ ),
+)
+@CommandArgument(
+ "--ssh-user",
+ dest="ssh_username",
+ default=None,
+ help="Username on the build server, skipping that prompt.",
+)
+@CommandArgument(
+ "--ssh-host",
+ default=None,
+ help="Build server to upload to and run commands on over SSH, skipping that prompt.",
+)
+def yeet_auth(command_context, **kwargs):
+ from yeet import auth
+
+ return auth.run(command_context, **kwargs)
=====================================
tools/yeet/remote.py
=====================================
@@ -0,0 +1,228 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import os
+import shlex
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from yeet import upload
+from yeet.common import (
+ GITLAB_API_BASE,
+ TERM,
+ prompt,
+ read_config,
+)
+
+PLATFORM_TOOLCHAIN_DIR = {
+ "debian_x86_64": "linux-x86_64",
+ "windows_x86_64": "windows-x86_64",
+ "macos_x86_64": "macos-x86_64",
+ "android_x86_64": "android-x86_64",
+}
+
+PLATFORMS = list(PLATFORM_TOOLCHAIN_DIR.keys())
+
+GITLAB_REQUEST_TIMEOUT_SECONDS = 30
+
+TOOLCHAINS_URL_BASE = "https://nightlies.tbb.torproject.org/nightly-builds/toolchains"
+
+# Each Android build channel/flavor ships under its own package name, so the
+# pipeline needs to be told which one to install.
+ANDROID_CHANNEL_PACKAGE_NAMES = {
+ "debug": "org.torproject.torbrowser_debug",
+ "nightly": "org.torproject.torbrowser_nightly",
+ "alpha": "org.torproject.torbrowser_alpha",
+ "release": "org.torproject.torbrowser",
+}
+ANDROID_CHANNELS = list(ANDROID_CHANNEL_PACKAGE_NAMES)
+
+
+def _read_browser_version(topsrcdir):
+ version_path = os.path.join(topsrcdir, "browser", "config", "version.txt")
+ with open(version_path) as f:
+ return f.read().strip()
+
+
+def _resolve_version(topsrcdir, version):
+ if version:
+ return version
+
+ version = _read_browser_version(topsrcdir)
+ print(
+ TERM.yellow(
+ f"""Inferred platform version {version} from browser/config/version.txt.
+Pass --version if this isn't the version you want to test."""
+ )
+ )
+ return version
+
+
+def _artifacts_url(version, platform):
+ return f"{TOOLCHAINS_URL_BASE}/{version}/{PLATFORM_TOOLCHAIN_DIR[platform]}/"
+
+
+def _mozharness_url(version, platform):
+ return f"{_artifacts_url(version, platform)}mozharness.zip"
+
+
+def _curl_command(url, headers, data):
+ args = ["curl", "--request", "POST"]
+ for name, value in headers.items():
+ args += ["--header", f"{name}: {value}"]
+ args += ["--data", data.decode("utf-8"), url]
+ return shlex.join(args)
+
+
+def _resolve_installer_url(topsrcdir, installer, platform, assume_yes, dry_run):
+ """Accept either an installer URL directly, or a local file path to
+ upload first. On a dry run a local file is not uploaded, and a
+ placeholder URL is returned instead. Raises whatever
+ `upload.run` raises on failure.
+ """
+ if urllib.parse.urlparse(installer).scheme in ("http", "https"):
+ return installer
+ if dry_run:
+ file_path = upload.resolve_file(installer)
+ print(TERM.yellow(f"Dry run: not uploading {file_path}."))
+ return f"<URL of uploaded {file_path.name}>"
+ return upload.run(topsrcdir, installer, platform, assume_yes=assume_yes)
+
+
+def _prompt_platform():
+ print()
+ print(
+ TERM.bold(
+ "Select the platform you are testing for (if not listed, tests are not supported yet):"
+ )
+ )
+ for i, platform in enumerate(PLATFORMS, 1):
+ print(f" {TERM.cyan(str(i))}) {platform}")
+ print()
+
+ while True:
+ choice = prompt(f"Platform [1-{len(PLATFORMS)}]: ").strip()
+ if choice.isdigit() and 1 <= int(choice) <= len(PLATFORMS):
+ print()
+ return PLATFORMS[int(choice) - 1]
+ print(TERM.red(f"ERROR! Please enter a number between 1 and {len(PLATFORMS)}."))
+
+
+def _prompt_channel():
+ print()
+ print(TERM.bold("Select the Android build channel/flavor you are testing:"))
+ for i, channel in enumerate(ANDROID_CHANNELS, 1):
+ print(f" {TERM.cyan(str(i))}) {channel}")
+ print()
+
+ while True:
+ choice = prompt(f"Channel [1-{len(ANDROID_CHANNELS)}]: ").strip()
+ if choice.isdigit() and 1 <= int(choice) <= len(ANDROID_CHANNELS):
+ print()
+ return ANDROID_CHANNELS[int(choice) - 1]
+ print(
+ TERM.red(
+ f"ERROR! Please enter a number between 1 and {len(ANDROID_CHANNELS)}."
+ )
+ )
+
+
+def run(command_context, **kwargs):
+ # TODO(tor-browser-bundle-testsuite#40120): this runs whatever the pipeline
+ # runs, indiscriminately -- fine for now since marionette is the only suite
+ # it has, but once others (xpcshell, cppunittest, mochitest, ...) exist, add
+ # a --suite argument here and thread it into `inputs` so a run can be scoped
+ # to just one.
+ config = read_config(command_context.topsrcdir)
+ if config is None:
+ print(TERM.red("No GitLab fork/token found, run `mach yeet auth` first."))
+ return 1
+
+ installer_url = kwargs["installer_url"].strip()
+ if not installer_url:
+ print(TERM.red("ERROR! The installer URL or path was empty."))
+ return 1
+
+ platform = kwargs.get("platform") or _prompt_platform()
+ dry_run = kwargs.get("dry_run", False)
+
+ try:
+ installer_url = _resolve_installer_url(
+ command_context.topsrcdir,
+ installer_url,
+ platform,
+ kwargs.get("assume_yes", False),
+ dry_run,
+ )
+ except (FileNotFoundError, RuntimeError) as e:
+ print()
+ print(TERM.red(f"ERROR! {e}"))
+ return 1
+
+ package_name = None
+ if platform == "android_x86_64":
+ channel = kwargs.get("channel") or _prompt_channel()
+ if channel not in ANDROID_CHANNEL_PACKAGE_NAMES:
+ print(TERM.red(f"ERROR! Unknown channel {channel!r}."))
+ return 1
+ package_name = ANDROID_CHANNEL_PACKAGE_NAMES[channel]
+
+ artifacts_url = kwargs.get("artifacts_url")
+ mozharness_url = kwargs.get("mozharness_url")
+ if not artifacts_url or not mozharness_url:
+ version = _resolve_version(command_context.topsrcdir, kwargs.get("version"))
+ if not artifacts_url:
+ artifacts_url = _artifacts_url(version, platform)
+ if not mozharness_url:
+ mozharness_url = _mozharness_url(version, platform)
+
+ inputs = {
+ "mozharness_url": mozharness_url,
+ f"{platform}_installer_url": installer_url,
+ f"{platform}_artifacts_url": artifacts_url,
+ }
+ if package_name:
+ inputs[f"{platform}_package_name"] = package_name
+ if sha256sums_url := kwargs.get("sha256sums_url"):
+ inputs[f"{platform}_sha256sums_url"] = sha256sums_url
+ if tags := kwargs.get("tags"):
+ inputs["tags"] = shlex.join(arg for tag in tags for arg in ("--tag", tag))
+
+ project_id = urllib.parse.quote(config["project"], safe="")
+ url = f"{GITLAB_API_BASE}/projects/{project_id}/trigger/pipeline"
+ headers = {"Content-Type": "application/json"}
+ data = json.dumps({
+ "token": config["token"],
+ "ref": kwargs.get("ref", "main"),
+ "inputs": inputs,
+ }).encode("utf-8")
+
+ if dry_run:
+ print()
+ print(TERM.cyan(_curl_command(url, headers, data)))
+ print()
+ return 0
+
+ request = urllib.request.Request(url, data=data, headers=headers, method="POST")
+
+ try:
+ with urllib.request.urlopen(
+ request, timeout=GITLAB_REQUEST_TIMEOUT_SECONDS
+ ) as response:
+ result = json.load(response)
+ except urllib.error.HTTPError as e:
+ body = e.read().decode("utf-8", "replace")
+ print(
+ TERM.red(f"ERROR! Failed to trigger pipeline: {e.code} {e.reason}\n{body}")
+ )
+ return 1
+ except urllib.error.URLError as e:
+ print(TERM.red(f"ERROR! Could not reach GitLab: {e}"))
+ return 1
+
+ print()
+ print(TERM.green(f"Pipeline triggered: {result.get('web_url')}"))
+ return 0
=====================================
tools/yeet/tests/python/conftest.py
=====================================
@@ -0,0 +1,23 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+
+from yeet import common # noqa: E402
+
+
+def write_config(tmp_path, **overrides):
+ """Write a `.yeet.json` under `tmp_path`, as `mach yeet auth` would,
+ for tests that need one already in place.
+ """
+ config = {
+ "project": "bea/tor-browser-bundle-testsuite",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+ config.update(overrides)
+ with open(tmp_path / common.YEET_CONFIG_FILENAME, "w") as f:
+ json.dump(config, f)
+ return config
=====================================
tools/yeet/tests/python/python.toml
=====================================
@@ -0,0 +1,10 @@
+[DEFAULT]
+subsuite = "base-browser"
+
+["test_auth.py"]
+
+["test_upload.py"]
+
+["test_remote.py"]
+
+["test_common.py"]
=====================================
tools/yeet/tests/python/test_auth.py
=====================================
@@ -0,0 +1,435 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import urllib.error
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from yeet import auth, common
+
+
+def _set_inputs(monkeypatch, *values):
+ values = iter(values)
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+
+def _forbid_prompts(monkeypatch):
+ """Make input()/getpass() blow up instead of hanging, so a test can
+ assert that a fully non-interactive call never prompts."""
+
+ def _fail(prompt=""):
+ raise AssertionError(f"unexpected prompt: {prompt!r}")
+
+ monkeypatch.setattr("builtins.input", _fail)
+ monkeypatch.setattr(common.getpass, "getpass", _fail)
+
+
+(a)pytest.mark.parametrize("value", ["bea", " bea ", "bea.b", "bea_b-1"])
+def test_resolve_project_accepts_username(value):
+ project = auth._resolve_project(value)
+
+ assert project == f"{value.strip()}/{common.CANONICAL_GITLAB_REPO_NAME}"
+
+
+(a)pytest.mark.parametrize(
+ "value",
+ [
+ common.CANONICAL_GITLAB_NAMESPACE,
+ common.CANONICAL_GITLAB_NAMESPACE.upper(),
+ f" {common.CANONICAL_GITLAB_NAMESPACE} ",
+ ],
+)
+def test_resolve_project_rejects_canonical_namespace(value):
+ with pytest.raises(ValueError, match="canonical"):
+ auth._resolve_project(value)
+
+
+def test_resolve_project_accepts_top_level_group_of_canonical_namespace():
+ group = common.CANONICAL_GITLAB_NAMESPACE.split("/", 1)[0]
+
+ assert auth._resolve_project(group) == (
+ f"{group}/{common.CANONICAL_GITLAB_REPO_NAME}"
+ )
+
+
+def test_prompt_fork_rejects_canonical_namespace(monkeypatch, capsys):
+ canonical_namespace = common.CANONICAL_GITLAB_NAMESPACE
+ _set_inputs(monkeypatch, canonical_namespace, "bea")
+
+ project = auth._prompt_fork()
+
+ assert project == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+ assert "not a" in capsys.readouterr().out.lower()
+
+
+(a)pytest.mark.parametrize("value", ["", " ", "\t\n"])
+def test_resolve_project_rejects_blank_username(value):
+ with pytest.raises(ValueError):
+ auth._resolve_project(value)
+
+
+def test_prompt_fork_rejects_empty_username(monkeypatch):
+ _set_inputs(monkeypatch, "", " \t ", "bea")
+
+ project = auth._prompt_fork()
+
+ assert project == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+
+
+(a)pytest.mark.parametrize("status", [400])
+def test_verify_auth_accepts_valid_token(monkeypatch, status):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.HTTPError("url", status, "msg", None, None)
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ assert auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok") is True
+
+
+(a)pytest.mark.parametrize("status", [401, 404])
+def test_verify_auth_rejects_bad_token_or_project(monkeypatch, status):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.HTTPError("url", status, "msg", None, None)
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ assert auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok") is False
+
+
+def test_verify_auth_propagates_network_errors(monkeypatch):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ with pytest.raises(urllib.error.URLError):
+ auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok")
+
+
+def test_verify_ssh_success(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs))
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(auth.subprocess, "run", fake_run)
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is True
+ cmd, kwargs = calls[0]
+ assert cmd[-2:] == ["bea(a)tb-build-03.torproject.org", "true"]
+ assert kwargs["stdin"] is auth.subprocess.DEVNULL
+
+
+def test_verify_ssh_failure(monkeypatch):
+ monkeypatch.setattr(
+ auth.subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(returncode=255),
+ )
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is False
+
+
+def test_verify_ssh_missing_binary(monkeypatch, capsys):
+ def fake_run(*args, **kwargs):
+ raise FileNotFoundError()
+
+ monkeypatch.setattr(auth.subprocess, "run", fake_run)
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is False
+ assert "no `ssh` binary" in capsys.readouterr().out.lower()
+
+
+def test_run_saves_config_and_skips_verification(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False)
+
+ assert result == 0
+ config_path = tmp_path / common.YEET_CONFIG_FILENAME
+ with open(config_path) as f:
+ saved = json.load(f)
+ assert saved == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+ assert (config_path.stat().st_mode & 0o777) == 0o600
+
+
+def test_prompt_ssh_username_reprompts_until_non_empty(monkeypatch, capsys):
+ _set_inputs(monkeypatch, "", " ", "bea")
+
+ assert auth._prompt_ssh_username(common.DEFAULT_SSH_HOST) == "bea"
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+def test_prompt_ssh_host_defaults_when_empty(monkeypatch):
+ _set_inputs(monkeypatch, " ")
+
+ assert auth._prompt_ssh_host() == common.DEFAULT_SSH_HOST
+
+
+def test_run_prompts_for_ssh_host(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "build.example.com", "bea")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context, verify=False, gitlab_username="bea", gitlab_token="s3cr3t"
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved["ssh_host"] == "build.example.com"
+ assert saved["ssh_user"] == "bea"
+
+
+def test_prompt_token_reprompts_until_non_empty(monkeypatch, capsys):
+ values = iter(["", " ", "s3cr3t"])
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": next(values))
+
+ assert auth._prompt_token() == "s3cr3t"
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+def test_run_aborts_when_gitlab_verification_fails(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: False)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ "ERROR! GitLab rejected that project/token combination."
+ in capsys.readouterr().out
+ )
+
+
+def test_run_aborts_when_gitlab_unreachable(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+
+ def raise_url_error(project, token):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(auth, "_verify_auth", raise_url_error)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ "ERROR! Could not reach GitLab: <urlopen error unreachable>"
+ in capsys.readouterr().out
+ )
+
+
+def test_run_aborts_when_ssh_verification_fails(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: False)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ f"ERROR! Could not SSH into bea(a){common.DEFAULT_SSH_HOST}."
+ in capsys.readouterr().out
+ )
+
+
+def test_run_saves_config_when_verification_succeeds(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: True)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+def test_run_uses_cli_gitlab_username_and_still_prompts_for_rest(tmp_path, monkeypatch):
+ # ssh host and username aren't given via CLI, so they're the only things
+ # prompted for.
+ _set_inputs(monkeypatch, "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False, gitlab_username="bea")
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved["project"] == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+ assert saved["ssh_user"] == "bea"
+
+
+def test_run_rejects_invalid_cli_gitlab_username(tmp_path, monkeypatch, capsys):
+ _forbid_prompts(monkeypatch)
+ canonical_namespace = common.CANONICAL_GITLAB_NAMESPACE
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context, verify=False, gitlab_username=canonical_namespace
+ )
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert "not a" in capsys.readouterr().out.lower()
+
+
+def test_run_fully_noninteractive_with_all_cli_args(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=False,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host=common.DEFAULT_SSH_HOST,
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+def test_run_saves_cli_ssh_host(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ targets = []
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(
+ auth, "_verify_ssh", lambda target: targets.append(target) or True
+ )
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=True,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host="build.example.com",
+ )
+
+ assert result == 0
+ assert targets == ["bea(a)build.example.com"]
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f)["ssh_host"] == "build.example.com"
+
+
+def test_run_fully_noninteractive_with_verification(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: True)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=True,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host=common.DEFAULT_SSH_HOST,
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+_CLI_ARGS = {
+ "gitlab_username": "bea",
+ "gitlab_token": "s3cr3t",
+ "ssh_username": "bea",
+ "ssh_host": "build.example.com",
+}
+
+_SAVED_CONFIG = {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": "build.example.com",
+ "ssh_user": "bea",
+}
+
+
+(a)pytest.mark.parametrize("padding", [" ", "\t", "\n", " \t\n "])
+def test_run_trims_cli_args(tmp_path, monkeypatch, padding):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=False,
+ **{name: f"{padding}{value}{padding}" for name, value in _CLI_ARGS.items()},
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == _SAVED_CONFIG
+
+
+def test_run_trims_prompted_values(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, " bea\t", " build.example.com\n", "\tbea ")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": " s3cr3t\t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False)
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == _SAVED_CONFIG
+
+
+(a)pytest.mark.parametrize("arg", list(_CLI_ARGS))
+(a)pytest.mark.parametrize("blank", ["", " ", "\t\n"])
+def test_run_rejects_blank_cli_arg(tmp_path, monkeypatch, capsys, arg, blank):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False, **{**_CLI_ARGS, arg: blank})
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert "ERROR!" in capsys.readouterr().out
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_common.py
=====================================
@@ -0,0 +1,80 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from yeet import common
+
+
+(a)pytest.mark.parametrize("secret", [False, True])
+def test_prompt_flushes_pending_tty_input(monkeypatch, secret):
+ termios = pytest.importorskip("termios")
+ events = []
+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))
+ monkeypatch.setattr(
+ termios, "tcflush", lambda fd, queue: events.append(("flush", queue))
+ )
+ monkeypatch.setattr(
+ "builtins.input", lambda message="": events.append("input") or "plain"
+ )
+ monkeypatch.setattr(
+ common.getpass,
+ "getpass",
+ lambda message="": events.append("getpass") or "hidden",
+ )
+
+ answer = common.prompt("Q: ", secret=secret)
+
+ assert answer == ("hidden" if secret else "plain")
+ assert events == [
+ ("flush", termios.TCIFLUSH),
+ "getpass" if secret else "input",
+ ]
+
+
+def test_prompt_skips_flush_when_not_a_tty(monkeypatch):
+ termios = pytest.importorskip("termios")
+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: False))
+ monkeypatch.setattr(
+ termios,
+ "tcflush",
+ lambda *args: pytest.fail("tcflush called on non-tty stdin"),
+ )
+ monkeypatch.setattr("builtins.input", lambda message="": "piped")
+
+ assert common.prompt("Q: ") == "piped"
+
+
+(a)pytest.mark.parametrize(
+ "answers,expected",
+ [
+ (["y"], True),
+ (["YES"], True),
+ ([" yes "], True),
+ ([""], False),
+ (["n"], False),
+ (["No"], False),
+ (["maybe", "y"], True),
+ ],
+)
+def test_confirm(monkeypatch, answers, expected):
+ answers = iter(answers)
+ monkeypatch.setattr("builtins.input", lambda message="": next(answers))
+
+ assert common.confirm("Go?") is expected
+
+
+def test_confirm_reprompts_on_invalid_answer(monkeypatch, capsys):
+ answers = iter(["maybe", "sure", "n"])
+ monkeypatch.setattr("builtins.input", lambda message="": next(answers))
+
+ assert common.confirm("Go?") is False
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_remote.py
=====================================
@@ -0,0 +1,636 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import shlex
+import urllib.error
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from conftest import write_config
+from yeet import remote
+
+
+class _FakeResponse:
+ def __init__(self, body):
+ self._body = body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def read(self):
+ return self._body
+
+
+def _write_version(tmp_path, version="153.2.0"):
+ version_dir = tmp_path / "browser" / "config"
+ version_dir.mkdir(parents=True)
+ (version_dir / "version.txt").write_text(f"{version}\n")
+
+
+def test_read_browser_version(tmp_path):
+ _write_version(tmp_path, "1.2.3")
+
+ assert remote._read_browser_version(tmp_path) == "1.2.3"
+
+
+def test_resolve_version_prefers_given_value(tmp_path):
+
+ assert remote._resolve_version(tmp_path, "9.9.9") == "9.9.9"
+
+
+def test_resolve_version_falls_back_to_in_tree_version(tmp_path, capsys):
+ _write_version(tmp_path, "1.2.3")
+
+ assert remote._resolve_version(tmp_path, None) == "1.2.3"
+ assert "1.2.3" in capsys.readouterr().out
+
+
+def test_artifacts_and_mozharness_urls():
+ artifacts = remote._artifacts_url("1.2.3", "android_x86_64")
+
+ assert artifacts == f"{remote.TOOLCHAINS_URL_BASE}/1.2.3/android-x86_64/"
+ assert remote._mozharness_url("1.2.3", "android_x86_64") == (
+ artifacts + "mozharness.zip"
+ )
+
+
+def test_curl_command_includes_header_data_and_url():
+ command = remote._curl_command(
+ "https://example.org/trigger",
+ {"Content-Type": "application/json"},
+ b'{"a": 1}',
+ )
+
+ assert shlex.split(command) == [
+ "curl",
+ "--request",
+ "POST",
+ "--header",
+ "Content-Type: application/json",
+ "--data",
+ '{"a": 1}',
+ "https://example.org/trigger",
+ ]
+
+
+def _failing_upload_run(topsrcdir, file, platform, assume_yes):
+ raise RuntimeError("boom")
+
+
+def test_resolve_installer_url_passes_through_a_url(tmp_path):
+
+ url = remote._resolve_installer_url(
+ tmp_path,
+ "https://example.org/app.apk",
+ "android_x86_64",
+ assume_yes=False,
+ dry_run=False,
+ )
+
+ assert url == "https://example.org/app.apk"
+
+
+def test_resolve_installer_url_uploads_a_local_path(tmp_path, monkeypatch):
+ calls = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ calls.append((topsrcdir, file, platform, assume_yes))
+ return "https://tb-build-03.torproject.org/~bea/yeet/ts.apk"
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ url = remote._resolve_installer_url(
+ tmp_path,
+ "/tmp/app.apk",
+ "android_x86_64",
+ assume_yes=True,
+ dry_run=False,
+ )
+
+ assert url == "https://tb-build-03.torproject.org/~bea/yeet/ts.apk"
+ assert calls == [(tmp_path, "/tmp/app.apk", "android_x86_64", True)]
+
+
+def test_resolve_installer_url_propagates_upload_error(tmp_path, monkeypatch):
+ monkeypatch.setattr(remote.upload, "run", _failing_upload_run)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ remote._resolve_installer_url(
+ tmp_path,
+ "/tmp/app.apk",
+ "android_x86_64",
+ assume_yes=False,
+ dry_run=False,
+ )
+
+
+def test_prompt_platform_rejects_invalid_choice_then_accepts(monkeypatch):
+ values = iter(["0", "99", "not-a-number", "2"])
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+ assert remote._prompt_platform() == remote.PLATFORMS[1]
+
+
+def test_prompt_channel_rejects_invalid_choice_then_accepts(monkeypatch):
+ values = iter(["0", "99", "not-a-number", "2"])
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+ assert remote._prompt_channel() == remote.ANDROID_CHANNELS[1]
+
+
+def _run_kwargs(**overrides):
+ kwargs = dict(
+ platform="android_x86_64",
+ channel="debug",
+ installer_url="https://example.org/app.apk",
+ sha256sums_url=None,
+ artifacts_url="https://example.org/artifacts/",
+ mozharness_url="https://example.org/mozharness.zip",
+ version=None,
+ ref="main",
+ tags=["tor"],
+ dry_run=False,
+ )
+ kwargs.update(overrides)
+ return kwargs
+
+
+def test_run_aborts_without_config(tmp_path, capsys):
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ assert "mach yeet auth" in capsys.readouterr().out
+
+
+def test_run_dry_run_prints_curl_and_skips_network(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fail_urlopen(*args, **kwargs):
+ raise AssertionError("urlopen should not be called in dry-run mode")
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fail_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs(dry_run=True))
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "curl --request POST" in out
+ assert "app.apk" in out
+
+
+def test_run_prompts_for_platform_when_missing(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ calls = []
+
+ def fake_prompt_platform():
+ calls.append(True)
+ return "debian_x86_64"
+
+ monkeypatch.setattr(remote, "_prompt_platform", fake_prompt_platform)
+
+ result = remote.run(command_context, **_run_kwargs(platform=None, dry_run=True))
+
+ assert result == 0
+ assert len(calls) == 1
+ assert "debian_x86_64_installer_url" in capsys.readouterr().out
+
+
+def test_run_prompts_for_channel_when_android_and_missing(
+ tmp_path, monkeypatch, capsys
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ calls = []
+
+ def fake_prompt_channel():
+ calls.append(True)
+ return "nightly"
+
+ monkeypatch.setattr(remote, "_prompt_channel", fake_prompt_channel)
+
+ result = remote.run(command_context, **_run_kwargs(channel=None, dry_run=True))
+
+ assert result == 0
+ assert len(calls) == 1
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] in capsys.readouterr().out
+
+
+def test_run_adds_package_name_input_for_android(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs(channel="nightly", dry_run=True))
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "android_x86_64_package_name" in out
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] in out
+
+
+def test_run_skips_channel_for_non_android_platforms(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote,
+ "_prompt_channel",
+ lambda: (_ for _ in ()).throw(AssertionError("should not prompt")),
+ )
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(
+ platform="debian_x86_64",
+ channel=None,
+ artifacts_url="https://example.org/artifacts/",
+ mozharness_url="https://example.org/mozharness.zip",
+ dry_run=True,
+ ),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "package_name" not in out
+
+
+def test_run_rejects_unknown_channel(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs(channel="not-a-channel"))
+
+ assert result == 1
+ assert "ERROR! Unknown channel 'not-a-channel'." in capsys.readouterr().out
+
+
+(a)pytest.mark.parametrize("dry_run", [False, True])
+(a)pytest.mark.parametrize("installer_url", ["", " ", "\t\n"])
+def test_run_rejects_empty_installer(
+ tmp_path, monkeypatch, capsys, installer_url, dry_run
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote, "_prompt_platform", lambda: pytest.fail("prompted for platform")
+ )
+ monkeypatch.setattr(
+ remote.upload, "run", lambda *args, **kwargs: pytest.fail("uploaded")
+ )
+ monkeypatch.setattr(
+ remote.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("pipeline triggered"),
+ )
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform=None, installer_url=installer_url, dry_run=dry_run),
+ )
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert "ERROR! The installer URL or path was empty." in out
+ assert "curl" not in out
+
+
+def test_run_trims_installer_url(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(installer_url=" https://example.org/app.apk\n", dry_run=True),
+ )
+
+ assert result == 0
+ assert '"android_x86_64_installer_url": "https://example.org/app.apk"' in (
+ capsys.readouterr().out
+ )
+
+
+def test_run_ignores_channel_for_non_android_platforms(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform="debian_x86_64", channel="nightly", dry_run=True),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "package_name" not in out
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] not in out
+
+
+(a)pytest.mark.parametrize(
+ "platform,installer",
+ [
+ ("debian_x86_64", "tor-browser-linux-x86_64.tar.xz"),
+ ("windows_x86_64", "tor-browser-windows-x86_64-portable.exe"),
+ ("macos_x86_64", "tor-browser-macos.dmg"),
+ ("android_x86_64", "tor-browser-android-x86_64.apk"),
+ ],
+)
+def test_run_uploads_a_local_path_before_triggering(
+ tmp_path, monkeypatch, platform, installer
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ installer_path = f"/tmp/{installer}"
+ uploaded_url = (
+ f"https://tb-build-03.torproject.org/~bea/yeet/ts-{platform}/{installer}"
+ )
+ uploads = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ uploads.append((file, platform))
+ return uploaded_url
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform=platform, installer_url=installer_path),
+ )
+
+ assert result == 0
+ assert uploads == [(installer_path, platform)]
+ inputs = json.loads(requests[0].data)["inputs"]
+ assert inputs[f"{platform}_installer_url"] == uploaded_url
+ assert (f"{platform}_package_name" in inputs) == (platform == "android_x86_64")
+
+
+def test_run_prompts_for_platform_before_uploading(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(remote, "_prompt_platform", lambda: "debian_x86_64")
+ seen = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ seen.append(platform)
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ remote.run(
+ command_context, **_run_kwargs(platform=None, installer_url="/tmp/app.tar.xz")
+ )
+
+ assert seen == ["debian_x86_64"]
+
+
+(a)pytest.mark.parametrize("assume_yes", [False, True])
+def test_run_forwards_assume_yes_to_upload(tmp_path, monkeypatch, assume_yes):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ seen = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ seen.append(assume_yes)
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ remote.run(
+ command_context,
+ **_run_kwargs(installer_url="/tmp/app.apk", assume_yes=assume_yes),
+ )
+
+ assert seen == [assume_yes]
+
+
+(a)pytest.mark.parametrize(
+ "tags,expected",
+ [
+ (["tor", "base-browser"], "--tag tor --tag base-browser"),
+ (["a b"], "--tag 'a b'"),
+ (["a b", '"c"'], """--tag 'a b' --tag '"c"'"""),
+ ],
+)
+def test_run_formats_tags_as_flags(tmp_path, monkeypatch, tags, expected):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ remote.run(command_context, **_run_kwargs(tags=tags))
+
+ assert json.loads(requests[0].data)["inputs"]["tags"] == expected
+
+
+def test_run_omits_tags_input_when_empty(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ remote.run(command_context, **_run_kwargs(tags=[]))
+
+ assert "tags" not in json.loads(requests[0].data)["inputs"]
+
+
+def _triggered_inputs(tmp_path, monkeypatch, **overrides):
+ write_config(tmp_path)
+ _write_version(tmp_path, "1.2.3")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ assert remote.run(command_context, **_run_kwargs(**overrides)) == 0
+ return json.loads(requests[0].data)["inputs"]
+
+
+(a)pytest.mark.parametrize("sha256sums_url", [None, "https://example.org/sha256sums.txt"])
+def test_run_includes_sha256sums_input_only_when_given(
+ tmp_path, monkeypatch, sha256sums_url
+):
+ inputs = _triggered_inputs(tmp_path, monkeypatch, sha256sums_url=sha256sums_url)
+
+ assert inputs.get("android_x86_64_sha256sums_url") == sha256sums_url
+
+
+(a)pytest.mark.parametrize("artifacts_url", [None, "https://example.org/artifacts/"])
+(a)pytest.mark.parametrize("mozharness_url", [None, "https://example.org/mozharness.zip"])
+def test_run_uses_given_artifacts_and_mozharness_urls_or_infers_them(
+ tmp_path, monkeypatch, artifacts_url, mozharness_url
+):
+ inputs = _triggered_inputs(
+ tmp_path,
+ monkeypatch,
+ artifacts_url=artifacts_url,
+ mozharness_url=mozharness_url,
+ )
+
+ assert inputs["android_x86_64_artifacts_url"] == (
+ artifacts_url or remote._artifacts_url("1.2.3", "android_x86_64")
+ )
+ assert inputs["mozharness_url"] == (
+ mozharness_url or remote._mozharness_url("1.2.3", "android_x86_64")
+ )
+
+
+def test_run_aborts_when_local_upload_fails(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(remote.upload, "run", _failing_upload_run)
+ monkeypatch.setattr(
+ remote.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("pipeline triggered after failed upload"),
+ )
+
+ result = remote.run(command_context, **_run_kwargs(installer_url="/tmp/app.apk"))
+
+ assert result == 1
+ assert "ERROR! boom" in capsys.readouterr().out
+
+
+def test_run_dry_run_does_not_upload_a_local_path(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote.upload,
+ "run",
+ lambda *args, **kwargs: pytest.fail("uploaded during a dry run"),
+ )
+
+ result = remote.run(
+ command_context, **_run_kwargs(installer_url=str(apk), dry_run=True)
+ )
+
+ assert result == 0
+ assert "<URL of uploaded app.apk>" in capsys.readouterr().out
+
+
+def test_run_dry_run_rejects_missing_local_path(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ missing = tmp_path / "missing.apk"
+
+ result = remote.run(
+ command_context, **_run_kwargs(installer_url=str(missing), dry_run=True)
+ )
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert f"ERROR! No such file: {missing}" in out
+ assert "curl" not in out
+
+
+def test_run_infers_version_artifacts_and_mozharness(tmp_path, capsys):
+ write_config(tmp_path)
+ _write_version(tmp_path, "1.2.3")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(artifacts_url=None, mozharness_url=None, dry_run=True),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "1.2.3" in out
+ assert "android-x86_64" in out
+
+
+def test_run_triggers_pipeline_and_reports_url(tmp_path, monkeypatch, capsys):
+ config = write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ body = json.dumps({"web_url": "https://gitlab.example/pipelines/1"}).encode()
+ return _FakeResponse(body)
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 0
+ assert "https://gitlab.example/pipelines/1" in capsys.readouterr().out
+ assert requests[0].full_url == (
+ f"{remote.GITLAB_API_BASE}/projects/"
+ f"{config['project'].replace('/', '%2F')}/trigger/pipeline"
+ )
+ payload = json.loads(requests[0].data)
+ assert payload["token"] == config["token"]
+ assert payload["ref"] == "main"
+ assert payload["inputs"]["tags"] == "--tag tor"
+
+
+def test_run_reports_http_error(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fake_urlopen(request, timeout=None):
+ raise urllib.error.HTTPError(
+ request.full_url,
+ 401,
+ "Unauthorized",
+ None,
+ SimpleNamespace(read=lambda: b"bad token", close=lambda: None),
+ )
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert "401" in out
+ assert "bad token" in out
+
+
+def test_run_reports_url_error(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fake_urlopen(request, timeout=None):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ assert "unreachable" in capsys.readouterr().out
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_upload.py
=====================================
@@ -0,0 +1,242 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from conftest import write_config
+from yeet import upload
+
+
+def _freeze_time(monkeypatch, fixed):
+ class _FrozenDatetime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return fixed.astimezone(tz)
+
+ monkeypatch.setattr(upload, "datetime", _FrozenDatetime)
+
+
+def test_resolve_file_missing():
+ with pytest.raises(FileNotFoundError, match="No such file"):
+ upload.resolve_file("/no/such/file/here")
+
+
+def test_resolve_file_existing(tmp_path):
+ apk = tmp_path / "fenix-x86_64-debug.apk"
+ apk.write_bytes(b"not really an apk")
+
+ assert upload.resolve_file(str(apk)) == apk.resolve()
+
+
+(a)pytest.mark.parametrize(
+ "fixed,expected",
+ [
+ (datetime(2026, 9, 14, 12, 34, 56, tzinfo=timezone.utc), "20260914-123456"),
+ (
+ datetime(
+ 2026, 9, 14, 18, 4, 56, tzinfo=timezone(timedelta(hours=5, minutes=30))
+ ),
+ "20260914-123456",
+ ),
+ (
+ datetime(2026, 9, 14, 21, 0, 0, tzinfo=timezone(timedelta(hours=-5))),
+ "20260915-020000",
+ ),
+ ],
+)
+def test_remote_dir_name_is_current_utc_time_and_platform(monkeypatch, fixed, expected):
+ _freeze_time(monkeypatch, fixed)
+
+ assert upload._remote_dir_name("android_x86_64") == f"{expected}-android_x86_64"
+
+
+def test_upload_success(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ assert kwargs["stdin"] is upload.subprocess.DEVNULL
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ url = upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+ assert url == "https://example.org/~bea/yeet/ts-os/app.apk"
+ assert calls[0][0] == "ssh"
+ assert calls[0][-3:] == ["mkdir", "-p", "~/public_html/yeet/ts-os"]
+ assert calls[1][0] == "scp"
+ assert calls[1][-2:] == [
+ "/tmp/app.apk",
+ "bea@example.org:~/public_html/yeet/ts-os/app.apk",
+ ]
+
+
+def test_upload_replaces_unsafe_filename_characters(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ url = upload._upload(
+ upload.Path("/tmp/app (1)#%?.apk"), "bea", "example.org", "ts-os"
+ )
+
+ assert url == "https://example.org/~bea/yeet/ts-os/app__1____.apk"
+ assert calls[1][-2:] == [
+ "/tmp/app (1)#%?.apk",
+ "bea@example.org:~/public_html/yeet/ts-os/app__1____.apk",
+ ]
+
+
+def test_upload_stops_if_mkdir_fails(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return SimpleNamespace(returncode=1)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ with pytest.raises(RuntimeError):
+ upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+ assert len(calls) == 1
+
+
+def test_upload_fails_if_scp_fails(monkeypatch):
+ def fake_run(cmd, **kwargs):
+ return SimpleNamespace(returncode=0 if cmd[0] == "ssh" else 1)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ with pytest.raises(RuntimeError):
+ upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+
+def test_run_aborts_without_config(tmp_path):
+ apk = tmp_path / "app.apk"
+ apk.touch()
+
+ with pytest.raises(RuntimeError, match="mach yeet auth"):
+ upload.run(tmp_path, str(apk), "android_x86_64")
+
+
+def test_run_aborts_when_file_missing(tmp_path):
+ write_config(tmp_path)
+
+ with pytest.raises(FileNotFoundError):
+ upload.run(tmp_path, str(tmp_path / "missing.apk"), "android_x86_64")
+
+
+def _write_apk(tmp_path):
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ return apk
+
+
+def _set_confirm_answers(monkeypatch, *answers):
+ answers = iter(answers)
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(answers))
+
+
+def test_run_uploads_into_timestamped_dir_and_prints_url(tmp_path, monkeypatch, capsys):
+ config = write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ _freeze_time(monkeypatch, datetime(2026, 9, 14, 12, 34, 56, tzinfo=timezone.utc))
+
+ calls = []
+
+ def fake_upload(file_path, ssh_user, ssh_host, remote_dir):
+ calls.append((file_path, ssh_user, ssh_host, remote_dir))
+ return f"https://{ssh_host}/~{ssh_user}/yeet/{remote_dir}/{file_path.name}"
+
+ monkeypatch.setattr(upload, "_upload", fake_upload)
+
+ url = upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+
+ assert url == (
+ f"https://{config['ssh_host']}/~{config['ssh_user']}/yeet/20260914-123456-android_x86_64/app.apk"
+ )
+ assert calls == [
+ (
+ apk.resolve(),
+ config["ssh_user"],
+ config["ssh_host"],
+ "20260914-123456-android_x86_64",
+ )
+ ]
+ assert url in capsys.readouterr().out
+
+
+def test_run_reports_upload_failure(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+
+ def fake_upload(file_path, ssh_user, ssh_host, remote_dir):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(upload, "_upload", fake_upload)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+
+
+(a)pytest.mark.parametrize("answer", ["y", "yes", "Y"])
+def test_run_uploads_after_confirmation(tmp_path, monkeypatch, answer):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ _set_confirm_answers(monkeypatch, answer)
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda file_path, ssh_user, ssh_host, remote_dir: "https://x/y",
+ )
+
+ assert upload.run(tmp_path, str(apk), "android_x86_64") == "https://x/y"
+
+
+(a)pytest.mark.parametrize("answers", [("",), ("n",), ("no",), ("maybe", "n")])
+def test_run_does_not_upload_when_declined(tmp_path, monkeypatch, answers):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ _set_confirm_answers(monkeypatch, *answers)
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda *args: pytest.fail("_upload called after the user declined"),
+ )
+
+ with pytest.raises(RuntimeError, match="cancelled"):
+ upload.run(tmp_path, str(apk), "android_x86_64")
+
+
+def test_run_skips_confirmation_with_assume_yes(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ monkeypatch.setattr(
+ "builtins.input", lambda prompt="": pytest.fail("unexpected prompt")
+ )
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda file_path, ssh_user, ssh_host, remote_dir: "https://x/y",
+ )
+
+ assert (
+ upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+ == "https://x/y"
+ )
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/upload.py
=====================================
@@ -0,0 +1,96 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import re
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+
+from yeet.common import TERM, YEET_CONFIG_FILENAME, confirm, read_config
+
+
+def resolve_file(file_arg):
+ path = Path(file_arg).resolve()
+ if not path.is_file():
+ raise FileNotFoundError(f"No such file: {path}")
+ return path
+
+
+def _remote_dir_name(platform):
+ """Name the upload's directory after the current time and `platform`,
+ so repeated uploads never collide or overwrite each other.
+ """
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ return f"{timestamp}-{platform}"
+
+
+def _upload(file_path, ssh_user, ssh_host, remote_dir):
+ """scp `file_path` into ~/public_html/yeet/`remote_dir` on
+ ssh_user@ssh_host, keeping its name (with characters unsafe in a URL or
+ shell replaced by `_`) and creating that directory first if needed. Both
+ commands get /dev/null as stdin so they can't swallow input buffered for
+ us; their touch/PIN/passphrase prompts go through /dev/tty and still reach
+ the user.
+
+ Returns the file's final https:// URL. Raises RuntimeError on failure.
+ """
+ ssh_target = f"{ssh_user}@{ssh_host}"
+ remote_name = re.sub(r"[^A-Za-z0-9._-]", "_", file_path.name)
+ dest_dir = f"~/public_html/yeet/{remote_dir}"
+ dest_path = f"{dest_dir}/{remote_name}"
+ html_path = f"~{ssh_user}/yeet/{remote_dir}/{remote_name}"
+
+ mkdir = subprocess.run(
+ ["ssh", ssh_target, "mkdir", "-p", dest_dir],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ if mkdir.returncode != 0:
+ raise RuntimeError(f"Could not create {dest_dir} on {ssh_target}.")
+
+ scp = subprocess.run(
+ ["scp", str(file_path), f"{ssh_target}:{dest_path}"],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ if scp.returncode != 0:
+ raise RuntimeError(f"Upload to {ssh_target} failed.")
+
+ return f"https://{ssh_host}/{html_path}"
+
+
+def run(topsrcdir, file, platform, assume_yes=False):
+ """Upload `file` for `platform` to the configured server, asking for
+ confirmation first unless `assume_yes`. Returns the file's final https://
+ URL. Raises FileNotFoundError if `file` or the config is missing, and
+ RuntimeError if the upload fails or is cancelled.
+ """
+ config = read_config(topsrcdir)
+ if config is None:
+ raise RuntimeError(
+ f"No {YEET_CONFIG_FILENAME} found. Run `mach yeet auth` first."
+ )
+
+ file_path = resolve_file(file)
+
+ remote_dir = _remote_dir_name(platform)
+
+ if not assume_yes:
+ print()
+ print(
+ TERM.yellow(
+ f"{file_path} will be uploaded to {config['ssh_host']} and "
+ "be publicly accessible."
+ )
+ )
+ if not confirm("Upload it?"):
+ raise RuntimeError("Upload cancelled.")
+
+ print()
+ print(f"Uploading {file_path.name} to {remote_dir}/...")
+ url = _upload(file_path, config["ssh_user"], config["ssh_host"], remote_dir)
+
+ print()
+ print(TERM.green(f"Uploaded: {url}"))
+ return url
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3f305e…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3f305e…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 13 commits: BB 45308: Implement ./mach yeet command
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
89980175 by Beatriz Rizental at 2026-11-05T08:37:09+01:00
BB 45308: Implement ./mach yeet command
./mach yeet is the Tor Project version of try -- but much simpler.
- - - - -
7bf6dbd8 by Beatriz Rizental at 2026-11-05T08:37:09+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet auth
- - - - -
fd82e86b by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet's upload step
Uploads a local file to the configured build server's public_html
over scp.
- - - - -
6c312932 by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Bug 45308: Implement ./mach yeet remote's CI trigger
- - - - -
cdd4f1f1 by Beatriz Rizental at 2026-11-05T08:37:10+01:00
fixup! BB 45308: Implement ./mach yeet command
Address review comments
- - - - -
48a32237 by Beatriz Rizental at 2026-11-05T08:37:11+01:00
fixup! BB 45308: Implement ./mach yeet command
Attend more review comments.
- - - - -
f661f0d7 by Pier Angelo Vendrame at 2026-11-05T08:37:11+01:00
fixup! TB 42669: [android] Use custom no-op app-services
- - - - -
adc63271 by Pier Angelo Vendrame at 2026-11-05T08:37:11+01:00
fixup! [android] Modify build system
- - - - -
6353e646 by Beatriz Rizental at 2026-11-05T08:37:11+01:00
fixup! TB 41089: Add tor-browser build scripts + Makefile to tor-browser
This reverts commit 5f43c88992e4b69ac03c5e40aeba08fe8d0bd56e.
- - - - -
1ce02a42 by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! TB 43564: Modify ./mach bootstrap for Tor Browser
Move NoScript gitignore statement to this commit
- - - - -
d95babfc by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! BB 45120: Add tests for Tor Browser
Bug 44820: Upstream geckoiew's own manifest requests
ACCESS_NETWORK_STATE. Tor Browser comments that line
out so geckoview doesn't ask for network-state access,
but the test app needs it. So we add it back.
- - - - -
1aaee7aa by Beatriz Rizental at 2026-11-05T08:37:12+01:00
fixup! TB 43817: Add tests for Tor Browser
Disable Fenix unit tests by default, since most of them
don't work in Tor Browser (some don't even compile). An
allowlist in the Fenix build.gradle controls which unit
tests are compiled and run, so they can be re-enabled as
they get fixed. When the allowlist is empty, the unit test
compile and test tasks are skipped entirely.
Also add a trivial SanityTest, enabled in the allowlist,
to make sure the unit test pipeline works.
- - - - -
ac3d0ae7 by Henry Wilkes at 2026-11-05T08:37:13+01:00
fixup! TB 41600: Add a tor circuit display panel.
TB 45398: Move tor circuit button into the identity box.
- - - - -
30 changed files:
- .gitignore
- browser/base/content/navigator-toolbox.inc.xhtml
- browser/themes/shared/identity-block/identity-block.css
- mobile/android/fenix/app/build.gradle
- + mobile/android/fenix/app/src/test/java/org/mozilla/fenix/torbrowser/SanityTest.kt
- mobile/android/geckoview/src/androidTest/AndroidManifest.xml
- python/mach/mach/command_util.py
- tools/moz.build
- − tools/torbrowser/Makefile
- − tools/torbrowser/browser-self-sign-macos.sh
- − tools/torbrowser/build.sh
- − tools/torbrowser/clobber.sh
- − tools/torbrowser/config.sh
- − tools/torbrowser/deploy.sh
- − tools/torbrowser/fetch.sh
- − tools/torbrowser/ide.sh
- − tools/torbrowser/jslint.sh
- − tools/torbrowser/prepare-tests.sh
- + tools/yeet/__init__.py
- + tools/yeet/auth.py
- + tools/yeet/common.py
- + tools/yeet/mach_commands.py
- + tools/yeet/remote.py
- + tools/yeet/tests/python/conftest.py
- + tools/yeet/tests/python/python.toml
- + tools/yeet/tests/python/test_auth.py
- + tools/yeet/tests/python/test_common.py
- + tools/yeet/tests/python/test_remote.py
- + tools/yeet/tests/python/test_upload.py
- + tools/yeet/upload.py
Changes:
=====================================
.gitignore
=====================================
@@ -430,14 +430,9 @@ CLAUDE.local.md
# lint-ignore-next-line: git-only
/*.json.gz
-# Ignore binary base of Tor Browser
-.binaries
+# GitLab project and token saved by `mach yeet auth`
+/.yeet.json
-# Other files modified at build time
-mobile/android/.experimenter.json
-
-# Tor libraries for local builds
-mobile/android/fenix/tools/nimbus-fml
-mobile/android/fenix/app/tor-expert-bundle.aar
+# Symlink to NoScript .xpi. It lives in MOZBUILD, but needs to be symlinked
+# to this path so it's added to the APK.
mobile/android/fenix/app/src/main/assets/extensions/{73a6fe31-595d-460b-a920-fcc0f8843232}.xpi
-
=====================================
browser/base/content/navigator-toolbox.inc.xhtml
=====================================
@@ -193,19 +193,6 @@
<image id="remote-control-icon"/>
</box>
- <!-- We follow the surrounding code and use a
- - <xul:box role="button"> rather than a more semantic
- - <html:button>, <xul:button> or <xul:toolbarbutton> -->
- <box id="tor-circuit-button"
- role="button"
- class="identity-box-button"
- align="center"
- data-l10n-id="tor-circuit-urlbar-button"
- urlbar-slot="site-info"
- hidden="true">
- <image id="tor-circuit-button-icon"/>
- </box>
-
<box
id="trust-icon-container"
align="center"
@@ -247,6 +234,17 @@
class="identity-box"
pageproxystate="invalid"
urlbar-slot="site-info">
+ <!-- We follow the surrounding code and use a
+ - <xul:box role="button"> rather than a more semantic
+ - <html:button>, <xul:button> or <xul:toolbarbutton> -->
+ <box id="tor-circuit-button"
+ role="button"
+ class="identity-box-button"
+ align="center"
+ data-l10n-id="tor-circuit-urlbar-button"
+ hidden="true">
+ <image id="tor-circuit-button-icon"/>
+ </box>
<!-- Shown when trustPanel.featureGate is off, or for
chromeUI/extensionPage where tracker blocking never runs, so we
never update `data-l10n-args`. -->
=====================================
browser/themes/shared/identity-block/identity-block.css
=====================================
@@ -7,7 +7,6 @@
#tracking-protection-icon-container,
#identity-box,
#trust-icon-container,
-#tor-circuit-button,
#urlbar-label-box {
height: var(--urlbar-basic-component-size);
}
@@ -33,7 +32,9 @@
/* And don't show the identity icon box in this case,
just permissions indication */
- > #identity-icon-box {
+ /* Hide the tor circuit when the identity box is also hidden.
+ * tor-browser#45398. */
+ > :is(#identity-icon-box, #tor-circuit-button) {
display: none;
}
}
=====================================
mobile/android/fenix/app/build.gradle
=====================================
@@ -717,6 +717,39 @@ protobuf {
}
}
+// Unit tests are disabled by default because most of them don't work in Tor Browser.
+// Add source path patterns here (e.g. 'org/mozilla/fenix/home/**') to re-enable them
+// as they get fixed. Only the listed tests (plus the shared helpers) are compiled and run.
+// When the list is empty, unit tests are neither compiled nor run.
+def enabledUnitTests = [
+ 'org/mozilla/fenix/torbrowser/**',
+]
+def unitTestHelpers = [
+ 'org/mozilla/fenix/helpers/**',
+]
+
+tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
+ if (name.contains("UnitTest")) {
+ if (enabledUnitTests) {
+ // The task already has default include patterns, so we can only narrow it down with excludes.
+ def allowed = new org.gradle.api.tasks.util.PatternSet()
+ .include((enabledUnitTests + unitTestHelpers).collect { "**/$it" })
+ .asSpec
+ exclude { !it.directory && !allowed.isSatisfiedBy(it) }
+ } else {
+ enabled = false
+ }
+ }
+}
+
+tasks.withType(Test).configureEach {
+ if (enabledUnitTests) {
+ include enabledUnitTests
+ } else {
+ enabled = false
+ }
+}
+
if (project.hasProperty("coverage")) {
tasks.withType(Test).configureEach {
jacoco.includeNoLocationClasses = true
=====================================
mobile/android/fenix/app/src/test/java/org/mozilla/fenix/torbrowser/SanityTest.kt
=====================================
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+package org.mozilla.fenix.torbrowser
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class SanityTest {
+ @Test
+ fun `one plus one is two`() {
+ assertEquals(2, 1 + 1)
+ }
+}
=====================================
mobile/android/geckoview/src/androidTest/AndroidManifest.xml
=====================================
@@ -4,6 +4,7 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
=====================================
python/mach/mach/command_util.py
=====================================
@@ -296,6 +296,7 @@ MACH_COMMANDS = {
"xpcshell-test": MachCommandReference(
"testing/xpcshell/mach_commands.py", ["test"]
),
+ "yeet": MachCommandReference("tools/yeet/mach_commands.py"),
}
=====================================
tools/moz.build
=====================================
@@ -75,4 +75,5 @@ PYTHON_UNITTEST_MANIFESTS += [
"lint/test/python.toml",
"tryselect/test/python.toml",
"update-packaging/test/python.toml",
+ "yeet/tests/python/python.toml",
]
=====================================
tools/torbrowser/Makefile deleted
=====================================
@@ -1,72 +0,0 @@
-.DEFAULT_GOAL := all
-
-# https://stackoverflow.com/questions/18136918/how-to-get-current-relative-di…
-mkfile_path := "$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))"
-
-DEV_ROOT = "$(mkfile_path)/../.."
-BINARIES = "$(DEV_ROOT)/.binaries"
-ARCHITECTURE = "$(shell uname -m)"
-
-# Correct the architecture naming for ARM to match what mozilla has
-ifeq ($(ARCHITECTURE), "arm64")
- ARCHITECTURE = "aarch64"
-endif
-
-ifeq ($(ARCHITECTURE), "aarch64")
- LINUX_VENDOR = "unknown"
-else
- LINUX_VENDOR = "pc"
-endif
-
-# Define build output path based on the platform.
-ifeq ("$(shell uname)", "Darwin")
- BUILD_OUTPUT = "$(DEV_ROOT)/obj-$(ARCHITECTURE)-apple-darwin$(shell uname -r)"
-else
- BUILD_OUTPUT = "$(DEV_ROOT)/obj-$(ARCHITECTURE)-$(LINUX_VENDOR)-linux-gnu"
-endif
-
-# Define the run command based on the platform.
-ifeq ("$(shell uname)", "Darwin")
- RUN_CMD := cd "$(BINARIES)/Tor Browser.app/Contents/MacOS/" && ./firefox --purgecaches
-else
- RUN_CMD := "$(BINARIES)/dev/Browser/start-tor-browser" -v --purgecaches $(ARGS)
-endif
-
-config:
- ./config.sh $(DEV_ROOT)
-
-ide-vscode:
- ./ide.sh vscode $(DEV_ROOT)
-
-ide-eclipse:
- ./ide.sh eclipse $(DEV_ROOT)
-
-ide-visualstudio:
- ./ide.sh visualstudio $(DEV_ROOT)
-
-fetch:
- ./fetch.sh $(BINARIES)
-
-build:
- ./build.sh $(DEV_ROOT)
-
-deploy:
- ./deploy.sh $(BINARIES) $(BUILD_OUTPUT)
-
-prepare-tests:
- ./prepare-tests.sh $(BINARIES) $(BUILD_OUTPUT)
-
-all: build deploy
-
-run:
- $(RUN_CMD)
-
-jslint:
- ./jslint.sh $(DEV_ROOT) $(JS)
-
-clobber:
- ./clobber.sh $(DEV_ROOT)
-
-clean:
- rm -rf $(BUILD_OUTPUT)
-
=====================================
tools/torbrowser/browser-self-sign-macos.sh deleted
=====================================
@@ -1,110 +0,0 @@
-#!/bin/bash
-
-CERTNAME=my-codesign-cert-tor
-BROWSERPATH=.
-
-if [ $# -ge 1 ]
-then
- BROWSERPATH=$1
-fi
-
-
-security find-certificate -c $CERTNAME > /dev/null
-
-if [ $? -ne 0 ]
-then
- echo ""
- echo "ERROR: Self Signing Certificate not found, please create:"
- echo " 1. In the Keychain Access app on your Mac, choose Keychain Access > Certificate Assistant > Create a Certificate."
- echo " 2. Enter the name '$CERTNAME' for the certificate"
- echo " 3. Choose an identity type: Self Signed Root"
- echo " 4. Certificate Type > Code Signing"
- echo " 5. Check 'Let me override defaults' & click Continue."
- echo " 6. Enter a unique Serial Number. (123 is fine)"
- echo " 7. Enter a big Validity Period (days), like 3560 & click Continue."
- echo " 8. Fill in your personal information & click Continue."
- echo " 9. Accept defaults for the rest of the dialog boxes. (Continue several times)"
- echo " 10. Certificate Created! Click Done."
- echo ""
- echo "For additional help see:"
- echo " https://support.apple.com/en-ca/guide/keychain-access/kyca8916/mac"
- echo " https://stackoverflow.com/questions/58356844/what-are-the-ways-or-technolog…"
-
- echo ""
- read -n 1 -r -s -p $'Press enter to launch "Keychain Access"...\n'
- open /System/Applications/Utilities/Keychain\ Access.app
-
- exit -1
-fi
-
-echo "Found $CERTNAME, looking for browser to sign..."
-
-if [ ! -f "$BROWSERPATH/XUL" ]
-then
- TESTPATH="$BROWSERPATH/Contents/MacOS"
- if [ -f "$TESTPATH/XUL" ]
- then
- BROWSERPATH=$TESTPATH
- else
- echo "Error: browser files not detected in $BROWSERPATH!"
- echo " This script needs to be run in the 'Contents/MacOS' directory of a SomeBrowser.app directory"
- exit -1
- fi
-fi
-
-echo "Mozilla based browser found, signing..."
-echo ' Will be asked for password to certificate for all the things that need to be signed. Click "Always Allow" to automate'
-
-cd "$BROWSERPATH"
-
-codesign -s $CERTNAME *.dylib
-codesign -s $CERTNAME plugin-container.app
-
-if [ -d Tor ]
-then
- codesign -s $CERTNAME Tor/PluggableTransports/*
- codesign -s $CERTNAME Tor/libevent-2.1.7.dylib
- if [ -f Tor/tor.real ]
- then
- codesign -s $CERTNAME Tor/tor.real
- fi
- if [ -f Tor/tor ]
- then
- codesign -s $CERTNAME Tor/tor
- fi
-fi
-
-codesign -s $CERTNAME XUL
-
-if [ -d updater.app ]
-then
- codesign -s $CERTNAME updater.app
-fi
-
-# mullvadbrowser
-if [ -f mullvadbrowser ]
-then
- codesign -s $CERTNAME mullvadbrowser
-fi
-
-# BB or TB
-if [ -f firefox ]
-then
- codesign -s $CERTNAME firefox
-fi
-
-echo ""
-echo "Browser signing step done!"
-echo ""
-
-echo "App still needs one more override to be easily opened with double click in Finder"
-echo "Alternatively you can right click it, select 'Open' and then select 'Open' from the override popup"
-echo "Or to enable it to be double clicked to open perform the following"
-echo ""
-echo "Double click the app and select either 'Ok' or 'Cancel' from the warning popup depending on which you get (Do Not 'Move to Trash')"
-echo 'Go to Preferences -> Security & Privacy and click on padlock to allow changes. '
-echo ' Then in "Allow appications downloaded from" select either:'
-echo ' - App Store and identified developers'
-echo ' - Anywhere'
-echo ' Below that may be a notice about your specific app saying it was blocked because it was not from an identified developer. Click "Open Anyways" and "Open"'
-
=====================================
tools/torbrowser/build.sh deleted
=====================================
@@ -1,15 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach build
-
-if [ -z "$LOCALES" ]; then
- ./mach build stage-package
-else
- export MOZ_CHROME_MULTILOCALE=$LOCALES
- # No quotes on purpose
- ./mach package-multi-locale --locales en-US $MOZ_CHROME_MULTILOCALE
- AB_CD=multi ./mach build stage-package
-fi
=====================================
tools/torbrowser/clobber.sh deleted
=====================================
@@ -1,6 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach clobber
=====================================
tools/torbrowser/config.sh deleted
=====================================
@@ -1,6 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-
-cd $DEV_ROOT
-./mach configure
=====================================
tools/torbrowser/deploy.sh deleted
=====================================
@@ -1,43 +0,0 @@
-#!/bin/bash
-set -e
-
-BINARIES="$1"
-BUILD_OUTPUT="$2"
-SCRIPT_DIR="$(realpath "$(dirname "$0")")"
-
-RESDIR="$BUILD_OUTPUT/dist/firefox"
-if [ "$(uname)" = "Darwin" ]; then
- RESDIR="$RESDIR/Tor Browser.app/Contents/Resources"
-fi
-
-# Repackage the manual
-# rm -rf $BUILD_OUTPUT/_omni
-# mkdir $BUILD_OUTPUT/_omni
-# unzip $BINARIES/dev/Browser/browser/omni.ja -d $BUILD_OUTPUT/_omni
-# cd $BUILD_OUTPUT/_omni && zip -Xmr $RESDIR/browser/omni.ja chrome/browser/content/browser/manual
-# rm -rf $BUILD_OUTPUT/_omni
-
-if [ "$(uname)" = "Darwin" ]; then
-
- # copy binaries
- cp -r "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/* "$BINARIES/Tor Browser.app/Contents/"
- rm -rf "$BINARIES/TorBrowser-Data/Browser/Caches/*.default/startupCache"
-
- # Self sign the Binaries
- cd "$BINARIES/Tor Browser.app/Contents/MacOS"
- "$SCRIPT_DIR/browser-self-sign-macos.sh"
-
-else
-
- # backup the startup script
- mv "$BINARIES/dev/Browser/firefox" "$BINARIES/dev/Browser/firefox.bak"
-
- # copy binaries
- cp -r "$RESDIR/"* "$BINARIES/dev/Browser"
- rm -rf "$BINARIES/dev/Browser/TorBrowser/Data/Browser/profile.default/startupCache"
-
- # shuffle firefox bin around and restore script to match a real deployment
- mv "$BINARIES/dev/Browser/firefox" "$BINARIES/dev/Browser/firefox.real"
- mv "$BINARIES/dev/Browser/firefox.bak" "$BINARIES/dev/Browser/firefox"
-
-fi
=====================================
tools/torbrowser/fetch.sh deleted
=====================================
@@ -1,40 +0,0 @@
-#!/bin/sh
-set -e
-
-BINARIES_DIR="$1"
-
-# download the current downloads.json
-wget https://aus1.torproject.org/torbrowser/update_3/alpha/downloads.json
-# get url for latest alpha linux package
-TOR_BROWSER_VERSION=$(grep -Eo "\"version\"\s*:\s*\"[0-9.a]+\"" downloads.json | grep -Eo "[0-9.a]+")
-if [ "$(uname)" = "Darwin" ]; then
- TOR_BROWSER_PACKAGE="tor-browser-macos-${TOR_BROWSER_VERSION}.dmg"
- else
- TOR_BROWSER_PACKAGE="tor-browser-linux-$(uname -m)-${TOR_BROWSER_VERSION}.tar.xz"
-fi
-TOR_BROWSER_PACKAGE_URL="https://dist.torproject.org/torbrowser/${TOR_BROWSER_VERSION}/${TOR_BROWSER…"
-
-# remove download manifest
-rm downloads.json
-
-# clear out previous tor-browser and previous package
-rm -rf "${BINARIES_DIR}"
-rm -f "${TOR_BROWSER_PACKAGE}"
-
-# download
-wget "${TOR_BROWSER_PACKAGE_URL}"
-mkdir -p "${BINARIES_DIR}"
-
-# and extract
-if [ "$(uname)" = "Darwin" ]
- then
- hdiutil attach "${TOR_BROWSER_PACKAGE}"
- cp -R "/Volumes/Tor Browser Alpha/Tor Browser Alpha.app" "${BINARIES_DIR}/Tor Browser.app"
- hdiutil detach "/Volumes/Tor Browser Alpha"
- else
- tar -xf "${TOR_BROWSER_PACKAGE}" -C "${BINARIES_DIR}"
- mv "${BINARIES_DIR}/tor-browser" "${BINARIES_DIR}/dev"
-fi
-
-# Final cleanup
-rm -f "${TOR_BROWSER_PACKAGE}"
=====================================
tools/torbrowser/ide.sh deleted
=====================================
@@ -1,7 +0,0 @@
-#!/bin/bash
-set -e
-IDE=$1
-DEV_ROOT=$2
-
-cd $DEV_ROOT
-./mach ide $IDE
=====================================
tools/torbrowser/jslint.sh deleted
=====================================
@@ -1,7 +0,0 @@
-#!/bin/bash
-set -e
-DEV_ROOT=$1
-JS_FILE=$2
-
-cd $DEV_ROOT
-./mach lint -l eslint --fix $JS_FILE
=====================================
tools/torbrowser/prepare-tests.sh deleted
=====================================
@@ -1,25 +0,0 @@
-#!/bin/sh
-set -e
-
-BINARIES="$1"
-BUILD_OUTPUT="$2"
-
-if [ ! -d "$BUILD_OUTPUT" ]; then
- echo "Error: $BUILD_OUTPUT directory does not exist."
- echo "Make sure to run `mach ./build` or `make -C tools/torbrowser build`."
- exit 1
-fi
-
-if [ ! -d "$BINARIES" ]; then
- echo "Error: $BINARIES directory does not exist."
- echo "Make sure to run `make -C tools/torbrowser fetch`."
- exit 1
-fi
-
-if [ "$(uname)" = "Darwin" ]; then
- cp -r "$BINARIES/Tor Browser.app/Contents/MacOS/Tor" "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/MacOS
- cp -r "$BINARIES/Tor Browser.app/Contents/Resources/fonts" "$BUILD_OUTPUT/dist/firefox/"*.app/Contents/Resources
-else
- cp -r "$BINARIES/dev/Browser/fonts" "$BUILD_OUTPUT/dist/bin"
- cp -r "$BINARIES/dev/Browser/TorBrowser" "$BUILD_OUTPUT/dist/bin"
-fi
=====================================
tools/yeet/__init__.py
=====================================
@@ -0,0 +1,3 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
=====================================
tools/yeet/auth.py
=====================================
@@ -0,0 +1,264 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import os
+import subprocess
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+from yeet.common import (
+ CANONICAL_GITLAB_PROJECT,
+ CANONICAL_GITLAB_REPO_NAME,
+ DEFAULT_SSH_HOST,
+ GITLAB_API_BASE,
+ TERM,
+ YEET_CONFIG_FILENAME,
+ prompt,
+)
+
+
+def _resolve_project(raw_username):
+ """Build a fork project path out of a GitLab username. Raises ValueError
+ if it's empty or the canonical repo's own namespace.
+ """
+ username = raw_username.strip()
+ if not username:
+ raise ValueError("A GitLab username is required.")
+
+ project = f"{username}/{CANONICAL_GITLAB_REPO_NAME}"
+ if project.lower() == CANONICAL_GITLAB_PROJECT.lower():
+ raise ValueError(
+ "That's the canonical repo's namespace, not a fork. Use your "
+ "own GitLab username instead."
+ )
+
+ return project
+
+
+def _prompt_fork():
+ print()
+ print(
+ TERM.yellow(
+ f"""`mach yeet remote` runs against your own fork of
+{CANONICAL_GITLAB_PROJECT}, never against the canonical repo
+directly -- that keeps CI runs off the shared project.
+
+If you haven't forked it yet, fork it first at:
+ https://gitlab.torproject.org/{CANONICAL_GITLAB_PROJECT}/-/forks/new
+
+Keep your fork up to date too. An outdated fork's .gitlab-ci.yml may be missing
+pieces this command relies on, so pipelines could fail or come back empty."""
+ )
+ )
+ print()
+
+ while True:
+ try:
+ return _resolve_project(prompt("Your GitLab username: "))
+ except ValueError as e:
+ print(TERM.red(f"ERROR! {e}"))
+
+
+def _gitlab_token_instructions(project):
+ return f"""
+Now you need a pipeline trigger token for your fork:
+ {project}
+
+This is NOT a personal access token -- it's specific to this one project, and
+it's the only kind that can actually run CI jobs here (their rules require it):
+
+ 1. Go to https://gitlab.torproject.org/{project}/-/settings/ci_cd#js-pipeline-trigge…
+ 2. Expand "Pipeline trigger tokens" and add a new one.
+ 3. Paste the token below.
+
+The project and token will be saved to {YEET_CONFIG_FILENAME} at the root of the repository
+and are not committed to it.
+""".strip()
+
+
+def _print_ssh_instructions():
+ print()
+ print(
+ TERM.yellow(
+ f"""`mach yeet` also uploads to and runs commands on a build server over SSH
+({DEFAULT_SSH_HOST} by default). Uploaded files are served from your
+account's public_html there, at:
+ https://<host>/~<username>
+
+Anything special about the connection -- port, jump host, a hardware key's
+PKCS11 provider, agent forwarding -- belongs in your ~/.ssh/config, not here:
+we just shell out to `ssh`. Whatever already works on your command line works
+for `mach yeet` too."""
+ )
+ )
+ print()
+
+
+def _prompt_ssh_host():
+ return prompt(f"SSH host [{DEFAULT_SSH_HOST}]: ").strip() or DEFAULT_SSH_HOST
+
+
+def _prompt_ssh_username(ssh_host):
+ while True:
+ username = prompt(f"Your username on {ssh_host}: ").strip()
+ if username:
+ return username
+ print(TERM.red("ERROR! Username cannot be empty."))
+
+
+def _prompt_token():
+ while True:
+ token = prompt("GitLab token: ", secret=True).strip()
+ if token:
+ return token
+ print(TERM.red("ERROR! Token cannot be empty."))
+
+
+def _verify_ssh(target):
+ """Try an actual SSH connection. stdin is /dev/null so ssh can't swallow
+ input buffered for us; its touch/PIN/passphrase prompts go through
+ /dev/tty and still reach the user.
+ """
+ try:
+ result = subprocess.run(
+ ["ssh", target, "true"],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ except FileNotFoundError:
+ print()
+ print(TERM.red("ERROR! No `ssh` binary found on PATH."))
+ return False
+ return result.returncode == 0
+
+
+def _verify_auth(project, token):
+ """Check that `project`/`token` are accepted by GitLab, without
+ actually triggering a pipeline.
+
+ GitLab authenticates the trigger token before validating the rest of
+ the request, so posting to the trigger endpoint without the required
+ `ref` param never queues a pipeline: a valid token/project combination
+ gets rejected with 400 (missing ref) instead, while an invalid token
+ or unknown project is rejected with 401/404 before `ref` is even
+ looked at.
+ """
+ url = f"{GITLAB_API_BASE}/projects/{urllib.parse.quote(project, safe='')}/trigger/pipeline"
+ data = urllib.parse.urlencode({"token": token}).encode()
+ request = urllib.request.Request(url, data=data, method="POST")
+ try:
+ with urllib.request.urlopen(request):
+ pass
+ except urllib.error.HTTPError as e:
+ return e.code == 400
+ else:
+ return True
+
+
+def run(command_context, **kwargs):
+ gitlab_username = kwargs.get("gitlab_username")
+ if gitlab_username is not None:
+ try:
+ project = _resolve_project(gitlab_username)
+ except ValueError as e:
+ print(TERM.red(f"ERROR! --gitlab-username: {e}"))
+ return 1
+ else:
+ project = _prompt_fork()
+
+ gitlab_token = kwargs.get("gitlab_token")
+ if gitlab_token is not None:
+ token = gitlab_token.strip()
+ if not token:
+ print()
+ print(TERM.red("ERROR! --gitlab-token was empty."))
+ return 1
+ else:
+ print()
+ print(_gitlab_token_instructions(project))
+ print()
+ token = _prompt_token()
+
+ verify = kwargs.get("verify", True)
+ if verify:
+ print()
+ print("Verifying credentials with GitLab...")
+ try:
+ verified = _verify_auth(project, token)
+ except urllib.error.URLError as e:
+ print()
+ print(TERM.red(f"ERROR! Could not reach GitLab: {e}"))
+ return 1
+
+ if not verified:
+ print()
+ print(
+ TERM.red(
+ "ERROR! GitLab rejected that project/token combination. "
+ "Double-check the fork name and the trigger token."
+ )
+ )
+ return 1
+ print(TERM.green("Credentials verified."))
+
+ ssh_host = kwargs.get("ssh_host")
+ ssh_username = kwargs.get("ssh_username")
+ if ssh_host is None or ssh_username is None:
+ _print_ssh_instructions()
+
+ if ssh_host is not None:
+ ssh_host = ssh_host.strip()
+ if not ssh_host:
+ print()
+ print(TERM.red("ERROR! --ssh-host was empty."))
+ return 1
+ else:
+ ssh_host = _prompt_ssh_host()
+
+ if ssh_username is not None:
+ ssh_username = ssh_username.strip()
+ if not ssh_username:
+ print()
+ print(TERM.red("ERROR! --ssh-user was empty."))
+ return 1
+ else:
+ ssh_username = _prompt_ssh_username(ssh_host)
+
+ if verify:
+ ssh_target = f"{ssh_username}@{ssh_host}"
+ print()
+ print(f"Verifying SSH access to {ssh_target}...")
+ if not _verify_ssh(ssh_target):
+ print()
+ print(
+ TERM.red(
+ f"ERROR! Could not SSH into {ssh_target}. Make sure you "
+ "can `ssh` there yourself first."
+ )
+ )
+ return 1
+ print(TERM.green("SSH access verified."))
+
+ tokens_path = Path(command_context.topsrcdir) / YEET_CONFIG_FILENAME
+ file_desc = os.open(
+ tokens_path, flags=os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=0o600
+ )
+ with open(file_desc, "w") as f:
+ json.dump(
+ {
+ "project": project,
+ "token": token,
+ "ssh_host": ssh_host,
+ "ssh_user": ssh_username,
+ },
+ f,
+ )
+ os.chmod(tokens_path, 0o600)
+
+ print()
+ print(TERM.green(f"Saved to {tokens_path}"))
+ return 0
=====================================
tools/yeet/common.py
=====================================
@@ -0,0 +1,66 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import getpass
+import json
+import sys
+from pathlib import Path
+
+from mozterm import Terminal
+
+TERM = Terminal()
+
+GITLAB_API_BASE = "https://gitlab.torproject.org/api/v4"
+
+# The canonical repo. `mach yeet remote` must never target this directly --
+# only a fork of it, so CI runs don't pile up on the shared project.
+CANONICAL_GITLAB_NAMESPACE = "tpo/applications"
+CANONICAL_GITLAB_REPO_NAME = "tor-browser-bundle-testsuite"
+CANONICAL_GITLAB_PROJECT = f"{CANONICAL_GITLAB_NAMESPACE}/{CANONICAL_GITLAB_REPO_NAME}"
+
+# Project and token saved by `mach yeet auth`.
+YEET_CONFIG_FILENAME = ".yeet.json"
+
+# The default server `mach yeet` uploads to and runs commands on over SSH.
+# Uploaded files are served from the user's public_html on it.
+DEFAULT_SSH_HOST = "tb-build-03.torproject.org"
+
+
+def prompt(message, secret=False):
+ """Read a line of user input, first discarding anything typed before the
+ prompt appeared so stray keystrokes aren't taken as the answer.
+ """
+ if sys.stdin.isatty():
+ try:
+ import termios
+
+ termios.tcflush(sys.stdin, termios.TCIFLUSH)
+ except ImportError:
+ pass
+ if secret:
+ return getpass.getpass(message)
+ return input(message)
+
+
+def confirm(message):
+ """Ask a yes/no question, defaulting to no, until a valid answer is given."""
+ while True:
+ answer = prompt(f"{message} [y/N]: ").strip().lower()
+ if answer in ("y", "yes"):
+ return True
+ if answer in ("", "n", "no"):
+ return False
+ print(TERM.red("ERROR! Please answer 'y' or 'n'."))
+
+
+def read_config(topsrcdir):
+ """Read the project/token/ssh_* config saved by `mach yeet auth`, or
+ None if it hasn't been run yet.
+ """
+ config_path = Path(topsrcdir) / YEET_CONFIG_FILENAME
+ if not config_path.is_file():
+ return None
+
+ with open(config_path) as f:
+ return json.load(f)
=====================================
tools/yeet/mach_commands.py
=====================================
@@ -0,0 +1,141 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from mach.decorators import Command, CommandArgument, SubCommand # noqa: I001
+
+from yeet import remote
+
+
+@Command(
+ "yeet",
+ category="ci",
+ description="TODO: build / test remotely from the current state of the repo.",
+)
+def yeet(command_context):
+ # TODO: this will be the main "yeet" command -- push, build and (maybe)
+ # test remotely from the current state of the local repo, rather than
+ # requiring an already-published build like `yeet remote` does.
+ pass
+
+
+@SubCommand(
+ "yeet",
+ "remote",
+ description="Trigger a tor-browser-bundle-testsuite CI job against an "
+ "already-published build, for a single platform.",
+)
+@CommandArgument(
+ "--platform",
+ default=None,
+ choices=remote.PLATFORMS,
+ help="Platform to test. Prompted for if not provided.",
+)
+@CommandArgument(
+ "--channel",
+ default=None,
+ choices=remote.ANDROID_CHANNELS,
+ help="Android build channel/flavor to install (only used with "
+ "--platform android_x86_64). Prompted for if not provided.",
+)
+@CommandArgument(
+ "installer_url",
+ help="URL of the installer to test, or a local file path to upload first.",
+)
+@CommandArgument(
+ "--sha256sums-url", default=None, help="URL of the build's sha256sums file."
+)
+@CommandArgument(
+ "--artifacts-url",
+ default=None,
+ help="URL of the build's artifacts directory. Inferred from the "
+ "in-tree browser version and --platform if not provided.",
+)
+@CommandArgument(
+ "--mozharness-url",
+ default=None,
+ help="URL of the mozharness.zip to use. Inferred from the in-tree "
+ "browser version and --platform if not provided.",
+)
+@CommandArgument(
+ "--version",
+ default=None,
+ help="Browser version to use when inferring --artifacts-url and "
+ "--mozharness-url. Defaults to the in-tree version "
+ "(browser/config/version.txt).",
+)
+@CommandArgument(
+ "--ref",
+ default="main",
+ help="tor-browser-bundle-testsuite ref to run on. Must have a "
+ ".gitlab-ci.yml, which the default branch may not.",
+)
+@CommandArgument(
+ "--tag",
+ dest="tags",
+ action="append",
+ default=None,
+ help="Test tag to filter tests by (can be passed multiple times, e.g. "
+ "--tag tor --tag base-browser). Defaults to '--tag tor --tag base-browser'.",
+)
+@CommandArgument(
+ "--dry-run",
+ action="store_true",
+ default=False,
+ help="Print the curl command instead of triggering the pipeline.",
+)
+@CommandArgument(
+ "--yes",
+ "-y",
+ dest="assume_yes",
+ action="store_true",
+ default=False,
+ help="Upload a local installer without asking for confirmation.",
+)
+def yeet_remote(command_context, **kwargs):
+ # With action="append", argparse appends to a non-None default instead of
+ # replacing it, so the default tags are applied here only if none were given.
+ if kwargs["tags"] is None:
+ kwargs["tags"] = ["tor", "base-browser"]
+ return remote.run(command_context, **kwargs)
+
+
+@SubCommand(
+ "yeet",
+ "auth",
+ description="Save a GitLab project and access token for running CI jobs.",
+)
+@CommandArgument(
+ "--no-verify",
+ dest="verify",
+ action="store_false",
+ help="Skip checking the GitLab and SSH credentials before saving them.",
+)
+@CommandArgument(
+ "--gitlab-username",
+ default=None,
+ help="GitLab username to use, skipping that prompt.",
+)
+@CommandArgument(
+ "--gitlab-token",
+ default=None,
+ help=(
+ "GitLab pipeline trigger token to use, skipping that prompt. Note "
+ "this may end up in your shell history."
+ ),
+)
+@CommandArgument(
+ "--ssh-user",
+ dest="ssh_username",
+ default=None,
+ help="Username on the build server, skipping that prompt.",
+)
+@CommandArgument(
+ "--ssh-host",
+ default=None,
+ help="Build server to upload to and run commands on over SSH, skipping that prompt.",
+)
+def yeet_auth(command_context, **kwargs):
+ from yeet import auth
+
+ return auth.run(command_context, **kwargs)
=====================================
tools/yeet/remote.py
=====================================
@@ -0,0 +1,228 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import os
+import shlex
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from yeet import upload
+from yeet.common import (
+ GITLAB_API_BASE,
+ TERM,
+ prompt,
+ read_config,
+)
+
+PLATFORM_TOOLCHAIN_DIR = {
+ "debian_x86_64": "linux-x86_64",
+ "windows_x86_64": "windows-x86_64",
+ "macos_x86_64": "macos-x86_64",
+ "android_x86_64": "android-x86_64",
+}
+
+PLATFORMS = list(PLATFORM_TOOLCHAIN_DIR.keys())
+
+GITLAB_REQUEST_TIMEOUT_SECONDS = 30
+
+TOOLCHAINS_URL_BASE = "https://nightlies.tbb.torproject.org/nightly-builds/toolchains"
+
+# Each Android build channel/flavor ships under its own package name, so the
+# pipeline needs to be told which one to install.
+ANDROID_CHANNEL_PACKAGE_NAMES = {
+ "debug": "org.torproject.torbrowser_debug",
+ "nightly": "org.torproject.torbrowser_nightly",
+ "alpha": "org.torproject.torbrowser_alpha",
+ "release": "org.torproject.torbrowser",
+}
+ANDROID_CHANNELS = list(ANDROID_CHANNEL_PACKAGE_NAMES)
+
+
+def _read_browser_version(topsrcdir):
+ version_path = os.path.join(topsrcdir, "browser", "config", "version.txt")
+ with open(version_path) as f:
+ return f.read().strip()
+
+
+def _resolve_version(topsrcdir, version):
+ if version:
+ return version
+
+ version = _read_browser_version(topsrcdir)
+ print(
+ TERM.yellow(
+ f"""Inferred platform version {version} from browser/config/version.txt.
+Pass --version if this isn't the version you want to test."""
+ )
+ )
+ return version
+
+
+def _artifacts_url(version, platform):
+ return f"{TOOLCHAINS_URL_BASE}/{version}/{PLATFORM_TOOLCHAIN_DIR[platform]}/"
+
+
+def _mozharness_url(version, platform):
+ return f"{_artifacts_url(version, platform)}mozharness.zip"
+
+
+def _curl_command(url, headers, data):
+ args = ["curl", "--request", "POST"]
+ for name, value in headers.items():
+ args += ["--header", f"{name}: {value}"]
+ args += ["--data", data.decode("utf-8"), url]
+ return shlex.join(args)
+
+
+def _resolve_installer_url(topsrcdir, installer, platform, assume_yes, dry_run):
+ """Accept either an installer URL directly, or a local file path to
+ upload first. On a dry run a local file is not uploaded, and a
+ placeholder URL is returned instead. Raises whatever
+ `upload.run` raises on failure.
+ """
+ if urllib.parse.urlparse(installer).scheme in ("http", "https"):
+ return installer
+ if dry_run:
+ file_path = upload.resolve_file(installer)
+ print(TERM.yellow(f"Dry run: not uploading {file_path}."))
+ return f"<URL of uploaded {file_path.name}>"
+ return upload.run(topsrcdir, installer, platform, assume_yes=assume_yes)
+
+
+def _prompt_platform():
+ print()
+ print(
+ TERM.bold(
+ "Select the platform you are testing for (if not listed, tests are not supported yet):"
+ )
+ )
+ for i, platform in enumerate(PLATFORMS, 1):
+ print(f" {TERM.cyan(str(i))}) {platform}")
+ print()
+
+ while True:
+ choice = prompt(f"Platform [1-{len(PLATFORMS)}]: ").strip()
+ if choice.isdigit() and 1 <= int(choice) <= len(PLATFORMS):
+ print()
+ return PLATFORMS[int(choice) - 1]
+ print(TERM.red(f"ERROR! Please enter a number between 1 and {len(PLATFORMS)}."))
+
+
+def _prompt_channel():
+ print()
+ print(TERM.bold("Select the Android build channel/flavor you are testing:"))
+ for i, channel in enumerate(ANDROID_CHANNELS, 1):
+ print(f" {TERM.cyan(str(i))}) {channel}")
+ print()
+
+ while True:
+ choice = prompt(f"Channel [1-{len(ANDROID_CHANNELS)}]: ").strip()
+ if choice.isdigit() and 1 <= int(choice) <= len(ANDROID_CHANNELS):
+ print()
+ return ANDROID_CHANNELS[int(choice) - 1]
+ print(
+ TERM.red(
+ f"ERROR! Please enter a number between 1 and {len(ANDROID_CHANNELS)}."
+ )
+ )
+
+
+def run(command_context, **kwargs):
+ # TODO(tor-browser-bundle-testsuite#40120): this runs whatever the pipeline
+ # runs, indiscriminately -- fine for now since marionette is the only suite
+ # it has, but once others (xpcshell, cppunittest, mochitest, ...) exist, add
+ # a --suite argument here and thread it into `inputs` so a run can be scoped
+ # to just one.
+ config = read_config(command_context.topsrcdir)
+ if config is None:
+ print(TERM.red("No GitLab fork/token found, run `mach yeet auth` first."))
+ return 1
+
+ installer_url = kwargs["installer_url"].strip()
+ if not installer_url:
+ print(TERM.red("ERROR! The installer URL or path was empty."))
+ return 1
+
+ platform = kwargs.get("platform") or _prompt_platform()
+ dry_run = kwargs.get("dry_run", False)
+
+ try:
+ installer_url = _resolve_installer_url(
+ command_context.topsrcdir,
+ installer_url,
+ platform,
+ kwargs.get("assume_yes", False),
+ dry_run,
+ )
+ except (FileNotFoundError, RuntimeError) as e:
+ print()
+ print(TERM.red(f"ERROR! {e}"))
+ return 1
+
+ package_name = None
+ if platform == "android_x86_64":
+ channel = kwargs.get("channel") or _prompt_channel()
+ if channel not in ANDROID_CHANNEL_PACKAGE_NAMES:
+ print(TERM.red(f"ERROR! Unknown channel {channel!r}."))
+ return 1
+ package_name = ANDROID_CHANNEL_PACKAGE_NAMES[channel]
+
+ artifacts_url = kwargs.get("artifacts_url")
+ mozharness_url = kwargs.get("mozharness_url")
+ if not artifacts_url or not mozharness_url:
+ version = _resolve_version(command_context.topsrcdir, kwargs.get("version"))
+ if not artifacts_url:
+ artifacts_url = _artifacts_url(version, platform)
+ if not mozharness_url:
+ mozharness_url = _mozharness_url(version, platform)
+
+ inputs = {
+ "mozharness_url": mozharness_url,
+ f"{platform}_installer_url": installer_url,
+ f"{platform}_artifacts_url": artifacts_url,
+ }
+ if package_name:
+ inputs[f"{platform}_package_name"] = package_name
+ if sha256sums_url := kwargs.get("sha256sums_url"):
+ inputs[f"{platform}_sha256sums_url"] = sha256sums_url
+ if tags := kwargs.get("tags"):
+ inputs["tags"] = shlex.join(arg for tag in tags for arg in ("--tag", tag))
+
+ project_id = urllib.parse.quote(config["project"], safe="")
+ url = f"{GITLAB_API_BASE}/projects/{project_id}/trigger/pipeline"
+ headers = {"Content-Type": "application/json"}
+ data = json.dumps({
+ "token": config["token"],
+ "ref": kwargs.get("ref", "main"),
+ "inputs": inputs,
+ }).encode("utf-8")
+
+ if dry_run:
+ print()
+ print(TERM.cyan(_curl_command(url, headers, data)))
+ print()
+ return 0
+
+ request = urllib.request.Request(url, data=data, headers=headers, method="POST")
+
+ try:
+ with urllib.request.urlopen(
+ request, timeout=GITLAB_REQUEST_TIMEOUT_SECONDS
+ ) as response:
+ result = json.load(response)
+ except urllib.error.HTTPError as e:
+ body = e.read().decode("utf-8", "replace")
+ print(
+ TERM.red(f"ERROR! Failed to trigger pipeline: {e.code} {e.reason}\n{body}")
+ )
+ return 1
+ except urllib.error.URLError as e:
+ print(TERM.red(f"ERROR! Could not reach GitLab: {e}"))
+ return 1
+
+ print()
+ print(TERM.green(f"Pipeline triggered: {result.get('web_url')}"))
+ return 0
=====================================
tools/yeet/tests/python/conftest.py
=====================================
@@ -0,0 +1,23 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+
+from yeet import common # noqa: E402
+
+
+def write_config(tmp_path, **overrides):
+ """Write a `.yeet.json` under `tmp_path`, as `mach yeet auth` would,
+ for tests that need one already in place.
+ """
+ config = {
+ "project": "bea/tor-browser-bundle-testsuite",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+ config.update(overrides)
+ with open(tmp_path / common.YEET_CONFIG_FILENAME, "w") as f:
+ json.dump(config, f)
+ return config
=====================================
tools/yeet/tests/python/python.toml
=====================================
@@ -0,0 +1,10 @@
+[DEFAULT]
+subsuite = "base-browser"
+
+["test_auth.py"]
+
+["test_upload.py"]
+
+["test_remote.py"]
+
+["test_common.py"]
=====================================
tools/yeet/tests/python/test_auth.py
=====================================
@@ -0,0 +1,435 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import urllib.error
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from yeet import auth, common
+
+
+def _set_inputs(monkeypatch, *values):
+ values = iter(values)
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+
+def _forbid_prompts(monkeypatch):
+ """Make input()/getpass() blow up instead of hanging, so a test can
+ assert that a fully non-interactive call never prompts."""
+
+ def _fail(prompt=""):
+ raise AssertionError(f"unexpected prompt: {prompt!r}")
+
+ monkeypatch.setattr("builtins.input", _fail)
+ monkeypatch.setattr(common.getpass, "getpass", _fail)
+
+
+(a)pytest.mark.parametrize("value", ["bea", " bea ", "bea.b", "bea_b-1"])
+def test_resolve_project_accepts_username(value):
+ project = auth._resolve_project(value)
+
+ assert project == f"{value.strip()}/{common.CANONICAL_GITLAB_REPO_NAME}"
+
+
+(a)pytest.mark.parametrize(
+ "value",
+ [
+ common.CANONICAL_GITLAB_NAMESPACE,
+ common.CANONICAL_GITLAB_NAMESPACE.upper(),
+ f" {common.CANONICAL_GITLAB_NAMESPACE} ",
+ ],
+)
+def test_resolve_project_rejects_canonical_namespace(value):
+ with pytest.raises(ValueError, match="canonical"):
+ auth._resolve_project(value)
+
+
+def test_resolve_project_accepts_top_level_group_of_canonical_namespace():
+ group = common.CANONICAL_GITLAB_NAMESPACE.split("/", 1)[0]
+
+ assert auth._resolve_project(group) == (
+ f"{group}/{common.CANONICAL_GITLAB_REPO_NAME}"
+ )
+
+
+def test_prompt_fork_rejects_canonical_namespace(monkeypatch, capsys):
+ canonical_namespace = common.CANONICAL_GITLAB_NAMESPACE
+ _set_inputs(monkeypatch, canonical_namespace, "bea")
+
+ project = auth._prompt_fork()
+
+ assert project == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+ assert "not a" in capsys.readouterr().out.lower()
+
+
+(a)pytest.mark.parametrize("value", ["", " ", "\t\n"])
+def test_resolve_project_rejects_blank_username(value):
+ with pytest.raises(ValueError):
+ auth._resolve_project(value)
+
+
+def test_prompt_fork_rejects_empty_username(monkeypatch):
+ _set_inputs(monkeypatch, "", " \t ", "bea")
+
+ project = auth._prompt_fork()
+
+ assert project == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+
+
+(a)pytest.mark.parametrize("status", [400])
+def test_verify_auth_accepts_valid_token(monkeypatch, status):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.HTTPError("url", status, "msg", None, None)
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ assert auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok") is True
+
+
+(a)pytest.mark.parametrize("status", [401, 404])
+def test_verify_auth_rejects_bad_token_or_project(monkeypatch, status):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.HTTPError("url", status, "msg", None, None)
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ assert auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok") is False
+
+
+def test_verify_auth_propagates_network_errors(monkeypatch):
+ def fake_urlopen(request, *args, **kwargs):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake_urlopen)
+
+ with pytest.raises(urllib.error.URLError):
+ auth._verify_auth("bea/tor-browser-bundle-testsuite", "tok")
+
+
+def test_verify_ssh_success(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs))
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(auth.subprocess, "run", fake_run)
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is True
+ cmd, kwargs = calls[0]
+ assert cmd[-2:] == ["bea(a)tb-build-03.torproject.org", "true"]
+ assert kwargs["stdin"] is auth.subprocess.DEVNULL
+
+
+def test_verify_ssh_failure(monkeypatch):
+ monkeypatch.setattr(
+ auth.subprocess,
+ "run",
+ lambda *args, **kwargs: SimpleNamespace(returncode=255),
+ )
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is False
+
+
+def test_verify_ssh_missing_binary(monkeypatch, capsys):
+ def fake_run(*args, **kwargs):
+ raise FileNotFoundError()
+
+ monkeypatch.setattr(auth.subprocess, "run", fake_run)
+
+ assert auth._verify_ssh("bea(a)tb-build-03.torproject.org") is False
+ assert "no `ssh` binary" in capsys.readouterr().out.lower()
+
+
+def test_run_saves_config_and_skips_verification(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False)
+
+ assert result == 0
+ config_path = tmp_path / common.YEET_CONFIG_FILENAME
+ with open(config_path) as f:
+ saved = json.load(f)
+ assert saved == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+ assert (config_path.stat().st_mode & 0o777) == 0o600
+
+
+def test_prompt_ssh_username_reprompts_until_non_empty(monkeypatch, capsys):
+ _set_inputs(monkeypatch, "", " ", "bea")
+
+ assert auth._prompt_ssh_username(common.DEFAULT_SSH_HOST) == "bea"
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+def test_prompt_ssh_host_defaults_when_empty(monkeypatch):
+ _set_inputs(monkeypatch, " ")
+
+ assert auth._prompt_ssh_host() == common.DEFAULT_SSH_HOST
+
+
+def test_run_prompts_for_ssh_host(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "build.example.com", "bea")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context, verify=False, gitlab_username="bea", gitlab_token="s3cr3t"
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved["ssh_host"] == "build.example.com"
+ assert saved["ssh_user"] == "bea"
+
+
+def test_prompt_token_reprompts_until_non_empty(monkeypatch, capsys):
+ values = iter(["", " ", "s3cr3t"])
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": next(values))
+
+ assert auth._prompt_token() == "s3cr3t"
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+def test_run_aborts_when_gitlab_verification_fails(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: False)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ "ERROR! GitLab rejected that project/token combination."
+ in capsys.readouterr().out
+ )
+
+
+def test_run_aborts_when_gitlab_unreachable(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+
+ def raise_url_error(project, token):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(auth, "_verify_auth", raise_url_error)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ "ERROR! Could not reach GitLab: <urlopen error unreachable>"
+ in capsys.readouterr().out
+ )
+
+
+def test_run_aborts_when_ssh_verification_fails(tmp_path, monkeypatch, capsys):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: False)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert (
+ f"ERROR! Could not SSH into bea(a){common.DEFAULT_SSH_HOST}."
+ in capsys.readouterr().out
+ )
+
+
+def test_run_saves_config_when_verification_succeeds(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, "bea", "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: True)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=True)
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+def test_run_uses_cli_gitlab_username_and_still_prompts_for_rest(tmp_path, monkeypatch):
+ # ssh host and username aren't given via CLI, so they're the only things
+ # prompted for.
+ _set_inputs(monkeypatch, "", "bea")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": "s3cr3t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False, gitlab_username="bea")
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved["project"] == f"bea/{common.CANONICAL_GITLAB_REPO_NAME}"
+ assert saved["ssh_user"] == "bea"
+
+
+def test_run_rejects_invalid_cli_gitlab_username(tmp_path, monkeypatch, capsys):
+ _forbid_prompts(monkeypatch)
+ canonical_namespace = common.CANONICAL_GITLAB_NAMESPACE
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context, verify=False, gitlab_username=canonical_namespace
+ )
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert "not a" in capsys.readouterr().out.lower()
+
+
+def test_run_fully_noninteractive_with_all_cli_args(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=False,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host=common.DEFAULT_SSH_HOST,
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ saved = json.load(f)
+ assert saved == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+def test_run_saves_cli_ssh_host(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ targets = []
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(
+ auth, "_verify_ssh", lambda target: targets.append(target) or True
+ )
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=True,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host="build.example.com",
+ )
+
+ assert result == 0
+ assert targets == ["bea(a)build.example.com"]
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f)["ssh_host"] == "build.example.com"
+
+
+def test_run_fully_noninteractive_with_verification(tmp_path, monkeypatch):
+ _forbid_prompts(monkeypatch)
+ monkeypatch.setattr(auth, "_verify_auth", lambda project, token: True)
+ monkeypatch.setattr(auth, "_verify_ssh", lambda target: True)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=True,
+ gitlab_username="bea",
+ gitlab_token="s3cr3t",
+ ssh_username="bea",
+ ssh_host=common.DEFAULT_SSH_HOST,
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": common.DEFAULT_SSH_HOST,
+ "ssh_user": "bea",
+ }
+
+
+_CLI_ARGS = {
+ "gitlab_username": "bea",
+ "gitlab_token": "s3cr3t",
+ "ssh_username": "bea",
+ "ssh_host": "build.example.com",
+}
+
+_SAVED_CONFIG = {
+ "project": f"bea/{common.CANONICAL_GITLAB_REPO_NAME}",
+ "token": "s3cr3t",
+ "ssh_host": "build.example.com",
+ "ssh_user": "bea",
+}
+
+
+(a)pytest.mark.parametrize("padding", [" ", "\t", "\n", " \t\n "])
+def test_run_trims_cli_args(tmp_path, monkeypatch, padding):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(
+ command_context,
+ verify=False,
+ **{name: f"{padding}{value}{padding}" for name, value in _CLI_ARGS.items()},
+ )
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == _SAVED_CONFIG
+
+
+def test_run_trims_prompted_values(tmp_path, monkeypatch):
+ _set_inputs(monkeypatch, " bea\t", " build.example.com\n", "\tbea ")
+ monkeypatch.setattr(common.getpass, "getpass", lambda prompt="": " s3cr3t\t")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False)
+
+ assert result == 0
+ with open(tmp_path / common.YEET_CONFIG_FILENAME) as f:
+ assert json.load(f) == _SAVED_CONFIG
+
+
+(a)pytest.mark.parametrize("arg", list(_CLI_ARGS))
+(a)pytest.mark.parametrize("blank", ["", " ", "\t\n"])
+def test_run_rejects_blank_cli_arg(tmp_path, monkeypatch, capsys, arg, blank):
+ _forbid_prompts(monkeypatch)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = auth.run(command_context, verify=False, **{**_CLI_ARGS, arg: blank})
+
+ assert result == 1
+ assert not (tmp_path / common.YEET_CONFIG_FILENAME).exists()
+ assert "ERROR!" in capsys.readouterr().out
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_common.py
=====================================
@@ -0,0 +1,80 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from yeet import common
+
+
+(a)pytest.mark.parametrize("secret", [False, True])
+def test_prompt_flushes_pending_tty_input(monkeypatch, secret):
+ termios = pytest.importorskip("termios")
+ events = []
+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))
+ monkeypatch.setattr(
+ termios, "tcflush", lambda fd, queue: events.append(("flush", queue))
+ )
+ monkeypatch.setattr(
+ "builtins.input", lambda message="": events.append("input") or "plain"
+ )
+ monkeypatch.setattr(
+ common.getpass,
+ "getpass",
+ lambda message="": events.append("getpass") or "hidden",
+ )
+
+ answer = common.prompt("Q: ", secret=secret)
+
+ assert answer == ("hidden" if secret else "plain")
+ assert events == [
+ ("flush", termios.TCIFLUSH),
+ "getpass" if secret else "input",
+ ]
+
+
+def test_prompt_skips_flush_when_not_a_tty(monkeypatch):
+ termios = pytest.importorskip("termios")
+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: False))
+ monkeypatch.setattr(
+ termios,
+ "tcflush",
+ lambda *args: pytest.fail("tcflush called on non-tty stdin"),
+ )
+ monkeypatch.setattr("builtins.input", lambda message="": "piped")
+
+ assert common.prompt("Q: ") == "piped"
+
+
+(a)pytest.mark.parametrize(
+ "answers,expected",
+ [
+ (["y"], True),
+ (["YES"], True),
+ ([" yes "], True),
+ ([""], False),
+ (["n"], False),
+ (["No"], False),
+ (["maybe", "y"], True),
+ ],
+)
+def test_confirm(monkeypatch, answers, expected):
+ answers = iter(answers)
+ monkeypatch.setattr("builtins.input", lambda message="": next(answers))
+
+ assert common.confirm("Go?") is expected
+
+
+def test_confirm_reprompts_on_invalid_answer(monkeypatch, capsys):
+ answers = iter(["maybe", "sure", "n"])
+ monkeypatch.setattr("builtins.input", lambda message="": next(answers))
+
+ assert common.confirm("Go?") is False
+ assert capsys.readouterr().out.count("ERROR!") == 2
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_remote.py
=====================================
@@ -0,0 +1,636 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import json
+import shlex
+import urllib.error
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from conftest import write_config
+from yeet import remote
+
+
+class _FakeResponse:
+ def __init__(self, body):
+ self._body = body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def read(self):
+ return self._body
+
+
+def _write_version(tmp_path, version="153.2.0"):
+ version_dir = tmp_path / "browser" / "config"
+ version_dir.mkdir(parents=True)
+ (version_dir / "version.txt").write_text(f"{version}\n")
+
+
+def test_read_browser_version(tmp_path):
+ _write_version(tmp_path, "1.2.3")
+
+ assert remote._read_browser_version(tmp_path) == "1.2.3"
+
+
+def test_resolve_version_prefers_given_value(tmp_path):
+
+ assert remote._resolve_version(tmp_path, "9.9.9") == "9.9.9"
+
+
+def test_resolve_version_falls_back_to_in_tree_version(tmp_path, capsys):
+ _write_version(tmp_path, "1.2.3")
+
+ assert remote._resolve_version(tmp_path, None) == "1.2.3"
+ assert "1.2.3" in capsys.readouterr().out
+
+
+def test_artifacts_and_mozharness_urls():
+ artifacts = remote._artifacts_url("1.2.3", "android_x86_64")
+
+ assert artifacts == f"{remote.TOOLCHAINS_URL_BASE}/1.2.3/android-x86_64/"
+ assert remote._mozharness_url("1.2.3", "android_x86_64") == (
+ artifacts + "mozharness.zip"
+ )
+
+
+def test_curl_command_includes_header_data_and_url():
+ command = remote._curl_command(
+ "https://example.org/trigger",
+ {"Content-Type": "application/json"},
+ b'{"a": 1}',
+ )
+
+ assert shlex.split(command) == [
+ "curl",
+ "--request",
+ "POST",
+ "--header",
+ "Content-Type: application/json",
+ "--data",
+ '{"a": 1}',
+ "https://example.org/trigger",
+ ]
+
+
+def _failing_upload_run(topsrcdir, file, platform, assume_yes):
+ raise RuntimeError("boom")
+
+
+def test_resolve_installer_url_passes_through_a_url(tmp_path):
+
+ url = remote._resolve_installer_url(
+ tmp_path,
+ "https://example.org/app.apk",
+ "android_x86_64",
+ assume_yes=False,
+ dry_run=False,
+ )
+
+ assert url == "https://example.org/app.apk"
+
+
+def test_resolve_installer_url_uploads_a_local_path(tmp_path, monkeypatch):
+ calls = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ calls.append((topsrcdir, file, platform, assume_yes))
+ return "https://tb-build-03.torproject.org/~bea/yeet/ts.apk"
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ url = remote._resolve_installer_url(
+ tmp_path,
+ "/tmp/app.apk",
+ "android_x86_64",
+ assume_yes=True,
+ dry_run=False,
+ )
+
+ assert url == "https://tb-build-03.torproject.org/~bea/yeet/ts.apk"
+ assert calls == [(tmp_path, "/tmp/app.apk", "android_x86_64", True)]
+
+
+def test_resolve_installer_url_propagates_upload_error(tmp_path, monkeypatch):
+ monkeypatch.setattr(remote.upload, "run", _failing_upload_run)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ remote._resolve_installer_url(
+ tmp_path,
+ "/tmp/app.apk",
+ "android_x86_64",
+ assume_yes=False,
+ dry_run=False,
+ )
+
+
+def test_prompt_platform_rejects_invalid_choice_then_accepts(monkeypatch):
+ values = iter(["0", "99", "not-a-number", "2"])
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+ assert remote._prompt_platform() == remote.PLATFORMS[1]
+
+
+def test_prompt_channel_rejects_invalid_choice_then_accepts(monkeypatch):
+ values = iter(["0", "99", "not-a-number", "2"])
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(values))
+
+ assert remote._prompt_channel() == remote.ANDROID_CHANNELS[1]
+
+
+def _run_kwargs(**overrides):
+ kwargs = dict(
+ platform="android_x86_64",
+ channel="debug",
+ installer_url="https://example.org/app.apk",
+ sha256sums_url=None,
+ artifacts_url="https://example.org/artifacts/",
+ mozharness_url="https://example.org/mozharness.zip",
+ version=None,
+ ref="main",
+ tags=["tor"],
+ dry_run=False,
+ )
+ kwargs.update(overrides)
+ return kwargs
+
+
+def test_run_aborts_without_config(tmp_path, capsys):
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ assert "mach yeet auth" in capsys.readouterr().out
+
+
+def test_run_dry_run_prints_curl_and_skips_network(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fail_urlopen(*args, **kwargs):
+ raise AssertionError("urlopen should not be called in dry-run mode")
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fail_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs(dry_run=True))
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "curl --request POST" in out
+ assert "app.apk" in out
+
+
+def test_run_prompts_for_platform_when_missing(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ calls = []
+
+ def fake_prompt_platform():
+ calls.append(True)
+ return "debian_x86_64"
+
+ monkeypatch.setattr(remote, "_prompt_platform", fake_prompt_platform)
+
+ result = remote.run(command_context, **_run_kwargs(platform=None, dry_run=True))
+
+ assert result == 0
+ assert len(calls) == 1
+ assert "debian_x86_64_installer_url" in capsys.readouterr().out
+
+
+def test_run_prompts_for_channel_when_android_and_missing(
+ tmp_path, monkeypatch, capsys
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ calls = []
+
+ def fake_prompt_channel():
+ calls.append(True)
+ return "nightly"
+
+ monkeypatch.setattr(remote, "_prompt_channel", fake_prompt_channel)
+
+ result = remote.run(command_context, **_run_kwargs(channel=None, dry_run=True))
+
+ assert result == 0
+ assert len(calls) == 1
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] in capsys.readouterr().out
+
+
+def test_run_adds_package_name_input_for_android(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs(channel="nightly", dry_run=True))
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "android_x86_64_package_name" in out
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] in out
+
+
+def test_run_skips_channel_for_non_android_platforms(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote,
+ "_prompt_channel",
+ lambda: (_ for _ in ()).throw(AssertionError("should not prompt")),
+ )
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(
+ platform="debian_x86_64",
+ channel=None,
+ artifacts_url="https://example.org/artifacts/",
+ mozharness_url="https://example.org/mozharness.zip",
+ dry_run=True,
+ ),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "package_name" not in out
+
+
+def test_run_rejects_unknown_channel(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(command_context, **_run_kwargs(channel="not-a-channel"))
+
+ assert result == 1
+ assert "ERROR! Unknown channel 'not-a-channel'." in capsys.readouterr().out
+
+
+(a)pytest.mark.parametrize("dry_run", [False, True])
+(a)pytest.mark.parametrize("installer_url", ["", " ", "\t\n"])
+def test_run_rejects_empty_installer(
+ tmp_path, monkeypatch, capsys, installer_url, dry_run
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote, "_prompt_platform", lambda: pytest.fail("prompted for platform")
+ )
+ monkeypatch.setattr(
+ remote.upload, "run", lambda *args, **kwargs: pytest.fail("uploaded")
+ )
+ monkeypatch.setattr(
+ remote.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("pipeline triggered"),
+ )
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform=None, installer_url=installer_url, dry_run=dry_run),
+ )
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert "ERROR! The installer URL or path was empty." in out
+ assert "curl" not in out
+
+
+def test_run_trims_installer_url(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(installer_url=" https://example.org/app.apk\n", dry_run=True),
+ )
+
+ assert result == 0
+ assert '"android_x86_64_installer_url": "https://example.org/app.apk"' in (
+ capsys.readouterr().out
+ )
+
+
+def test_run_ignores_channel_for_non_android_platforms(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform="debian_x86_64", channel="nightly", dry_run=True),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "package_name" not in out
+ assert remote.ANDROID_CHANNEL_PACKAGE_NAMES["nightly"] not in out
+
+
+(a)pytest.mark.parametrize(
+ "platform,installer",
+ [
+ ("debian_x86_64", "tor-browser-linux-x86_64.tar.xz"),
+ ("windows_x86_64", "tor-browser-windows-x86_64-portable.exe"),
+ ("macos_x86_64", "tor-browser-macos.dmg"),
+ ("android_x86_64", "tor-browser-android-x86_64.apk"),
+ ],
+)
+def test_run_uploads_a_local_path_before_triggering(
+ tmp_path, monkeypatch, platform, installer
+):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ installer_path = f"/tmp/{installer}"
+ uploaded_url = (
+ f"https://tb-build-03.torproject.org/~bea/yeet/ts-{platform}/{installer}"
+ )
+ uploads = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ uploads.append((file, platform))
+ return uploaded_url
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(platform=platform, installer_url=installer_path),
+ )
+
+ assert result == 0
+ assert uploads == [(installer_path, platform)]
+ inputs = json.loads(requests[0].data)["inputs"]
+ assert inputs[f"{platform}_installer_url"] == uploaded_url
+ assert (f"{platform}_package_name" in inputs) == (platform == "android_x86_64")
+
+
+def test_run_prompts_for_platform_before_uploading(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(remote, "_prompt_platform", lambda: "debian_x86_64")
+ seen = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ seen.append(platform)
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ remote.run(
+ command_context, **_run_kwargs(platform=None, installer_url="/tmp/app.tar.xz")
+ )
+
+ assert seen == ["debian_x86_64"]
+
+
+(a)pytest.mark.parametrize("assume_yes", [False, True])
+def test_run_forwards_assume_yes_to_upload(tmp_path, monkeypatch, assume_yes):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ seen = []
+
+ def fake_upload_run(topsrcdir, file, platform, assume_yes):
+ seen.append(assume_yes)
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(remote.upload, "run", fake_upload_run)
+
+ remote.run(
+ command_context,
+ **_run_kwargs(installer_url="/tmp/app.apk", assume_yes=assume_yes),
+ )
+
+ assert seen == [assume_yes]
+
+
+(a)pytest.mark.parametrize(
+ "tags,expected",
+ [
+ (["tor", "base-browser"], "--tag tor --tag base-browser"),
+ (["a b"], "--tag 'a b'"),
+ (["a b", '"c"'], """--tag 'a b' --tag '"c"'"""),
+ ],
+)
+def test_run_formats_tags_as_flags(tmp_path, monkeypatch, tags, expected):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ remote.run(command_context, **_run_kwargs(tags=tags))
+
+ assert json.loads(requests[0].data)["inputs"]["tags"] == expected
+
+
+def test_run_omits_tags_input_when_empty(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ remote.run(command_context, **_run_kwargs(tags=[]))
+
+ assert "tags" not in json.loads(requests[0].data)["inputs"]
+
+
+def _triggered_inputs(tmp_path, monkeypatch, **overrides):
+ write_config(tmp_path)
+ _write_version(tmp_path, "1.2.3")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ return _FakeResponse(json.dumps({"web_url": "https://x"}).encode())
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ assert remote.run(command_context, **_run_kwargs(**overrides)) == 0
+ return json.loads(requests[0].data)["inputs"]
+
+
+(a)pytest.mark.parametrize("sha256sums_url", [None, "https://example.org/sha256sums.txt"])
+def test_run_includes_sha256sums_input_only_when_given(
+ tmp_path, monkeypatch, sha256sums_url
+):
+ inputs = _triggered_inputs(tmp_path, monkeypatch, sha256sums_url=sha256sums_url)
+
+ assert inputs.get("android_x86_64_sha256sums_url") == sha256sums_url
+
+
+(a)pytest.mark.parametrize("artifacts_url", [None, "https://example.org/artifacts/"])
+(a)pytest.mark.parametrize("mozharness_url", [None, "https://example.org/mozharness.zip"])
+def test_run_uses_given_artifacts_and_mozharness_urls_or_infers_them(
+ tmp_path, monkeypatch, artifacts_url, mozharness_url
+):
+ inputs = _triggered_inputs(
+ tmp_path,
+ monkeypatch,
+ artifacts_url=artifacts_url,
+ mozharness_url=mozharness_url,
+ )
+
+ assert inputs["android_x86_64_artifacts_url"] == (
+ artifacts_url or remote._artifacts_url("1.2.3", "android_x86_64")
+ )
+ assert inputs["mozharness_url"] == (
+ mozharness_url or remote._mozharness_url("1.2.3", "android_x86_64")
+ )
+
+
+def test_run_aborts_when_local_upload_fails(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(remote.upload, "run", _failing_upload_run)
+ monkeypatch.setattr(
+ remote.urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("pipeline triggered after failed upload"),
+ )
+
+ result = remote.run(command_context, **_run_kwargs(installer_url="/tmp/app.apk"))
+
+ assert result == 1
+ assert "ERROR! boom" in capsys.readouterr().out
+
+
+def test_run_dry_run_does_not_upload_a_local_path(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ monkeypatch.setattr(
+ remote.upload,
+ "run",
+ lambda *args, **kwargs: pytest.fail("uploaded during a dry run"),
+ )
+
+ result = remote.run(
+ command_context, **_run_kwargs(installer_url=str(apk), dry_run=True)
+ )
+
+ assert result == 0
+ assert "<URL of uploaded app.apk>" in capsys.readouterr().out
+
+
+def test_run_dry_run_rejects_missing_local_path(tmp_path, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+ missing = tmp_path / "missing.apk"
+
+ result = remote.run(
+ command_context, **_run_kwargs(installer_url=str(missing), dry_run=True)
+ )
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert f"ERROR! No such file: {missing}" in out
+ assert "curl" not in out
+
+
+def test_run_infers_version_artifacts_and_mozharness(tmp_path, capsys):
+ write_config(tmp_path)
+ _write_version(tmp_path, "1.2.3")
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ result = remote.run(
+ command_context,
+ **_run_kwargs(artifacts_url=None, mozharness_url=None, dry_run=True),
+ )
+
+ assert result == 0
+ out = capsys.readouterr().out
+ assert "1.2.3" in out
+ assert "android-x86_64" in out
+
+
+def test_run_triggers_pipeline_and_reports_url(tmp_path, monkeypatch, capsys):
+ config = write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ requests = []
+
+ def fake_urlopen(request, timeout=None):
+ requests.append(request)
+ body = json.dumps({"web_url": "https://gitlab.example/pipelines/1"}).encode()
+ return _FakeResponse(body)
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 0
+ assert "https://gitlab.example/pipelines/1" in capsys.readouterr().out
+ assert requests[0].full_url == (
+ f"{remote.GITLAB_API_BASE}/projects/"
+ f"{config['project'].replace('/', '%2F')}/trigger/pipeline"
+ )
+ payload = json.loads(requests[0].data)
+ assert payload["token"] == config["token"]
+ assert payload["ref"] == "main"
+ assert payload["inputs"]["tags"] == "--tag tor"
+
+
+def test_run_reports_http_error(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fake_urlopen(request, timeout=None):
+ raise urllib.error.HTTPError(
+ request.full_url,
+ 401,
+ "Unauthorized",
+ None,
+ SimpleNamespace(read=lambda: b"bad token", close=lambda: None),
+ )
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ out = capsys.readouterr().out
+ assert "401" in out
+ assert "bad token" in out
+
+
+def test_run_reports_url_error(tmp_path, monkeypatch, capsys):
+ write_config(tmp_path)
+ command_context = SimpleNamespace(topsrcdir=str(tmp_path))
+
+ def fake_urlopen(request, timeout=None):
+ raise urllib.error.URLError("unreachable")
+
+ monkeypatch.setattr(remote.urllib.request, "urlopen", fake_urlopen)
+
+ result = remote.run(command_context, **_run_kwargs())
+
+ assert result == 1
+ assert "unreachable" in capsys.readouterr().out
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/tests/python/test_upload.py
=====================================
@@ -0,0 +1,242 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+
+import mozunit
+import pytest
+from conftest import write_config
+from yeet import upload
+
+
+def _freeze_time(monkeypatch, fixed):
+ class _FrozenDatetime(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return fixed.astimezone(tz)
+
+ monkeypatch.setattr(upload, "datetime", _FrozenDatetime)
+
+
+def test_resolve_file_missing():
+ with pytest.raises(FileNotFoundError, match="No such file"):
+ upload.resolve_file("/no/such/file/here")
+
+
+def test_resolve_file_existing(tmp_path):
+ apk = tmp_path / "fenix-x86_64-debug.apk"
+ apk.write_bytes(b"not really an apk")
+
+ assert upload.resolve_file(str(apk)) == apk.resolve()
+
+
+(a)pytest.mark.parametrize(
+ "fixed,expected",
+ [
+ (datetime(2026, 9, 14, 12, 34, 56, tzinfo=timezone.utc), "20260914-123456"),
+ (
+ datetime(
+ 2026, 9, 14, 18, 4, 56, tzinfo=timezone(timedelta(hours=5, minutes=30))
+ ),
+ "20260914-123456",
+ ),
+ (
+ datetime(2026, 9, 14, 21, 0, 0, tzinfo=timezone(timedelta(hours=-5))),
+ "20260915-020000",
+ ),
+ ],
+)
+def test_remote_dir_name_is_current_utc_time_and_platform(monkeypatch, fixed, expected):
+ _freeze_time(monkeypatch, fixed)
+
+ assert upload._remote_dir_name("android_x86_64") == f"{expected}-android_x86_64"
+
+
+def test_upload_success(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ assert kwargs["stdin"] is upload.subprocess.DEVNULL
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ url = upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+ assert url == "https://example.org/~bea/yeet/ts-os/app.apk"
+ assert calls[0][0] == "ssh"
+ assert calls[0][-3:] == ["mkdir", "-p", "~/public_html/yeet/ts-os"]
+ assert calls[1][0] == "scp"
+ assert calls[1][-2:] == [
+ "/tmp/app.apk",
+ "bea@example.org:~/public_html/yeet/ts-os/app.apk",
+ ]
+
+
+def test_upload_replaces_unsafe_filename_characters(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return SimpleNamespace(returncode=0)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ url = upload._upload(
+ upload.Path("/tmp/app (1)#%?.apk"), "bea", "example.org", "ts-os"
+ )
+
+ assert url == "https://example.org/~bea/yeet/ts-os/app__1____.apk"
+ assert calls[1][-2:] == [
+ "/tmp/app (1)#%?.apk",
+ "bea@example.org:~/public_html/yeet/ts-os/app__1____.apk",
+ ]
+
+
+def test_upload_stops_if_mkdir_fails(monkeypatch):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append(cmd)
+ return SimpleNamespace(returncode=1)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ with pytest.raises(RuntimeError):
+ upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+ assert len(calls) == 1
+
+
+def test_upload_fails_if_scp_fails(monkeypatch):
+ def fake_run(cmd, **kwargs):
+ return SimpleNamespace(returncode=0 if cmd[0] == "ssh" else 1)
+
+ monkeypatch.setattr(upload.subprocess, "run", fake_run)
+
+ with pytest.raises(RuntimeError):
+ upload._upload(upload.Path("/tmp/app.apk"), "bea", "example.org", "ts-os")
+
+
+def test_run_aborts_without_config(tmp_path):
+ apk = tmp_path / "app.apk"
+ apk.touch()
+
+ with pytest.raises(RuntimeError, match="mach yeet auth"):
+ upload.run(tmp_path, str(apk), "android_x86_64")
+
+
+def test_run_aborts_when_file_missing(tmp_path):
+ write_config(tmp_path)
+
+ with pytest.raises(FileNotFoundError):
+ upload.run(tmp_path, str(tmp_path / "missing.apk"), "android_x86_64")
+
+
+def _write_apk(tmp_path):
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ return apk
+
+
+def _set_confirm_answers(monkeypatch, *answers):
+ answers = iter(answers)
+ monkeypatch.setattr("builtins.input", lambda prompt="": next(answers))
+
+
+def test_run_uploads_into_timestamped_dir_and_prints_url(tmp_path, monkeypatch, capsys):
+ config = write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+ _freeze_time(monkeypatch, datetime(2026, 9, 14, 12, 34, 56, tzinfo=timezone.utc))
+
+ calls = []
+
+ def fake_upload(file_path, ssh_user, ssh_host, remote_dir):
+ calls.append((file_path, ssh_user, ssh_host, remote_dir))
+ return f"https://{ssh_host}/~{ssh_user}/yeet/{remote_dir}/{file_path.name}"
+
+ monkeypatch.setattr(upload, "_upload", fake_upload)
+
+ url = upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+
+ assert url == (
+ f"https://{config['ssh_host']}/~{config['ssh_user']}/yeet/20260914-123456-android_x86_64/app.apk"
+ )
+ assert calls == [
+ (
+ apk.resolve(),
+ config["ssh_user"],
+ config["ssh_host"],
+ "20260914-123456-android_x86_64",
+ )
+ ]
+ assert url in capsys.readouterr().out
+
+
+def test_run_reports_upload_failure(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ apk = tmp_path / "app.apk"
+ apk.write_bytes(b"not really an apk")
+
+ def fake_upload(file_path, ssh_user, ssh_host, remote_dir):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(upload, "_upload", fake_upload)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+
+
+(a)pytest.mark.parametrize("answer", ["y", "yes", "Y"])
+def test_run_uploads_after_confirmation(tmp_path, monkeypatch, answer):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ _set_confirm_answers(monkeypatch, answer)
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda file_path, ssh_user, ssh_host, remote_dir: "https://x/y",
+ )
+
+ assert upload.run(tmp_path, str(apk), "android_x86_64") == "https://x/y"
+
+
+(a)pytest.mark.parametrize("answers", [("",), ("n",), ("no",), ("maybe", "n")])
+def test_run_does_not_upload_when_declined(tmp_path, monkeypatch, answers):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ _set_confirm_answers(monkeypatch, *answers)
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda *args: pytest.fail("_upload called after the user declined"),
+ )
+
+ with pytest.raises(RuntimeError, match="cancelled"):
+ upload.run(tmp_path, str(apk), "android_x86_64")
+
+
+def test_run_skips_confirmation_with_assume_yes(tmp_path, monkeypatch):
+ write_config(tmp_path)
+ apk = _write_apk(tmp_path)
+ monkeypatch.setattr(
+ "builtins.input", lambda prompt="": pytest.fail("unexpected prompt")
+ )
+ monkeypatch.setattr(
+ upload,
+ "_upload",
+ lambda file_path, ssh_user, ssh_host, remote_dir: "https://x/y",
+ )
+
+ assert (
+ upload.run(tmp_path, str(apk), "android_x86_64", assume_yes=True)
+ == "https://x/y"
+ )
+
+
+if __name__ == "__main__":
+ mozunit.main()
=====================================
tools/yeet/upload.py
=====================================
@@ -0,0 +1,96 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import re
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+
+from yeet.common import TERM, YEET_CONFIG_FILENAME, confirm, read_config
+
+
+def resolve_file(file_arg):
+ path = Path(file_arg).resolve()
+ if not path.is_file():
+ raise FileNotFoundError(f"No such file: {path}")
+ return path
+
+
+def _remote_dir_name(platform):
+ """Name the upload's directory after the current time and `platform`,
+ so repeated uploads never collide or overwrite each other.
+ """
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ return f"{timestamp}-{platform}"
+
+
+def _upload(file_path, ssh_user, ssh_host, remote_dir):
+ """scp `file_path` into ~/public_html/yeet/`remote_dir` on
+ ssh_user@ssh_host, keeping its name (with characters unsafe in a URL or
+ shell replaced by `_`) and creating that directory first if needed. Both
+ commands get /dev/null as stdin so they can't swallow input buffered for
+ us; their touch/PIN/passphrase prompts go through /dev/tty and still reach
+ the user.
+
+ Returns the file's final https:// URL. Raises RuntimeError on failure.
+ """
+ ssh_target = f"{ssh_user}@{ssh_host}"
+ remote_name = re.sub(r"[^A-Za-z0-9._-]", "_", file_path.name)
+ dest_dir = f"~/public_html/yeet/{remote_dir}"
+ dest_path = f"{dest_dir}/{remote_name}"
+ html_path = f"~{ssh_user}/yeet/{remote_dir}/{remote_name}"
+
+ mkdir = subprocess.run(
+ ["ssh", ssh_target, "mkdir", "-p", dest_dir],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ if mkdir.returncode != 0:
+ raise RuntimeError(f"Could not create {dest_dir} on {ssh_target}.")
+
+ scp = subprocess.run(
+ ["scp", str(file_path), f"{ssh_target}:{dest_path}"],
+ stdin=subprocess.DEVNULL,
+ check=False,
+ )
+ if scp.returncode != 0:
+ raise RuntimeError(f"Upload to {ssh_target} failed.")
+
+ return f"https://{ssh_host}/{html_path}"
+
+
+def run(topsrcdir, file, platform, assume_yes=False):
+ """Upload `file` for `platform` to the configured server, asking for
+ confirmation first unless `assume_yes`. Returns the file's final https://
+ URL. Raises FileNotFoundError if `file` or the config is missing, and
+ RuntimeError if the upload fails or is cancelled.
+ """
+ config = read_config(topsrcdir)
+ if config is None:
+ raise RuntimeError(
+ f"No {YEET_CONFIG_FILENAME} found. Run `mach yeet auth` first."
+ )
+
+ file_path = resolve_file(file)
+
+ remote_dir = _remote_dir_name(platform)
+
+ if not assume_yes:
+ print()
+ print(
+ TERM.yellow(
+ f"{file_path} will be uploaded to {config['ssh_host']} and "
+ "be publicly accessible."
+ )
+ )
+ if not confirm("Upload it?"):
+ raise RuntimeError("Upload cancelled.")
+
+ print()
+ print(f"Uploading {file_path.name} to {remote_dir}/...")
+ url = _upload(file_path, config["ssh_user"], config["ssh_host"], remote_dir)
+
+ print()
+ print(TERM.green(f"Uploaded: {url}"))
+ return url
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3f305e…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3f305e…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 32 commits: fixup! Firefox preference overrides.
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
cd85b0b4 by Beatriz Rizental at 2026-11-05T08:33:50+01:00
fixup! Firefox preference overrides.
Bug 44284: Never show promotional vertical pinned tabs dialog
- - - - -
14fee542 by Beatriz Rizental at 2026-11-05T08:33:50+01:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
Bug 45237: Fix pref typo
- - - - -
9a1017b6 by Dan Ballard at 2026-11-05T08:33:50+01:00
fixup! [android] Implement Android-native Connection Assist UI
TB 44132: MinSDK raised to 26/O, removing check if Android Version is N or above
- - - - -
eda06ede by Pier Angelo Vendrame at 2026-11-05T08:33:50+01:00
fixup! BB 41369: Improve Firefox language settings for multi-lingual packages
BB 45360: Move our language setting customization to the new design.
- - - - -
dfcef5b5 by Henry Wilkes at 2026-11-05T08:33:51+01:00
fixup! TB 7494: Create local home page for TBB.
TB 45218: Tweak YEC styling for 2026.
- - - - -
e42b6214 by Elena at 2026-11-05T08:33:51+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented bridge line parsing.
- - - - -
24a68c35 by Elena at 2026-11-05T08:33:51+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented the parsers to get PTs.
- - - - -
d924ae42 by Elena at 2026-11-05T08:33:52+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented the GETCONF commands.
- - - - -
e576e7cf by Elena at 2026-11-05T08:33:52+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implemented the SETCONF.
- - - - -
c767ab4b by Dan Ballard at 2026-11-05T08:33:52+01:00
fixup! [android] Disable features and functionality
TB 45363: Disable import bookmarks in android until stable
- - - - -
a4aa95c5 by Pier Angelo Vendrame at 2026-11-05T08:33:52+01:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
TB 45333: Disable the fast-path to skip proxy resolution.
We are always behind a proxy, we don't need this.
- - - - -
ef0fb38c by hackademix at 2026-11-05T08:33:53+01:00
fixup! TB 30237: Add v3 onion services client authentication prompt
TB 45346: Open about:manual from parent process.
- - - - -
2c850765 by Beatriz Rizental at 2026-11-05T08:33:53+01:00
fixup! BB 31740: Remove some unnecessary RemoteSettings instances
Bug 44154: Keep RemoteSettings instances required for testing, when testing
- - - - -
6cb0ac7d by Beatriz Rizental at 2026-11-05T08:33:53+01:00
fixup! BB 42730: Patch RemoteSettings to use only local dumps as a data source
Bug 44154: Implement tests to verify correctness of patch
- - - - -
99fe0e30 by Beatriz Rizental at 2026-11-05T08:33:54+01:00
fixup! BB 44711: Hide unwanted setting controls in Base Browser.
Bug 576: Hide more unwanted stuff from settings
- - - - -
5e59ddf7 by Morgan at 2026-11-05T08:33:54+01:00
fixup! TB 45178: Update support settings for Tor Browser.
- - - - -
c04c5093 by Beatriz Rizental at 2026-11-05T08:33:54+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: Disable HTTPS-only mode when running mochitests
- - - - -
abefbc64 by Beatriz Rizental at 2026-11-05T08:33:54+01:00
fixup! TB 43817: Add tests for Tor Browser
Bug 44820: Modify mochi runtests scripts to work in Tor Browser.
- - - - -
1a5b318a by Beatriz Rizental at 2026-11-05T08:33:55+01:00
fixup! TB3: Tor Browser's official .mozconfigs.
Bug 44820: Make TOR_BROWSER config is available to gradle
- - - - -
a1e88e38 by Beatriz Rizental at 2026-11-05T08:33:55+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: Upstream geckoiew's own manifest requests
ACCESS_NETWORK_STATE. Tor Browser comments that line
out so geckoview doesn't ask for network-state access,
but the test app needs it. So we add it back.
- - - - -
b5ebb9cc by Beatriz Rizental at 2026-11-05T08:33:55+01:00
fixup! Firefox preference overrides.
Bug 44820: Add note about prefs modified for mochitests
- - - - -
65d7d7f3 by Pier Angelo Vendrame at 2026-11-05T08:33:55+01:00
fixup! BB 42084: Ensure English spoofing works even if preferences are set out of order.
BB 44341: Unregister the intl.accept_languages observer.
- - - - -
0919fa05 by clairehurst at 2026-11-05T08:33:56+01:00
fixup! [android] Modify UI/UX
Bug 45364: Remove "New private tab" item in list that shows after long pressing the tab counter
- - - - -
12cfbe70 by Beatriz Rizental at 2026-11-05T08:33:56+01:00
fixup! BB 41695: Warn on window maximization without letterboxing in RFPHelper module
Keep the original window sizes in a module-level WeakMap keyed by window,
instead of in a _rfpOriginalSize expando on the chrome window. Browser chrome
tests fail when a test leaves unexpected properties on the window.
- - - - -
8f4dbc3d by Beatriz Rizental at 2026-11-05T08:33:56+01:00
fixup! BB 42443: Shrink window to match letterboxing size when the emtpy area is clicked.
Make shrinkToLetterbox an RFPHelper method that takes the window, instead
of attaching it to every chrome window. Browser chrome tests fail when a
test leaves unexpected properties on the window.
- - - - -
ed5c3a02 by Beatriz Rizental at 2026-11-05T08:33:57+01:00
fixup! BB 41919: Letterboxing, add temporarily visible web content-size indicator on window resizing.
Keep the letterboxing status timeouts in a module-level WeakMap keyed by
window, instead of in a _letterboxingStatusTimeout expando on the chrome
window. Browser chrome tests fail when a test leaves unexpected properties on
the window.
- - - - -
36a0b77a by Beatriz Rizental at 2026-11-05T08:33:57+01:00
fixup! BB 41581: Hide NoScript extension's toolbar button by default.
The widget is created once per browser window, so the extensions.hideNoScript
pref observer was added for every window and never removed. It kept each
closed window alive until shutdown. Remove it when the window unloads.
- - - - -
8e6ad547 by Beatriz Rizental at 2026-11-05T08:33:57+01:00
fixup! BB 9173: Change the default Firefox profile directory to be relative.
Clear the cached gDataDirPortable in DoShutdown, as is done for the other
cached directories. Otherwise its nsIFile is only released by static
destructors, after the leak checker runs, and every test run reports a
48 byte leak.
- - - - -
6f84ee4e by Beatriz Rizental at 2026-11-05T08:33:57+01:00
fixup! TB 43817: Add tests for Tor Browser
Bug 44820: This change was part of tor-browser#2251
but during some of the commit handling I must have dropped it.
- - - - -
70b4b911 by Beatriz Rizental at 2026-11-05T08:33:58+01:00
fixup! BB 43535: Enable tests
This reverts commit e42d7f1136aa55573c01c91a87dec69bbfbdb529.
- - - - -
ac8e3409 by Beatriz Rizental at 2026-11-05T08:33:58+01:00
fixup! BB 45120: Add tests for Base Browser
Bug 44820: The mochitest harness built the testing-common resource
mapping as "file:///" + testingModulesDir. On Linux and macOS
testingModulesDir is already an absolute path, so this produced
"file:////home/...", which content processes fail to load from.
- - - - -
3f305ea7 by Pier Angelo Vendrame at 2026-11-05T08:33:58+01:00
fixup! TB 7494: Create local home page for TBB.
Lint
- - - - -
38 changed files:
- Cargo.lock
- browser/app/profile/000-tor-browser.js
- browser/app/profile/001-base-profile.js
- browser/components/abouttor/content/aboutTor.css
- browser/components/abouttor/content/aboutTor.html
- browser/components/extensions/parent/ext-browserAction.js
- browser/components/preferences/config/languages.mjs
- browser/components/preferences/config/tabs-browsing.mjs
- browser/components/preferences/main.js
- mobile/android/fenix/app/nimbus.fml.yaml
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/components/toolbar/BrowserToolbarMiddleware.kt
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/tor/TorConnectionAssistFragment.kt
- mobile/android/test_runner/src/main/AndroidManifest.xml
- moz.configure
- services/settings/dumps/main/moz.build
- services/settings/remote-settings.sys.mjs
- + services/settings/test/unit/test_remote_settings_base_browser.js
- services/settings/test/unit/xpcshell.toml
- testing/mochitest/mochitest_options.py
- testing/mochitest/runtests.py
- testing/mochitest/runtestsremote.py
- testing/specialpowers/api.js
- toolkit/actors/NetErrorParent.sys.mjs
- toolkit/components/resistfingerprinting/RFPHelper.sys.mjs
- toolkit/components/tor-integration/tor_provider/Cargo.toml
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/get_conf.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/mod.rs
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/commands/set_conf.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/error.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/mod.rs
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/bridge_line.rs
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/client_transport_plugin.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/parsers/mod.rs
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/types.rs
- toolkit/content/aboutNetError.mjs
- toolkit/modules/RemotePageAccessManager.sys.mjs
- toolkit/xre/nsXREDirProvider.cpp
The diff was not included because it is too large.
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/228fc5…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/228fc5…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 27 commits: fixup! [android] Modify UI/UX
by Pier Angelo Vendrame (@pierov) 05 Nov '26
by Pier Angelo Vendrame (@pierov) 05 Nov '26
05 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
4e842054 by Beatriz Rizental at 2026-11-05T08:32:05+01:00
fixup! [android] Modify UI/UX
Bug 44936: Make search widget icon larger
- - - - -
2bb0f66b by Pier Angelo Vendrame at 2026-11-05T08:32:05+01:00
fixup! Firefox preference overrides.
TB 45276: Deprecate the Android-specific pref file.
We are importing our main preference file anyway, which has higher
visibility to all devs.
- - - - -
40ffbda4 by Pier Angelo Vendrame at 2026-11-05T08:32:06+01:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
TB 45276: Deprecate the Android-specific pref file.
We are importing our main preference file anyway, which has higher
visibility to all devs.
- - - - -
62a1a469 by Pier Angelo Vendrame at 2026-11-05T08:32:06+01:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
TB 45073: Pref review, part 1: 000-tor-browser.js.
- - - - -
a9a0077e by Pier Angelo Vendrame at 2026-11-05T08:32:06+01:00
fixup! Firefox preference overrides.
BB 45073: Pref review, part 1: 000-tor-browser.js.
- - - - -
deeca686 by clairehurst at 2026-11-05T08:32:06+01:00
fixup! [android] Delete unused media
Bug 45281: Fix or remove broken "Use screen lock to hide Tor Browser tabs" feature
- - - - -
6a314f79 by clairehurst at 2026-11-05T08:32:07+01:00
fixup! TB 44027: [android] Update PBM lockscreen
Bug 45281: Fix or remove broken "Use screen lock to hide Tor Browser tabs" feature
- - - - -
925613a0 by Dan Ballard at 2026-11-05T08:32:07+01:00
fixup! [android] TBA strings
TB45256: Add YEC26 TBA strings
- - - - -
20881878 by Pier Angelo Vendrame at 2026-11-05T08:32:07+01:00
fixup! TB 23247: Communicating security expectations for .onion
TB 42065: Self-signed onion certs are detected as a user exception.
- - - - -
f43916dc by Henry Wilkes at 2026-11-05T08:32:08+01:00
fixup! TB 44361: Notification for dropped support for 32-bit Linux.
TB 44887: Drop the deprecation notice.
This reverts commit 7d9ed316243ed2aeaf869f7c9d4c16d6831ac56e.
- - - - -
b5e6d544 by Henry Wilkes at 2026-11-05T08:32:08+01:00
fixup! Tor Browser strings
TB 44887: Drop linux 32-bit deprecation strings.
- - - - -
059090f1 by Henry Wilkes at 2026-11-05T08:32:08+01:00
fixup! BB 41930: Remove the UI to customize accept_languages.
TB 45177: Remove websiteSpoofEnglishControl.
- - - - -
8b8c897e by Pier Angelo Vendrame at 2026-11-05T08:32:08+01:00
fixup! Base Browser's .mozconfigs.
BB 45336: Add --disable-proxy-direct-failover.
- - - - -
8fe34c59 by Henry Wilkes at 2026-11-05T08:32:09+01:00
BB 45249: Remove the duplicate "Verified by" from the old site identity panel.
- - - - -
c1641f3e by Henry Wilkes at 2026-11-05T08:32:09+01:00
fixup! TB 23247: Communicating security expectations for .onion
TB 45249: Hide verifier information when it is empty.
Special thanks to @soni.
- - - - -
a8521e5a by Henry Wilkes at 2026-11-05T08:32:09+01:00
fixup! Firefox preference overrides.
BB 45338: Lock browser.smartwindow.enabled.
- - - - -
e3a0b1e5 by Pier Angelo Vendrame at 2026-11-05T08:32:09+01:00
fixup! Firefox preference overrides.
BB 44815: Disable harmful addon URL blocking.
- - - - -
62ae0653 by Henry Wilkes at 2026-11-05T08:32:10+01:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
TB 45288: Change the "share ideas" url to point to about:manual.
- - - - -
76e3e992 by Henry Wilkes at 2026-11-05T08:32:10+01:00
fixup! BB 18905: Hide unwanted items from help menu
BB 45288: Show "share ideas" menu item again.
- - - - -
c0c65c76 by Henry Wilkes at 2026-11-05T08:32:10+01:00
fixup! TB 45178: Update support settings for Tor Browser.
TB 45288: Change the "share ideas" link in settings.
- - - - -
3e8db524 by Beatriz Rizental at 2026-11-05T08:32:10+01:00
fixup! BB 43243: Modify mozharness scripts for Base Browser
Bug 45334: Haver marionette harness accept multiple tags
- - - - -
70c0ba16 by Pier Angelo Vendrame at 2026-11-05T08:32:11+01:00
fixup! Firefox preference overrides.
BB 45080: Disable the reporting API.
- - - - -
a3c92838 by Dan Ballard at 2026-11-05T08:32:11+01:00
fixup! TB 34378: [android] Port external helper app prompting
TB40627: Fix android share by making new intents with new request codes and not caching the dialog
- - - - -
e6671e68 by Dan Ballard at 2026-11-05T08:32:11+01:00
fixup! [android] Disable features and functionality
TB 40627: Remove Share function from selected text context menu
- - - - -
f51468ef by Pier Angelo Vendrame at 2026-11-05T08:32:12+01:00
fixup! Firefox preference overrides.
BB 45073: 140-153 preference review.
- - - - -
673d9239 by Pier Angelo Vendrame at 2026-11-05T08:32:12+01:00
fixup! TB 23247: Communicating security expectations for .onion
TB 45343: Hide the custom roots warning for onion sites.
At the moment, we allow self-signed certificates for onion services.
However, tghere are several warnings we need to hide, as they would be
misleading of the actual situation.
Also, hide any field we get from the certificate, to avoid phishing.
In the future, we may re-evaluate accepting self-certificates from
onion services.
- - - - -
228fc53e by Dan Ballard at 2026-11-05T08:32:12+01:00
fixup! [android] Override settings
TB 44913: Fully disable custom download location
- - - - -
58 changed files:
- .prettierignore
- browser/app/profile/000-tor-browser.js
- browser/app/profile/001-base-profile.js
- browser/base/content/browser-main.js
- browser/base/content/browser-menubar.inc.xhtml
- browser/base/content/browser-siteIdentity.js
- − browser/base/content/droppedSupportNotification.js
- browser/base/jar.mn
- browser/components/controlcenter/content/securityInformation.inc.xhtml
- browser/components/preferences/config/about-firefox.mjs
- browser/components/preferences/config/languages.mjs
- browser/components/preferences/main.inc.xhtml
- browser/components/preferences/main.js
- browser/config/mozconfigs/base-browser
- browser/config/mozconfigs/base-browser-android
- browser/themes/shared/controlcenter/panel.css
- eslint-ignores.config.mjs
- mobile/android/android-components/components/feature/contextmenu/src/main/java/mozilla/components/feature/contextmenu/DefaultSelectionActionDelegate.kt
- mobile/android/android-components/components/support/utils/src/main/java/mozilla/components/support/utils/TorUtils.kt
- − mobile/android/app/000-tor-browser-android.js
- mobile/android/app/geckoview-prefs.js
- mobile/android/app/moz.build
- mobile/android/fenix/app/nimbus.fml.yaml
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/pbmlock/UnlockPrivateTabsScreen.kt
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/settings/TabsSettingsFragment.kt
- + mobile/android/fenix/app/src/main/res/drawable-hdpi/ic_logo_wordmark_normal.webp
- + mobile/android/fenix/app/src/main/res/drawable-hdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/main/res/drawable-mdpi/ic_logo_wordmark_normal.webp
- + mobile/android/fenix/app/src/main/res/drawable-mdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/main/res/drawable-night/ic_logo_wordmark_normal.xml
- + mobile/android/fenix/app/src/main/res/drawable-xhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/main/res/drawable-xxhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/main/res/drawable-xxxhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/main/res/drawable/ic_wordmark_logo.webp
- mobile/android/fenix/app/src/main/res/layout/search_widget_extra_small_v1.xml
- mobile/android/fenix/app/src/main/res/layout/search_widget_extra_small_v2.xml
- mobile/android/fenix/app/src/main/res/layout/search_widget_large.xml
- mobile/android/fenix/app/src/main/res/layout/search_widget_medium.xml
- mobile/android/fenix/app/src/main/res/layout/search_widget_small.xml
- mobile/android/fenix/app/src/main/res/layout/search_widget_small_no_mic.xml
- mobile/android/fenix/app/src/main/res/values/styles.xml
- mobile/android/fenix/app/src/main/res/values/torbrowser_strings.xml
- + mobile/android/fenix/app/src/nightly/res/drawable-hdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/nightly/res/drawable-mdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/nightly/res/drawable-xhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/nightly/res/drawable-xxhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/nightly/res/drawable-xxxhdpi/ic_logo_wordmark_normal.webp
- + mobile/android/fenix/app/src/nightly/res/drawable-xxxhdpi/ic_logo_wordmark_private.webp
- + mobile/android/fenix/app/src/nightly/res/drawable/ic_wordmark_logo.webp
- + mobile/android/fenix/app/src/nightly/res/drawable/ic_wordmark_text_normal.webp
- + mobile/android/fenix/app/src/nightly/res/drawable/ic_wordmark_text_private.webp
- + mobile/android/fenix/app/src/release/res/drawable-hdpi/ic_logo_wordmark_normal.webp
- + mobile/android/fenix/app/src/release/res/drawable-hdpi/ic_logo_wordmark_private.webp
- mobile/android/installer/package-manifest.in
- security/manager/ssl/SSLServerCertVerification.cpp
- testing/mozharness/scripts/marionette.py
- toolkit/locales/en-US/toolkit/global/tor-browser.ftl
The diff was not included because it is too large.
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/8518d5…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/8518d5…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-155.0a1-17.0-1] 2 commits: BB 41108: Remove privileged macOS installation
by Pier Angelo Vendrame (@pierov) 04 Nov '26
by Pier Angelo Vendrame (@pierov) 04 Nov '26
04 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-155.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
Commits:
d646ae03 by Pier Angelo Vendrame at 2026-11-04T21:59:23+01:00
BB 41108: Remove privileged macOS installation
- - - - -
8518d56b by Pier Angelo Vendrame at 2026-11-04T21:59:23+01:00
fixup! Base Browser's .mozconfigs.
BB 45240: Fix updater-related build errors on macOS.
Introduce CONFIG["BASE_BROWSER"].
- - - - -
4 changed files:
- browser/app/moz.build
- moz.configure
- toolkit/moz.build
- toolkit/xre/MacRunFromDmgUtils.mm
Changes:
=====================================
browser/app/moz.build
=====================================
@@ -80,6 +80,12 @@ if CONFIG["MOZ_WIDGET_TOOLKIT"] == "cocoa":
f"!/{FINAL_TARGET}/org.mozilla.updater",
"Library/LaunchServices/org.mozilla.updater",
))
+ moves = [("ChannelPrefs.framework", "Frameworks/ChannelPrefs.framework")]
+ if not CONFIG["BASE_BROWSER"]:
+ moves.append((
+ "org.mozilla.dmgInstallHelper",
+ "Library/LaunchServices/org.mozilla.dmgInstallHelper",
+ ))
MacOSBundle(
f"!/dist/{CONFIG['MOZ_MACBUNDLE_NAME']}",
skeleton="macbuild/Contents",
@@ -93,13 +99,7 @@ if CONFIG["MOZ_WIDGET_TOOLKIT"] == "cocoa":
(f"!/{FINAL_TARGET}/{CONFIG['MOZ_APP_NAME']}", CONFIG["MOZ_APP_NAME"])
],
extra_files=extra_files,
- moves=[
- ("ChannelPrefs.framework", "Frameworks/ChannelPrefs.framework"),
- (
- "org.mozilla.dmgInstallHelper",
- "Library/LaunchServices/org.mozilla.dmgInstallHelper",
- ),
- ],
+ moves=moves,
pkginfo="APPLTORB",
)
=====================================
moz.configure
=====================================
@@ -1035,6 +1035,9 @@ def base_browser_version_quoted(value):
return f'"{value[0]}"'
+set_config(
+ "BASE_BROWSER", depends(base_browser_version)(lambda v: True if v else False)
+)
set_define("BASE_BROWSER_VERSION", base_browser_version)
set_define("BASE_BROWSER_VERSION_QUOTED", base_browser_version_quoted)
=====================================
toolkit/moz.build
=====================================
@@ -63,11 +63,12 @@ if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
]
elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "cocoa":
DIRS += [
- "mozapps/dmgInstallHelper",
"mozapps/macos-frameworks",
"system/commonproxy",
"system/osxproxy",
]
+ if not CONFIG["BASE_BROWSER"]:
+ DIRS += ["mozapps/dmgInstallHelper"]
elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows":
DIRS += [
"system/commonproxy",
=====================================
toolkit/xre/MacRunFromDmgUtils.mm
=====================================
@@ -279,6 +279,7 @@ static void ShowInstallFailedDialog() {
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
+#ifndef BASE_BROWSER_VERSION
// Install the DMGInstallHelper as an elevated helper and use it to install
bool LaunchElevatedDmgInstall(NSString* aBundlePath, NSString* aDestPath) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
@@ -355,6 +356,7 @@ bool LaunchElevatedDmgInstall(NSString* aBundlePath, NSString* aDestPath) {
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
+#endif
// Note: both arguments are expected to contain the app name (to end with
// '.app').
@@ -381,6 +383,7 @@ static bool InstallFromPath(NSString* aBundlePath, NSString* aDestPath) {
os_log_info(runFromDMGLogger, "Unelevated installation: %s",
installSuccessful ? "success" : "failed");
+#ifndef BASE_BROWSER_VERSION
// The installation may have been unsuccessful if the user did not have the
// rights to write to the Applications directory. Check for this situation and
// launch an elevated helper application.
@@ -396,6 +399,7 @@ static bool InstallFromPath(NSString* aBundlePath, NSString* aDestPath) {
return false;
}
}
+#endif
if (!installSuccessful) {
os_log_error(runFromDMGLogger, "Unknown install failure.");
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/90e50e…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/90e50e…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-153.6.0esr-16.0-1] 4 commits: fixup! Tor Browser localization migration scripts.
by henry (@henry) 04 Nov '26
by henry (@henry) 04 Nov '26
04 Nov '26
henry pushed to branch tor-browser-153.6.0esr-16.0-1 at The Tor Project / Applications / Tor Browser
Commits:
0d103a1e by Henry Wilkes at 2026-11-03T15:03:48+00:00
fixup! Tor Browser localization migration scripts.
TB 45433: Change the script to be more versatile for test runs.
Instead of passing in a python module name for the recipe, you now pass
in the file path to the recipe script.
You can now change the reference directory with the
--reference-directory argument, which is useful for testing scripts
before the changes have reached the translation repository.
- - - - -
7e33b574 by Henry Wilkes at 2026-11-04T14:51:14+00:00
fixup! Tor Browser localization migration scripts.
TB 45433: Refactor the WeblateMetadata class.
We are stricter about checking the return types from the weblate API,
and making sure it doesn't make requests to unexpected URLs.
We also limit the components to the browser components, and we slightly
alter the `is_translated` public method.
- - - - -
90fb8c89 by Henry Wilkes at 2026-11-04T14:51:16+00:00
fixup! Tor Browser localization migration scripts.
TB 45433: Add type hints to the script.
- - - - -
fdcaef33 by Henry Wilkes at 2026-11-04T14:51:17+00:00
fixup! Tor Browser localization migration scripts.
TB 45433: Update the migrate.py documentation.
- - - - -
1 changed file:
- tools/torbrowser/l10n/migrate.py
Changes:
=====================================
tools/torbrowser/l10n/migrate.py
=====================================
@@ -1,58 +1,252 @@
"""
-Migration script for running migration recipes.
+Migration script for running Tor Browser migration recipes.
-Requires the mozilla fluent.migrate package (available with pip).
+Based on the Firefox migration script, adapted for Tor Browser. See
+https://firefox-source-docs.mozilla.org/l10n/migrations/ for more context and
+information on how to write the migration recipes.
-NOTE: This will likely send queries to the weblate API as part of the run.
-Weblate may have a query limit of 100 requests per day for unauthorised users.
+## Concepts
+
++ String. Here, when we say "string", it refers to a piece of text that can be
+ translated. In practice, you can think of it as a being defined by a triple:
+ a file path relative to a locale's directory, an ID, and some content. For
+ example `("./tor-browser.ftl", "my-id", "my-id =\\n .label=Content")`.
+ When a string is translated the file path and ID stay the same, whilst the
+ translatable part of the content can vary.
++ Reference files. These are the en-US source Fluent files that contain the
+ *manual* string changes made by a developer. For most migrations, there is
+ only one reference file.
++ Migration recipe. A collection of instructions that take some string inputs
+ and transforms them into new strings. These are meant to mirror the manual
+ changes that were made in the reference files, in a way that can be applied
+ to any locale.
++ Translation repository. This refers to a local copy of the `translation`
+ repository (https://gitlab.torproject.org/tpo/translation) This repository
+ contains a different branch for different collections of strings. For
+ Tor Browser we usually use `tor-browser`, `base-browser` and
+ `fenix-torbrowserstringsxml`. Each branch will contain an `en-US` directory,
+ which contains the "source" files for translators to translate. These source
+ files are taken from the `tor-browser` repository. The branches also contain
+ a directory for each locale that is to be translated, in a file structure that
+ reflects the source `en-US` directory. This is where the migration script will
+ write changes to the translated files.
+
+
+## Usage
+
+You will likely want to run this with `./mach python`, so that it uses the
+`fluent.migrate` and `fluent.syntax` packages provided with the `tor-browser`
+repository.
+
+For example, you might run this as
-Based on the firefox migration script, adapted for tor browser. See
-https://firefox-source-docs.mozilla.org/l10n/migrations/ for more context and
-information on how to write the migration recipes.
+```
+ ./mach python migrate.py --translation-git /home/user/translation --locales 'es-ES sr' ./migrations/bug-xxxx-my-migration-recipe.py
+```
+
+Here `/home/user/translation` is a local translation repository with one of its
+branches checked out (see below). This will run the migration recipe given in
+`./migrations/bug-xxxx-my-migration-recipe.py` for the `es-ES` and `sr`
+sub-directories within the `translation/` directory.
+
+### Changing the reference location
+
+You can optionally run the script with `--reference_directory` to read the
+reference en-US files from somewhere other than the `translation` directory.
+This can be useful when your manual changes have yet to reach the translation
+repository, so you want to point the script to read the reference from the
+`tor-browser` working directory instead. E.g.
+
+```
+ --reference-directory /home/user/tor-browser/toolkit/locales/en-US/toolkit/global/
+```
+
+
+## Recipes
+
+Migration recipes are meant to mirror some manual change that was made to the
+en-US source strings, in a way that can be reproduced in another locale.
+### Example 1
-Usage with an example:
+For this example, a developer wants to remove the string content from
+`old-strings.properties`:
-We have some en-US file "updated.ftl" in the tor-browser repository that we have
-added new strings to. Some of these strings are copies or concatenations of some
-already existing strings in a `.dtd`, `.properties` or `.ftl` file (including
-strings within "updated.ftl").
+```
+my.old.string=Some string content
+my.old.title=This is the tooltip
+```
+
+And add them to `tor-browser.ftl` instead, as:
-So we also write a migration recipe in
-`./l10n_migrations/bug-xxxx-my-migration-recipe.py`
-which includes a `migrate(ctx)` method. This method takes the old strings and
-create new Messages or Terms for "updated.ftl" using `ctx.add_transforms`. These
-should match what was already done manually in "updated.ftl".
+```
+my-new-string = Some string content
+ .title = This is the tooltip
+```
+
+For the en-US source strings, the developer simply deletes the two lines in the
+`old-strings.properties` file (or the whole file, if these are the last two).
+And they manually write in the content of `my-new-string` to `tor-browser.ftl`.
+These manual changes will then eventually reach the `translation` repository to
+be translated.
+
+But to save translators making the same manual changes, or re-translating, the
+developer can write a migration recipe that mirror's their manual changes. In
+this case, this migration recipe would contain:
+
+```
+ctx.add_transforms(
+ "tor-browser.ftl", # The path to write to.
+ "tor-browser.ftl", # The path to the reference file.
+ transforms_from(
+ \"\"\"
+my-new-string = { COPY(path, "my.old.string") }
+ .title = { COPY(path, "my.old.title") }
+\"\"\",
+ path="old-strings.properties", # The path to read from.
+ ),
+)
+```
+
+Note, the first argument of `add_transforms` is the target path, which is
+`tor-browser.ftl` in this case. This means that the migration script will try to
+write the resulting `my-new-string` to the locale's `./tor-browser.ftl` file.
+For example, to `translation/es-ES/tor-browser.ftl`.
+
+The second argument refers to the *reference* path. In almost all cases the
+reference file will have the same name and path as the target path, but it has a
+different role. Here the path is relative to the reference directory, which
+contains the en-US source files. In this case, by default this means that
+`translation/en-US/tor-browser.ftl` will act as the reference, but the exact
+path could be changed with the `--reference-directory` argument. The existing
+`my-new-string` will be read from this file to confirm that the migration
+recipe produces the correct result.
+
+The file `old-strings.properties` is used as an input. This means that the
+existing strings in the locale's `old-strings.properties` file will be read to
+construct the new string `my-new-string`. For example, it will be read from
+`translation/es-ES/old-strings.properties`.
+
+The `COPY` acts like a Fluent function, which asks the transformation to copy
+the content from the translated string directly.
+
+### Example 2
+
+For this example, a developer wants to swap a string in `tor-browser.ftl` from:
+
+```
+my-old-string2 = Some string content
+ .title = This is the tooltip
+```
+
+to
+
+```
+my-new-string2 =
+ .label = Some string content
+ .title = This is the tooltip
+```
-Then we copy the en-US file to our local translation repository, say at
-`/home/user/translation/en-US/updated.ftl`. The en-US file is needed as a
-reference during migration to know where in the new file the new Messages or
-Terms should be placed. Moreover, the migration can be verified against the
-en-US file to ensure it is working as intended.
+The developer removes `my-old-string2` from the file and adds `my-new-string2`
+instead. This manual change will then eventually reach the `translation`
+repository for `my-new-string2` to be translated.
-Then we run the migration for individual locales:
+The developer also writes a migration recipe to mirror this change:
```
- python migrate_l10n.py --translation-git /home/user/translation --locales 'es-ES sr' l10n_migrations.bug-xxxx-my-migration-recipe
+ctx.add_transforms(
+ "tor-browser.ftl",
+ "tor-browser.ftl",
+ transforms_from(
+ \"\"\"
+my-new-string2 =
+ .label = { COPY_PATTERN(path, "my-old-string2") }
+ .title = { COPY_PATTERN(path, "my-old-string2.title") }
+\"\"\",
+ path="tor-browser.ftl",
+ ),
+)
```
-This will first run a mock migration using the en-US localization files. This is
-to help ensure that the migration will work as intended. I.e. if we ran the
-migration recipe for en-US, using it as both the source of old strings and as a
-reference, then each transformation using these old strings should produce a
-Message or Term that is identical to the one in the reference file.
+Note that in this case the locale's `tor-browser.ftl` file is being used as both
+the input and the output.
+
+Note that for a Fluent-to-Fluent migration we use `COPY_PATTERN` rather than
+`COPY`. The second argument provides an ID that either point's to the
+Fluent Messages' value (roughly, the text content) by giving the Message's ID,
+or one of its attributes by adding a corresponding suffix to the ID.
+
+### Other examples
+
+Migration recipes can support a lot more, including more advanced
+transformations like removing or replacing HTML tags from content. There are
+some existing recipes in the `./migrations` directory that can be used as a
+reference.
+
+
+## translation directory
+
+In most cases, you will just need to check out a `translation` branch that
+contains the translated strings used by the migration recipe, as well as the
+Fluent file that will be written to. Usually, this will be a branch based on
+the origin/upstream `tor-browser` or `base-browser` branches.
+
+However, if the migration recipe requires source files that are in a different
+branch to the Fluent file that is being written to, then you will need to
+manually copy those files into the working directory before running the script.
+
+
+## Script procedure
-Then this will run `migrate(ctx)` for the es-ES and sr locales. Some of the
-transformations will not be completed for a locale if that locale does not
-contain a translated version of the old strings the transformation requires
-(because there is no string to copy).
+### Test en-US migration
-If one of the old strings is from a `.dtd` or `.properties` file, this will
-check whether they are marked as translated on weblate using its API. This
-prevents copying "placeholder" en-US values into the locale's fluent files.
+The script will first run a test migration using the en-US strings. It will run
+the migration using the files from `translation/en-US/` as the input. In the
+previous example 1, this will read `my.old.string` and `my.old.title` from
+`translation/en-US/old-strings.properties`. And in example 2, this will read
+`my-old-string2` from `translation/en-US/tor-browser.ftl`.
-Any warnings or errors will be logged to stderr in the console.
+If any of the input strings are missing, this indicates that there is likely a
+mistake in the recipe or the translation directory and the script will be
+aborted without running the migration for the other locales.
+
+Otherwise, it then compares the result of this migration with the strings found
+in the reference files. In the previous example 1, this will read the entry for
+`my-new-string` from `<reference-dir>/tor-browser.ftl`, where `<reference-dir>`
+is `translation/en-US/` unless `--reference-directory` is given to use a
+different directory. If the reference entry for `my-new-string` differs from the
+entry that the recipe automatically produced, then this indicates that there is
+a mistake in the recipe and the script will be aborted.
+
+### Locale migrations
+
+If the test migration passed, then the recipe will be re-run for each of the
+specified locales. If the locale is missing some strings or files that a single
+transformation requires, then that transformation will be skipped and the
+corresponding entry won't be written to the Fluent file. Otherwise the new
+entries will be appended to the existing Fluent files.
+
+#### Non-Fluent strings and Weblate queries
+
+Some non-Fluent formats, like DTD and properties, will fill untranslated strings
+with the source en-US content. And we don't want these untranslated strings to
+be used for migrations. There is no metadata within the files to determine this,
+and simply being the same as the en-US string is not a reliable indicator.
+
+So for these strings the script will additionally make a remote query to the
+Weblate API to fetch the metadata that indicates whether the string is
+considered translated or not. If a transformation requires a string that is
+marked as untranslated, it will be skipped.
+
+NOTE: The Weblate metadata is not always reliable, so you should still manually
+review the changes.
+
+NOTE: When testing before, the Weblate API was limited to 100 requests per day
+per IP address for unauthorised users. If this becomes an issue you may want to
+run the migrations in limited batches of locales with new IP addresses. Or, you
+can create a Weblate account and change this script to pass an authorisation
+token with the request.
"""
import argparse
@@ -63,142 +257,299 @@ import logging
import os
import sys
import urllib.request
+from collections.abc import Iterator
+from typing import Any, NamedTuple, Protocol, cast
from fluent.migrate.context import MigrationContext
from fluent.migrate.errors import EmptyLocalizationError, UnreadableReferenceError
from fluent.syntax import ast, parse, serialize
-def in_red(string):
+def in_red(string: str) -> str:
"""
Wrap a string so that it is shown as red in the console.
+ :param string: The string to wrap.
+ :returns: The wrapped string.
"""
return f"\x1b[1;91m{string}\x1b[0m"
+def assert_keys(
+ check_dict: dict[Any, Any], expected_keys: tuple[str, ...], url: str
+) -> None:
+ """
+ Verify that the dictionary contains *at least* the expected keys,
+ otherwise this throws.
+ :param check_dict: The dictionary to check.
+ :param url: The url where the dictionary was fetched from.
+ """
+ for key in expected_keys:
+ if key not in check_dict:
+ raise ValueError(f"Missing '{key}' in response for {url}")
+
+
+class WeblateUnit:
+ """
+ Represents a Weblate "unit": roughly corresponds to a translated string.
+
+ See https://docs.weblate.org/en/latest/api.html#units.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("context", "translated"), url)
+ string_id = data["context"]
+ translated = data["translated"]
+ if not isinstance(string_id, str):
+ raise ValueError(f"Unexpected 'context' type in response for {url}")
+ if not isinstance(translated, bool):
+ raise ValueError(f"Unexpected 'translated' type in response for {url}")
+
+ self.string_id = string_id
+ self.translated = translated
+
+
+class WeblateTranslation:
+ """
+ Represents a Weblate "translation": roughly corresponds to the translation
+ of a file for a given locale/language.
+
+ See https://docs.weblate.org/en/latest/api.html#translations.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("filename", "units_list_url"), url)
+ locale_path = data["filename"]
+ units_url = data["units_list_url"]
+ if not isinstance(locale_path, str):
+ raise ValueError(f"Unexpected 'filename' type in response for {url}")
+ if not isinstance(units_url, str):
+ raise ValueError(f"Unexpected 'units_list_url' type in response for {url}")
+
+ self.locale_path = locale_path
+ self.units_url = units_url
+ # The units, indexed by their string ID. Lazy-loaded and `None` whilst
+ # unfilled.
+ self.units: None | dict[str, WeblateUnit] = None
+
+
+class WeblateComponent:
+ """
+ Represents a Weblate "component": roughly corresponds to a source (en-US)
+ file that can be translated.
+
+ See https://docs.weblate.org/en/latest/api.html#components.
+ And https://docs.weblate.org/en/latest/user/basic.html.
+ """
+
+ def __init__(self, data: dict[Any, Any], url: str) -> None:
+ """
+ :param data: The Weblate data response.
+ :param url: The URL that the data came from.
+ """
+ assert_keys(data, ("template", "translations_url", "branch"), url)
+ template_path = data["template"]
+ translations_url = data["translations_url"]
+ branch = data["branch"]
+ if not isinstance(template_path, str):
+ raise ValueError(f"Unexpected 'template' type in response for {url}")
+ if not isinstance(translations_url, str):
+ raise ValueError(
+ f"Unexpected 'translations_url' type in response for {url}"
+ )
+ if not isinstance(branch, str):
+ raise ValueError(f"Unexpected 'branch' type in response for {url}")
+
+ self.branch = branch
+ # The path to the source (en-US) file.
+ self.template_path = template_path
+ # The URL to fetch the component's translations from.
+ self.translations_url = translations_url
+ # The translations data, indexed by the locale file paths. Lazy-loaded
+ # and `None` whilst unfilled.
+ self.translations: None | dict[str, WeblateTranslation] = None
+
+
class WeblateMetadata:
"""
- Manages and fetches string metadata from weblate.
+ Manages and fetches string metadata from Weblate.
"""
- def __init__(self):
+ # The translation branches that we expect to be used for Weblate.
+ _BROWSER_BRANCHES = ["tor-browser", "base-browser", "fenix-torbrowserstringsxml"]
+ _WEBLATE_API_URL = "https://hosted.weblate.org/api/"
+ _WEBLATE_API_TOR_COMPONENTS_URL = _WEBLATE_API_URL + "projects/tor/components/"
+
+ def __init__(self) -> None:
+ """
+ Create a new instance for fetching Weblate metadata.
+ """
self.logger = logging.getLogger("weblate-metadata")
self.logger.setLevel(logging.INFO)
- # The _components property will be lazy-loaded with weblate data.
- #
- # On weblate, for monolingual formats, the component will have a
- # "template" file, which matches the en-US file path in the
- # "translation" git repo. So we can find a component through a matching
- # template.
- #
- # Each translation in that component will have a "filename" that will
- # match the locale's file path in the "translation" git repo. So we can
- # find a translation through a matching filename.
- #
- # Each translation can be queried for its units, including metadata.
- # Each unit's "context" will match the string's id in the corresponding
- # file.
- #
- # Expect the final structure to be:
- # {
- # template: {
- # "translations-url": str, # Used for API translations query.
- # "translations": {
- # filename: {
- # "units-url": str, # Used for API units query.
- # "units": {
- # context: {
- # "translated": bool,
- # },
- # },
- # },
- # },
- # },
- # }
- self._components = None
-
- def _get_weblate_response(self, url):
+ # The _components property will be lazy-loaded with Weblate data.
+ self._components: dict[str, WeblateComponent] | None = None
+
+ def _get_weblate_response(self, url: str) -> Any:
+ """
+ Make a single query to Weblate.
+ :param url: The URL to fetch.
+ :returns: The JSON response.
+ """
+ if not url.startswith(self._WEBLATE_API_URL):
+ raise ValueError(f"Unexpected URL request: {url}")
+
weblate_request = urllib.request.Request(
url,
# NOTE: can set the request header:
# "Authorization": "Token WEBLATE_TOKEN"
- # to get around rate-limiting
+ # to get around rate-limiting.
+ # NOTE: We empty the User-Agent to override the default
+ # value of "Python-urllib/{major}.{minor}".
headers={"User-Agent": ""},
)
- with urllib.request.urlopen(weblate_request, timeout=20) as response:
+ with urllib.request.urlopen(weblate_request) as response:
return json.load(response)
- def _get_from_weblate(self, url):
- ret = []
+ def _get_from_weblate(self, url: str) -> list[dict[Any, Any]]:
+ """
+ Fetch a list of results from Weblate.
+ :param url: The initial URL to fetch a response from.
+ :returns: The returned list of results.
+ """
+ ret: list[dict[Any, Any]] = []
while url:
response = self._get_weblate_response(url)
+ if not isinstance(response, dict):
+ raise ValueError(f"Unexpected response type for {url}")
+ assert_keys(response, ("results", "next"), url)
+
+ res_val = response["results"]
+ if not isinstance(res_val, list):
+ raise ValueError(f"Unexpected 'results' type for {url}")
+ for res_item in res_val:
+ if not isinstance(res_item, dict):
+ raise ValueError(f"Unexpected 'results' item type for {url}")
+ ret.append(res_item)
+
# Continue to fetch the next page, if it is present.
- # Expect the "next" url to be empty
+ # Expect the "next" url to be null
# or the same url with "?page=2", etc.
- url = response["next"]
- ret.extend(response["results"])
+ next_val = response["next"]
+ if next_val is not None and not isinstance(next_val, str):
+ raise ValueError(f"Unexpected 'next' type in response for {url}")
+ url = "" if next_val is None else next_val
return ret
- def _get_components(self):
+ def _get_components(self) -> dict[str, WeblateComponent]:
+ """
+ Get all the Tor Browser Weblate components.
+
+ We identify each Weblate component by its template path: the en-US
+ file path in the translation repository.
+
+ NOTE: We assume that the template path uniquely identifies the
+ component, even though this is not guaranteed in general by Weblate.
+
+ :returns: A dictionary of components, indexed by their en-US template
+ path.
+ """
+ url = self._WEBLATE_API_TOR_COMPONENTS_URL
if self._components is None:
self._components = {
- comp["template"]: {
- "translations": None,
- "translations-url": comp["translations_url"],
- }
- for comp in self._get_from_weblate(
- "https://hosted.weblate.org/api/projects/tor/components/"
+ comp.template_path: comp
+ for comp in (
+ WeblateComponent(data, url) for data in self._get_from_weblate(url)
)
- if comp["template"]
+ if comp.template_path and comp.branch in self._BROWSER_BRANCHES
}
return self._components
- def _get_translations(self, template):
- component = self._get_components().get(template, None)
+ def _get_translations(
+ self, template_path: str
+ ) -> dict[str, WeblateTranslation] | None:
+ """
+ Get the Weblate translations for a given Weblate component.
+
+ We identify each translation by its file path: the locale-specific path
+ that the translated file is written to.
+
+ :param template_path: The component's en-US template path.
+ :returns: A dictionary of translations, indexed by their locale file
+ paths. Or `None` if no components were found.
+ """
+ component = self._get_components().get(template_path, None)
if not component:
- self.logger.warning(f"No component in weblate for {template}.")
+ self.logger.warning(f"No component in Weblate for {template_path}.")
return None
- if component["translations"] is None:
- component["translations"] = {
- trans["filename"]: {
- "units": None,
- "units-url": trans["units_list_url"],
- }
- for trans in self._get_from_weblate(component["translations-url"])
+ if component.translations is None:
+ url = component.translations_url
+ component.translations = {
+ trans.locale_path: trans
+ for trans in (
+ WeblateTranslation(data, url)
+ for data in self._get_from_weblate(url)
+ )
}
- return component["translations"]
+ return component.translations
+
+ def _get_units(
+ self, template_path: str, locale_path: str
+ ) -> dict[str, WeblateUnit] | None:
+ """
+ Get the Weblate units for a given Weblate translation.
+
+ We identify each unit by its string ID.
- def _get_units(self, template, file):
- translation_dict = self._get_translations(template)
+ :param template_path: The containing component's en-US template path.
+ :param locale_path: The translation's locale file path.
+ :returns: A dictionary of units, indexed by their string ID. Or `None`
+ if no translations could be found.
+ """
+ translation_dict = self._get_translations(template_path)
if translation_dict is None:
return None
- translation = translation_dict.get(file, None)
+ translation = translation_dict.get(locale_path, None)
if translation is None:
- self.logger.warning(f"No translation in weblate for {file}.")
+ self.logger.warning(f"No translation in Weblate for {locale_path}.")
return None
- if translation["units"] is None:
- translation["units"] = {
- unit["context"]: {
- "translated": unit["translated"],
- }
- for unit in self._get_from_weblate(translation["units-url"])
+ if translation.units is None:
+ url = translation.units_url
+ translation.units = {
+ unit.string_id: unit
+ for unit in (
+ WeblateUnit(data, url) for data in self._get_from_weblate(url)
+ )
}
- return translation["units"]
+ return translation.units
- def is_translated(self, template_path, locale_path, string_id):
+ def is_translated(self, file_path: str, locale: str, string_id: str) -> bool:
"""
- Whether the given string is marked as translated on weblate.
+ Test whether the given string is marked as translated on Weblate.
+
+ :param file_path: The file to check the translation of, relative to the
+ locale's directory.
+ :param locale: The locale to check for.
+ :param string_id: The ID of the string to check.
"""
+ template_path = os.path.join("en-US", file_path)
+ locale_path = os.path.join(locale, file_path)
unit_dict = self._get_units(template_path, locale_path)
if unit_dict is None:
return False
unit = unit_dict.get(string_id, None)
if unit is None:
- self.logger.warning(f"No unit in weblate for {locale_path}:{string_id}.")
+ self.logger.warning(f"No unit in Weblate for {locale_path}:{string_id}.")
return False
- return unit["translated"]
+ return unit.translated
class TorBrowserMigrationContext(MigrationContext):
@@ -206,12 +557,18 @@ class TorBrowserMigrationContext(MigrationContext):
Extension which adds some extra methods to use for tor-browser.
"""
- def __init__(self, locale, reference_dir, localization_dir):
+ def __init__(self, locale: str, reference_dir: str, localization_dir: str) -> None:
super().__init__(locale, reference_dir, localization_dir)
- def _fluent_keys(self, resource):
+ def _fluent_keys(self, resource: ast.Resource) -> Iterator[str]:
+ """
+ Generate all the keys within a Fluent resource, where a key is an
+ identifier for a Term, a Message, a Term attribute, or a Message
+ attribute.
+ :yield: The Fluent keys.
+ """
# ast.Resource, want to extract all Message and Term identifiers, as
- # well as their
+ # well as their attributes.
for entry in resource.body:
if not isinstance(entry, (ast.Term, ast.Message)):
continue
@@ -223,12 +580,13 @@ class TorBrowserMigrationContext(MigrationContext):
for attr in entry.attributes:
yield f"{key}.{attr.id.name}"
- def tb_get_available_strings(self):
+ def tb_get_available_strings(self) -> set[tuple[str, str]]:
"""
- Return all the (path, string_id) pairs for all loaded localization
+ Get all the (path, string_id) pairs for all loaded localization
resources.
+ :returns: The string pairs.
"""
- all_strings = set()
+ all_strings: set[tuple[str, str]] = set()
# ctx.localization_resources is a dict containing all the loaded
# localization_resources that have been added during add_transforms.
# { localization_path: resource }
@@ -237,14 +595,13 @@ class TorBrowserMigrationContext(MigrationContext):
all_strings.update((path, key) for key in self._fluent_keys(resource))
else:
# dictionary of { identifies: value } in legacy resource.
- # For tor-browser,
- # Only include references that differ from the en-US strings.
all_strings.update((path, key) for key in resource.keys())
return all_strings
- def tb_get_missing_resources(self):
+ def tb_get_missing_resources(self) -> set[str]:
"""
- Return the missing localization resources.
+ Get the missing localization resources.
+ :returns: The set of resource paths.
"""
return set(
path
@@ -253,25 +610,51 @@ class TorBrowserMigrationContext(MigrationContext):
if path not in self.localization_resources
)
- def tb_get_transform(self, target_path, transform_id):
+ def tb_get_transform(
+ self, target_path: str, transform_id: str
+ ) -> ast.Message | ast.Term | None:
"""
- Find the transformation node with the given id for the given path.
+ Find a transformation node.
+ :param target_path: The target path of the transformation.
+ :param transform_id: The ID of the transformation, AKA the string ID.
+ :returns: The matching transformation node, or `None` if there is no
+ match.
"""
for node in self.transforms[target_path]:
if node.id.name == transform_id:
return node
return None
- def tb_get_reference_entry(self, target_path, entry_id):
+ def tb_get_reference_entry(
+ self, target_path: str, transform_id: str
+ ) -> ast.Message | ast.Term | None:
"""
- Find the reference node that would be used for the given id and path.
+ Find a reference Message or Term for a given transformation.
+ :param target_path: The target path of the transformation.
+ :param transform_id: The ID of the transformation, AKA the string ID.
+ :returns: The matching reference entry for the transformation, or `None`
+ if there is no match.
"""
for entry in self.reference_resources[target_path].body:
- if isinstance(entry, (ast.Term, ast.Message)) and entry.id.name == entry_id:
+ if (
+ isinstance(entry, (ast.Term, ast.Message))
+ and entry.id.name == transform_id
+ ):
return entry.clone()
return None
+class RecipeModule(Protocol):
+ def migrate(self, context: MigrationContext) -> None: ...
+
+
+class FluentSyntaxError(NamedTuple):
+ path: str
+ message: str
+ line: int
+ sample: str
+
+
class TorBrowserMigrator:
"""
Performs a tor-browser migration.
@@ -279,26 +662,38 @@ class TorBrowserMigrator:
def __init__(
self,
- en_US_dir,
- locale_dirs,
- migrate_module,
- weblate_metadata,
- ):
+ en_US_ref_dir: str,
+ en_US_target_dir: str,
+ locale_dirs: dict[str, str],
+ recipe_module: RecipeModule,
+ weblate_metadata: WeblateMetadata,
+ ) -> None:
+ """
+ :param en_US_ref_dir: The path to the en-US directory where reference
+ Fluent entries for the recipe can be found.
+ :param en_US_target_dir: The path to the en-US directory where existing
+ strings used by the recipe can be found.
+ :param locale_dirs: The collection of locales to run the migrations for.
+ :param recipe_module: The python module that contains the recipe
+ instructions.
+ :param weblate_metadata: The object to fetch Weblate metadata from.
+ """
self.logger = logging.getLogger("tor-browser-migrator")
self.logger.setLevel(logging.INFO)
- self.en_US_dir = en_US_dir
+ self.en_US_ref_dir = en_US_ref_dir
+ self.en_US_target_dir = en_US_target_dir
self.locale_dirs = locale_dirs
- self.migrate_module = migrate_module
+ self.recipe_module = recipe_module
self.weblate_metadata = weblate_metadata
- def run(self):
+ def run(self) -> None:
"""
Run the migration.
"""
if not self._check_en_US_resources():
sys.exit(1)
- fluent_errors = []
+ fluent_errors: list[FluentSyntaxError] = []
for locale, locale_dir in self.locale_dirs.items():
if locale == "en-US":
print("", file=sys.stderr)
@@ -316,12 +711,18 @@ class TorBrowserMigrator:
"Migration does not need to be run again, but the following "
"syntax errors should be fixed manually.\n"
+ "\n".join(
- f"{in_red(full_path)}: line {line}: {message}: [[{sample}]]"
- for full_path, message, line, sample in fluent_errors
+ f"{in_red(err.path)}: line {err.line}: {err.message}: [[{err.sample}]]"
+ for err in fluent_errors
)
)
- def _run_locale(self, locale, locale_dir):
+ def _run_locale(self, locale: str, locale_dir: str) -> list[FluentSyntaxError]:
+ """
+ Run a migration for a given locale.
+ :param locale: The name of the locale.
+ :param locale_dir: The path to the locale's directory.
+ :returns: A list of Fluent errors in the written files.
+ """
print("\n\n", file=sys.stderr)
self.logger.info(f"Migrating '{in_red(locale)}' locale\n")
@@ -358,7 +759,7 @@ class TorBrowserMigrator:
available_strings = ctx.tb_get_available_strings()
wrote_file = False
- errors = []
+ errors: list[FluentSyntaxError] = []
for target_path, reference in ctx.reference_resources.items():
translated_ids = [
@@ -422,13 +823,13 @@ class TorBrowserMigrator:
break
# Strings in legacy formats might have an entry in the file
# that is just a copy of the en-US strings.
- # For these we want to check the weblate metadata to ensure
+ # For these we want to check the Weblate metadata to ensure
# it is a translated string.
if not path.endswith(
".ftl"
) and not self.weblate_metadata.is_translated(
- os.path.join("en-US", path),
- os.path.join(locale, path),
+ path,
+ locale,
string_id,
):
can_transform = False
@@ -436,7 +837,7 @@ class TorBrowserMigrator:
f"Skipping transform {target_path}:{transform_id} "
f"for '{locale}' locale because the string "
f"{path}:{string_id} has not been translated on "
- "weblate."
+ "Weblate."
)
break
if not can_transform:
@@ -463,7 +864,9 @@ class TorBrowserMigrator:
wrote_file = True
# Collect any fluent parsing errors from the newly written file.
errors.extend(
- (full_path, message, line, sample)
+ FluentSyntaxError(
+ path=full_path, message=message, line=line, sample=sample
+ )
for message, line, sample in self._fluent_errors(full_content)
)
@@ -471,27 +874,42 @@ class TorBrowserMigrator:
self.logger.info(f"No files written for '{locale}' locale.")
return errors
- def _fluent_errors(self, fluent):
+ def _fluent_errors(self, fluent_content: str) -> Iterator[tuple[str, int, str]]:
"""
- Verify that the given fluent string can be parsed correctly.
+ Parse the given content as a Fluent file and generate all the syntax
+ errors.
+ :param fluent_content: The file content to parse.
+ :yield: Each encountered Fluent syntax error as a triple of the message,
+ the line number, and a sample.
"""
- resource = parse(fluent)
+ resource = parse(fluent_content)
for entry in resource.body:
if not isinstance(entry, ast.Junk):
continue
for annotation in entry.annotations:
- line = fluent[0 : annotation.span.start].count("\n") + 1
- sample_start = max(annotation.span.start - 15, 0)
- sample = "…" + fluent[sample_start : sample_start + 30] + "…"
- yield annotation.message, line, sample
-
- def _get_migration_context(self, locale, locale_dir):
- prev_missing_resources = set()
+ start = 0
+ if annotation.span:
+ start = annotation.span.start
+ line = fluent_content[0:start].count("\n") + 1
+ sample_start = max(start - 15, 0)
+ sample = "…" + fluent_content[sample_start : sample_start + 30] + "…"
+ yield annotation.message or "", line, sample
+
+ def _get_migration_context(
+ self, locale: str, locale_dir: str
+ ) -> TorBrowserMigrationContext:
+ """
+ Create a new migration context.
+ :param locale: The name of the locale.
+ :param locale_dir: The directory path for the locale.
+ :returns: The new context.
+ """
+ prev_missing_resources: set[str] = set()
while True:
- ctx = TorBrowserMigrationContext(locale, self.en_US_dir, locale_dir)
+ ctx = TorBrowserMigrationContext(locale, self.en_US_ref_dir, locale_dir)
try:
- self.migrate_module.migrate(ctx)
+ self.recipe_module.migrate(ctx)
except EmptyLocalizationError:
# This case will be handled by missing_resources below.
# NOTE: At the time of writing, add_transforms only throws if
@@ -543,20 +961,28 @@ class TorBrowserMigrator:
# before localization_resources was fully populated.
prev_missing_resources = missing_resources
- def _remove_if_empty(self, path):
+ def _remove_if_empty(self, path: str) -> None:
+ """
+ Remove a file if it is empty.
+ :param path: The path to remove.
+ """
if os.stat(path).st_size:
self.logger.warning(f"{path} is no longer empty. Not deleting.")
return
os.remove(path)
- def _check_en_US_resources(self):
- # We pass in the en-US directory as the localization directory, as well
- # as the reference directory.
- ctx = TorBrowserMigrationContext("en-US", self.en_US_dir, self.en_US_dir)
+ def _check_en_US_resources(self) -> bool:
+ """
+ Verify that the migration recipe works as expected using en-US strings.
+ :returns: Whether the recipe worked as expected.
+ """
+ ctx = TorBrowserMigrationContext(
+ "en-US", self.en_US_ref_dir, self.en_US_target_dir
+ )
have_error = False
try:
- self.migrate_module.migrate(ctx)
+ self.recipe_module.migrate(ctx)
except EmptyLocalizationError:
# Handle with localization_resources check.
# NOTE: This throwing may have prevented further add_transforms from
@@ -566,7 +992,9 @@ class TorBrowserMigrator:
have_error = True
except UnreadableReferenceError:
# Reference filename is printed before this.
- self.logger.error("Missing an en-US reference file.")
+ self.logger.error(
+ "Missing an en-US reference file. Is --reference-directory correct?"
+ )
return False
# Check each transform would create the same entry in the target as the
@@ -602,7 +1030,8 @@ class TorBrowserMigrator:
reference_entry = ctx.tb_get_reference_entry(target_path, transform_id)
if reference_entry is None:
self.logger.error(
- f"Missing en-US reference entry for transform {transform_name}"
+ f"Missing en-US reference entry for transform {transform_name}. "
+ "Is --reference-directory correct?"
)
have_error = True
continue
@@ -625,9 +1054,50 @@ class TorBrowserMigrator:
return not have_error
+def main(recipe_path: str, translation_dir: str, locales: str, ref_dir: str) -> None:
+ """
+ The main method.
+ :param recipe_path: The path to the recipe script.
+ :param translation_dir: The path to the translation repository directory.
+ :param locales: The locales to run the recipe for, separated by spaces.
+ :param ref_dir: The path to the reference directory.
+ """
+ if not os.path.isfile(recipe_path):
+ print(f"{in_red(recipe_path)} is not a file.", file=sys.stderr)
+ sys.exit(1)
+
+ recipe_module_spec = importlib.util.spec_from_file_location("_recipe", recipe_path)
+ recipe_module = cast(
+ RecipeModule, importlib.util.module_from_spec(recipe_module_spec)
+ )
+ recipe_module_spec.loader.exec_module(recipe_module)
+
+ def check_dir(path: str) -> str:
+ if not os.path.isdir(path):
+ print(f"{in_red(path)} is not a directory.", file=sys.stderr)
+ sys.exit(1)
+ return path
+
+ translation_dir = check_dir(translation_dir)
+ en_US_target_dir = check_dir(os.path.join(translation_dir, "en-US"))
+ en_US_ref_dir = en_US_target_dir if ref_dir is None else check_dir(ref_dir)
+
+ TorBrowserMigrator(
+ en_US_ref_dir,
+ en_US_target_dir,
+ {
+ locale: check_dir(os.path.join(translation_dir, locale))
+ for locale in (l.strip() for l in locales.split(" "))
+ if locale
+ },
+ recipe_module,
+ WeblateMetadata(),
+ ).run()
+
+
parser = argparse.ArgumentParser(
description="Run a tor-browser localization migration. "
- "See documentation within migrate_l10n.py."
+ "See documentation within migrate.py."
)
parser.add_argument(
"--translation-git",
@@ -638,35 +1108,30 @@ parser.add_argument(
parser.add_argument(
"--locales",
required=True,
- metavar="<locale1> <locale2> ...",
- help="Set of locales to restrict the migration to, separated by space.",
+ metavar="'<locale1> <locale2> ...'",
+ help="Set of locales to run the migration for, separated by space.",
)
parser.add_argument(
- "migration",
- help="Migration to run, given as a python module. "
- 'E.g. "l10n_migrations.my-migration-script".',
+ "--reference-directory",
+ metavar="<dir>",
+ help="Location of the en-US directory that contains the reference changes "
+ "that the recipe corresponds to. E.g. if the recipe constructs the string "
+ "`my-new-string` in `./tor-browser.ftl`, it should point to a directory "
+ "that contains the en-US `tor-browser.ftl` with `my-new-string` already "
+ "within it. Defaults to the `en-US/` sub-directory within the "
+ "translation-git directory.",
+)
+parser.add_argument(
+ "recipe",
+ help="The path to the migration recipe to run.",
)
parsed_args = parser.parse_args()
-
-def check_dir(path):
- if not os.path.isdir(path):
- print(f"{in_red(path)} is not a directory.", file=sys.stderr)
- sys.exit(1)
- return path
-
-
-translation_dir = check_dir(os.path.abspath(parsed_args.translation_git))
-
-TorBrowserMigrator(
- check_dir(os.path.join(translation_dir, "en-US")),
- {
- locale: check_dir(os.path.join(translation_dir, locale))
- for locale in (l.strip() for l in parsed_args.locales.split(" "))
- if locale
- },
- importlib.import_module(parsed_args.migration),
- WeblateMetadata(),
-).run()
+main(
+ parsed_args.recipe,
+ parsed_args.translation_git,
+ parsed_args.locales,
+ parsed_args.reference_directory,
+)
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/1f8c6d…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/1f8c6d…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0