From 9e91a1f021421077e17a5e53bcbc6680de8ea2c2 Mon Sep 17 00:00:00 2001 From: Alex Hochheiden Date: Sun, 13 Apr 2025 17:48:23 +0000 Subject: [PATCH] Bug 1715287 - [lint] Enable remaining pyupgrade rules and lint tree r=linter-reviewers,webdriver-reviewers,translations-reviewers,whimboo,sylvestre Differential Revision: https://phabricator.services.mozilla.com/D245320 --- accessible/base/RelationTypeGen.py | 2 +- accessible/base/RoleHGen.py | 2 +- browser/app/macversion.py | 4 +- .../marionette/session_store_test_case.py | 6 +- ...st_persist_closed_tabs_restore_manually.py | 4 +- .../marionette/test_restore_loading_tab.py | 2 +- .../test/marionette/test_restore_manually.py | 4 +- .../test_restore_manually_with_pinned_tabs.py | 2 +- .../test_restore_manually_with_tab_groups.py | 2 +- .../test/marionette/test_restore_sidebar.py | 4 +- .../test_restore_sidebar_automatic.py | 4 +- ..._restore_windows_after_restart_and_quit.py | 4 +- .../marionette/test_taskbartab_restore.py | 4 +- .../test_taskbartab_sessionstate.py | 4 +- browser/components/storybook/mach_commands.py | 2 +- build/build-clang/build-clang.py | 8 +- build/clang-plugin/import_mozilla_checks.py | 4 +- build/gn_processor.py | 6 +- build/mach_initialize.py | 6 +- build/midl.py | 4 +- build/pgo/genpgocert.py | 46 ++- build/pgo/profileserver.py | 6 +- build/unix/elfhack/inject/copy_source.py | 2 +- build/upload_generated_sources.py | 24 +- build/valgrind/mach_commands.py | 2 +- build/valgrind/output_handler.py | 2 +- build/variables.py | 2 +- client.py | 2 +- config/check_js_msg_encoding.py | 6 +- config/check_js_opcode.py | 4 +- config/check_source_count.py | 24 +- config/check_spidermonkey_style.py | 8 +- config/create_rc.py | 8 +- config/createprecomplete.py | 2 +- .../preprocess_wasm2c_config.py | 2 +- config/make-stl-wrappers.py | 2 +- config/make-windows-h-wrapper.py | 16 +- config/mozunit/mozunit/mozunit.py | 10 +- config/nsinstall.py | 8 +- config/tests/unit-mozunit.py | 22 +- config/tests/unit-nsinstall.py | 4 +- config/tests/unitMozZipFile.py | 2 +- configure.py | 2 +- devtools/rename.py | 2 +- dom/base/usecounters.py | 2 +- dom/bindings/mozwebidlcodegen/__init__.py | 8 +- .../test/test_mozwebidlcodegen.py | 8 +- dom/bindings/parser/runtests.py | 2 +- .../generate-wrappers-and-manifest.py | 28 +- dom/media/test/reftest/gen_combos.py | 2 +- dom/media/tools/checkGmpBalrog.py | 4 +- dom/media/tools/generateGmpJson.py | 14 +- .../webaudio/test/generate-test-files.py | 6 +- .../gn-configs/abseil_preprocessor.py | 2 +- .../gn-configs/webrtc_preprocessor.py | 2 +- .../third_party_build/lookup_branch_head.py | 2 +- .../qm_try_analysis/fn_anchors.py | 2 +- .../qm_try_analysis/telemetry.py | 2 +- .../qm-try-analysis/qm_try_analysis/utils.py | 6 +- .../qm-try-analysis/tests/test_reporting.py | 2 +- .../file_check-binary-messages_wsh.py | 6 +- gfx/layers/d3d11/genshaders.py | 16 +- intl/locale/props2arrays.py | 2 +- intl/unicharutil/util/base_chars.py | 17 +- ipc/ipdl/test/ipdl/runtests.py | 2 +- js/src/GeneratePrefs.py | 28 +- js/src/builtin/embedjs.py | 2 +- js/src/builtin/intl/make_intl_data.py | 334 +++++++----------- js/src/devtools/automation/autospider.py | 16 +- js/src/devtools/gc/gc-test.py | 2 +- js/src/devtools/rootAnalysis/analyze.py | 2 +- js/src/devtools/rootAnalysis/mach_commands.py | 4 +- js/src/devtools/rootAnalysis/run-test.py | 2 +- js/src/devtools/rootAnalysis/t/graph/test.py | 4 +- js/src/devtools/rootAnalysis/t/testlib.py | 19 +- js/src/frontend/GenerateReservedWords.py | 26 +- js/src/frontend/align_stack_comment.py | 14 +- js/src/gdb/mozilla/ExecutableAllocator.py | 6 +- js/src/gdb/mozilla/GCCellPtr.py | 8 +- js/src/gdb/mozilla/Interpreter.py | 10 +- js/src/gdb/mozilla/IonGraph.py | 6 +- js/src/gdb/mozilla/JSObject.py | 4 +- js/src/gdb/mozilla/JSString.py | 2 +- js/src/gdb/mozilla/JSSymbol.py | 6 +- js/src/gdb/mozilla/PropertyKey.py | 2 +- js/src/gdb/mozilla/Root.py | 2 +- js/src/gdb/mozilla/jsop.py | 8 +- js/src/gdb/mozilla/jsval.py | 6 +- js/src/gdb/mozilla/prettyprinters.py | 4 +- js/src/gdb/mozilla/unwind.py | 10 +- js/src/gdb/progressbar.py | 2 +- js/src/gdb/run-tests.py | 2 +- js/src/gdb/taskpool.py | 6 +- js/src/gdb/tests/enum-printers.py | 8 +- js/src/gdb/tests/typedef-printers.py | 2 +- js/src/irregexp/import-irregexp.py | 2 +- js/src/jit-test/jit_test.py | 10 +- js/src/jit/GenerateCacheIRFiles.py | 38 +- js/src/jit/GenerateLIRFiles.py | 4 +- js/src/jit/GenerateMIRFiles.py | 14 +- js/src/make-source-package.py | 48 ++- js/src/shell/js-gdb.py | 2 +- js/src/tests/compare_bench.py | 12 +- js/src/tests/jstests.py | 8 +- js/src/tests/lib/jittests.py | 74 ++-- js/src/tests/lib/manifest.py | 23 +- js/src/tests/lib/progressbar.py | 8 +- js/src/tests/lib/results.py | 24 +- js/src/tests/lib/structuredlog.py | 2 +- js/src/tests/lib/tasks_adb_remote.py | 14 +- js/src/tests/lib/tasks_unix.py | 4 +- js/src/tests/lib/terminal_unix.py | 2 +- js/src/tests/lib/terminal_win.py | 2 +- js/src/tests/lib/tests.py | 6 +- js/src/tests/lib/wptreport.py | 2 +- .../make-normalize-generateddata-input.py | 18 +- js/src/tests/parsemark.py | 6 +- js/src/tests/test/run.py | 2 +- js/src/tests/test262-update.py | 4 +- js/src/util/make_unicode.py | 133 +++---- js/src/vm/jsopcode.py | 61 +--- js/src/vm/make_opcode_doc.py | 26 +- js/xpconnect/loader/script_cache.py | 6 +- layout/tools/reftest/output.py | 2 +- layout/tools/reftest/reftest/__init__.py | 8 +- layout/tools/reftest/reftestcommandline.py | 2 +- layout/tools/reftest/runreftest.py | 18 +- layout/tools/reftest/selftest/conftest.py | 2 +- .../selftest/test_reftest_manifest_parser.py | 2 +- memory/replace/dmd/block_analyzer.py | 14 +- memory/replace/dmd/dmd.py | 57 +-- memory/replace/dmd/test/scan-test.py | 4 +- .../replace/logalloc/replay/logalloc_munge.py | 2 +- .../androidTest/parse-ui-test-fromfile.py | 2 +- .../src/main/java/appservices_version_bump.py | 2 +- mobile/android/beta-cut.py | 4 +- .../fenix/experimentintegration/adbrun.py | 2 +- .../generate_smoke_tests.py | 4 +- .../experimentintegration/gradlewbuild.py | 4 +- .../mozilla/fenix/syncintegration/adbrun.py | 2 +- .../mozilla/fenix/syncintegration/conftest.py | 14 +- .../fenix/syncintegration/gradlewbuild.py | 8 +- .../org/mozilla/fenix/syncintegration/tps.py | 6 +- .../androidTest/parse-ui-test-fromfile.py | 2 +- .../fenix/tools/data_renewal_generate.py | 2 +- .../fenix/tools/data_renewal_request.py | 2 +- mobile/android/fenix/tools/run_benchmark.py | 16 +- .../fenix/tools/setup-startup-profiling.py | 4 +- .../android/fenix/tools/update-glean-tags.py | 2 +- .../androidTest/parse-ui-test-fromfile.py | 2 +- .../tools/data_renewal_generate.py | 2 +- .../tools/data_renewal_request.py | 2 +- .../focus-android/tools/update-glean-tags.py | 2 +- mobile/android/gradle.py | 2 +- .../libpref/init/generate_static_pref_list.py | 54 ++- moz.configure | 2 +- .../build/generate_profiling_categories.py | 20 +- netwerk/base/makecppstring.py | 2 +- pyproject.toml | 9 - python/gdbpp/gdbpp/__init__.py | 2 +- python/gdbpp/gdbpp/enumset.py | 2 +- python/gdbpp/gdbpp/linkedlist.py | 2 +- python/gdbpp/gdbpp/owningthread.py | 2 +- python/gdbpp/gdbpp/smartptr.py | 6 +- python/gdbpp/gdbpp/string.py | 2 +- python/gdbpp/gdbpp/syncedcontext.py | 2 +- python/gdbpp/gdbpp/tarray.py | 2 +- python/gdbpp/gdbpp/thashtable.py | 2 +- python/l10n/test_fluent_migrations/fmt.py | 2 +- python/mach/mach/commands/commandinfo.py | 32 +- python/mach/mach/commands/settings.py | 4 +- python/mach/mach/config.py | 4 +- python/mach/mach/main.py | 2 +- python/mach/mach/registrar.py | 4 +- python/mach/mach/requirements.py | 2 +- python/mach/mach/sentry.py | 2 +- python/mach/mach/site.py | 2 +- python/mach_commands.py | 4 +- python/mozboot/mozboot/android.py | 31 +- python/mozboot/mozboot/base.py | 4 +- python/mozboot/mozboot/bootstrap.py | 8 +- python/mozboot/mozboot/linux_common.py | 2 +- python/mozboot/mozboot/mach_commands.py | 2 +- python/mozboot/mozboot/mozconfig.py | 2 +- python/mozboot/mozboot/osx.py | 2 +- python/mozboot/mozboot/test/test_msrv.py | 2 +- .../mozbuild/mozbuild/action/check_binary.py | 10 +- .../mozbuild/mozbuild/action/dumpsymbols.py | 2 +- python/mozbuild/mozbuild/action/fat_aar.py | 22 +- .../mozbuild/mozbuild/action/file_generate.py | 4 +- .../mozbuild/action/langpack_manifest.py | 14 +- python/mozbuild/mozbuild/action/node.py | 2 +- .../mozbuild/action/process_define_files.py | 8 +- .../mozbuild/action/symbols_archive.py | 4 +- .../mozbuild/mozbuild/action/test_archive.py | 6 +- python/mozbuild/mozbuild/action/tooltool.py | 32 +- .../mozbuild/mozbuild/action/unify_symbols.py | 6 +- python/mozbuild/mozbuild/analyze/hg.py | 12 +- python/mozbuild/mozbuild/artifact_cache.py | 2 +- python/mozbuild/mozbuild/artifact_commands.py | 8 +- python/mozbuild/mozbuild/artifacts.py | 72 ++-- python/mozbuild/mozbuild/backend/base.py | 4 +- python/mozbuild/mozbuild/backend/common.py | 6 +- .../mozbuild/backend/configenvironment.py | 10 +- .../mozbuild/backend/mach_commands.py | 18 +- .../mozbuild/backend/recursivemake.py | 12 +- python/mozbuild/mozbuild/base.py | 16 +- .../mozbuild/code_analysis/mach_commands.py | 93 ++--- .../mozbuild/mozbuild/code_analysis/utils.py | 2 +- .../mozbuild/codecoverage/lcov_rewriter.py | 14 +- .../mozbuild/codecoverage/manifest_handler.py | 2 +- .../mozbuild/mozbuild/compilation/warnings.py | 6 +- python/mozbuild/mozbuild/config_status.py | 4 +- .../mozbuild/mozbuild/configure/__init__.py | 4 +- python/mozbuild/mozbuild/configure/help.py | 2 +- python/mozbuild/mozbuild/configure/lint.py | 14 +- python/mozbuild/mozbuild/configure/options.py | 4 +- python/mozbuild/mozbuild/configure/util.py | 2 +- .../mozbuild/mozbuild/controller/building.py | 13 +- .../mozbuild/mozbuild/controller/clobber.py | 4 +- python/mozbuild/mozbuild/doctor.py | 8 +- python/mozbuild/mozbuild/faster_daemon.py | 26 +- python/mozbuild/mozbuild/frontend/context.py | 6 +- python/mozbuild/mozbuild/frontend/data.py | 8 +- python/mozbuild/mozbuild/frontend/emitter.py | 2 +- .../mozbuild/mozbuild/frontend/gyp_reader.py | 2 +- python/mozbuild/mozbuild/frontend/reader.py | 10 +- python/mozbuild/mozbuild/generated_sources.py | 2 +- python/mozbuild/mozbuild/html_build_viewer.py | 2 +- python/mozbuild/mozbuild/jar.py | 18 +- python/mozbuild/mozbuild/mach_commands.py | 22 +- python/mozbuild/mozbuild/makeutil.py | 6 +- python/mozbuild/mozbuild/mozconfig.py | 2 +- python/mozbuild/mozbuild/mozinfo.py | 8 +- python/mozbuild/mozbuild/preprocessor.py | 18 +- python/mozbuild/mozbuild/repackaging/mar.py | 4 +- python/mozbuild/mozbuild/repackaging/msi.py | 4 +- python/mozbuild/mozbuild/repackaging/msix.py | 88 ++--- .../repackaging/snapcraft_transform.py | 4 +- python/mozbuild/mozbuild/shellutil.py | 2 +- python/mozbuild/mozbuild/telemetry.py | 2 +- .../mozbuild/test/action/test_buildlist.py | 8 +- .../action/test_html_fragment_preprocessor.py | 2 +- .../mozbuild/test/backend/test_database.py | 26 +- .../test/backend/test_recursivemake.py | 90 +++-- .../test/backend/test_test_manifest.py | 2 +- python/mozbuild/mozbuild/test/common.py | 2 +- .../mozbuild/test/configure/common.py | 8 +- .../test/configure/test_checks_configure.py | 2 +- .../test/configure/test_compile_checks.py | 6 +- .../test/configure/test_moz_configure.py | 4 +- .../configure/test_toolchain_configure.py | 2 +- .../mozbuild/test/frontend/test_context.py | 4 +- .../mozbuild/test/frontend/test_namespaces.py | 2 +- .../mozbuild/test/test_artifact_cache.py | 4 +- python/mozbuild/mozbuild/test/test_base.py | 24 +- .../mozbuild/mozbuild/test/test_jarmaker.py | 6 +- python/mozbuild/mozbuild/test/test_mozinfo.py | 2 +- python/mozbuild/mozbuild/test/test_util.py | 8 +- python/mozbuild/mozbuild/testing.py | 4 +- python/mozbuild/mozbuild/toolchains.py | 2 +- python/mozbuild/mozbuild/util.py | 12 +- python/mozbuild/mozbuild/vendor/moz_yaml.py | 10 +- .../mozbuild/vendor/rewrite_mozbuild.py | 4 +- .../mozbuild/mozbuild/vendor/vendor_rust.py | 62 ++-- python/mozbuild/mozpack/archive.py | 2 +- python/mozbuild/mozpack/chrome/flags.py | 6 +- python/mozbuild/mozpack/chrome/manifest.py | 2 +- python/mozbuild/mozpack/copier.py | 6 +- python/mozbuild/mozpack/dmg.py | 4 +- python/mozbuild/mozpack/errors.py | 2 +- python/mozbuild/mozpack/files.py | 6 +- python/mozbuild/mozpack/macpkg.py | 6 +- python/mozbuild/mozpack/manifests.py | 2 +- python/mozbuild/mozpack/mozjar.py | 12 +- python/mozbuild/mozpack/packager/__init__.py | 10 +- python/mozbuild/mozpack/packager/formats.py | 4 +- python/mozbuild/mozpack/packager/l10n.py | 8 +- python/mozbuild/mozpack/path.py | 4 +- python/mozbuild/mozpack/test/test_errors.py | 2 +- python/mozbuild/mozpack/test/test_files.py | 10 +- .../mozbuild/mozpack/test/test_manifests.py | 44 +-- python/mozbuild/mozpack/test/test_packager.py | 8 +- python/mozbuild/mozpack/test/test_unify.py | 2 +- python/mozlint/mozlint/cli.py | 8 +- python/mozlint/mozlint/errors.py | 4 +- python/mozlint/mozlint/formatters/__init__.py | 2 +- python/mozlint/mozlint/formatters/compact.py | 2 +- python/mozlint/mozlint/formatters/stylish.py | 6 +- python/mozlint/mozlint/formatters/summary.py | 2 +- .../mozlint/mozlint/formatters/treeherder.py | 2 +- python/mozlint/mozlint/formatters/unix.py | 2 +- python/mozlint/mozlint/parser.py | 6 +- python/mozlint/mozlint/pathutils.py | 10 +- python/mozlint/mozlint/result.py | 4 +- python/mozlint/mozlint/roller.py | 4 +- python/mozlint/mozlint/types.py | 6 +- python/mozlint/test/linters/external.py | 4 +- python/mozlint/test/test_pathutils.py | 2 +- .../mozperftest/mozperftest/metrics/common.py | 6 +- .../mozperftest/metrics/notebook/constant.py | 2 +- .../metrics/notebook/perftestetl.py | 2 +- .../metrics/notebook/perftestnotebook.py | 2 +- .../metrics/notebook/transformer.py | 2 +- .../mozperftest/metrics/perfherder.py | 6 +- .../mozperftest/system/android_perf_tuner.py | 12 +- .../mozperftest/mozperftest/system/proxy.py | 2 +- .../mozperftest/test/browsertime/runner.py | 6 +- .../mozperftest/tests/test_binarysetup.py | 2 +- .../mozperftest/tests/test_shellscript.py | 8 +- .../mozperftest/tests/test_transformer.py | 2 +- .../mozrelease/mozrelease/buglist_creator.py | 14 +- .../mozrelease/mozrelease/partner_repack.py | 2 +- python/mozrelease/mozrelease/paths.py | 10 +- .../mozrelease/scriptworker_canary.py | 8 +- python/mozrelease/mozrelease/update_verify.py | 2 +- python/mozrelease/test/test_versions.py | 2 +- python/mozterm/mozterm/terminal.py | 2 +- python/mozterm/mozterm/widgets.py | 2 +- python/mozterm/test/test_widgets.py | 2 +- .../mozversioncontrol/errors.py | 2 +- .../mozversioncontrol/repo/base.py | 2 +- .../mozversioncontrol/repo/git.py | 2 +- .../mozversioncontrol/repo/mercurial.py | 2 +- .../mozversioncontrol/repo/source.py | 2 +- remote/mach_commands.py | 24 +- security/generate_mapfile.py | 2 +- security/manager/ssl/gen_cert_header.py | 2 +- .../crtshToIdentifyingStruct.py | 25 +- security/manager/tools/mach_commands.py | 4 +- security/manager/tools/pycert.py | 4 +- security/manager/tools/pycms.py | 2 +- security/manager/tools/pyct.py | 4 +- security/manager/tools/pykey.py | 4 +- security/manager/tools/pypkcs12.py | 2 +- taskcluster/android_taskgraph/build_config.py | 10 +- .../transforms/build_android_app.py | 2 +- .../android_taskgraph/transforms/notify.py | 4 +- .../android_taskgraph/util/scriptworker.py | 6 +- .../scripts/funsize.py | 14 +- .../scripts/getCTKnownLogs.py | 14 +- taskcluster/docker/snap-coreXX-build/parse.py | 2 +- .../snap-tests/basic_tests.py | 82 ++--- .../snap-coreXX-build/snap-tests/qa_tests.py | 58 ++- .../gecko_taskgraph/actions/cancel_all.py | 4 +- .../gecko_taskgraph/actions/registry.py | 12 +- .../actions/release_promotion.py | 12 +- .../gecko_taskgraph/actions/retrigger.py | 16 +- .../actions/run_missing_tests.py | 4 +- taskcluster/gecko_taskgraph/actions/util.py | 4 +- taskcluster/gecko_taskgraph/decision.py | 6 +- taskcluster/gecko_taskgraph/loader/test.py | 4 +- taskcluster/gecko_taskgraph/main.py | 2 +- .../gecko_taskgraph/optimize/strategies.py | 8 +- taskcluster/gecko_taskgraph/parameters.py | 2 +- .../test/test_util_backstop.py | 11 +- .../gecko_taskgraph/transforms/artifact.py | 2 +- .../gecko_taskgraph/transforms/attribution.py | 2 +- .../transforms/beetmover_repackage_partner.py | 8 +- .../transforms/bouncer_submission.py | 10 +- .../transforms/bouncer_submission_partners.py | 10 +- .../transforms/chunk_partners.py | 4 +- .../gecko_taskgraph/transforms/diffoscope.py | 4 +- .../transforms/docker_image.py | 12 +- .../gecko_taskgraph/transforms/fetch.py | 2 +- .../transforms/geckodriver_signing.py | 2 +- .../transforms/job/__init__.py | 26 +- .../transforms/job/distro_package.py | 4 +- .../transforms/job/mozharness.py | 2 +- .../transforms/job/mozharness_test.py | 4 +- .../transforms/job/run_task.py | 2 +- .../transforms/job/toolchain.py | 4 +- .../gecko_taskgraph/transforms/l10n.py | 2 +- .../gecko_taskgraph/transforms/partials.py | 6 +- .../transforms/partner_attribution.py | 44 +-- .../partner_attribution_beetmover.py | 2 +- .../transforms/partner_signing.py | 6 +- .../gecko_taskgraph/transforms/repackage.py | 4 +- .../gecko_taskgraph/transforms/signing.py | 2 +- .../gecko_taskgraph/transforms/snap_test.py | 2 +- .../gecko_taskgraph/transforms/source_test.py | 2 +- .../transforms/startup_test.py | 4 +- .../gecko_taskgraph/transforms/task.py | 2 +- .../gecko_taskgraph/transforms/test/chunk.py | 4 +- .../transforms/update_verify_config.py | 4 +- .../gecko_taskgraph/try_option_syntax.py | 18 +- taskcluster/gecko_taskgraph/util/bugbug.py | 4 +- taskcluster/gecko_taskgraph/util/hash.py | 5 +- taskcluster/gecko_taskgraph/util/hg.py | 4 +- taskcluster/gecko_taskgraph/util/partners.py | 8 +- taskcluster/gecko_taskgraph/util/verify.py | 77 ++-- taskcluster/mach_commands.py | 2 +- taskcluster/scripts/lib/testrail_utils.py | 4 +- taskcluster/scripts/misc/repack_rust.py | 23 +- .../scripts/tests/copy-artifacts-from-ftl.py | 2 +- testing/addtest.py | 18 +- testing/awsy/awsy/parse_about_memory.py | 6 +- testing/awsy/awsy/process_perf_data.py | 4 +- testing/awsy/awsy/webservers.py | 10 +- testing/condprofile/condprof/archiver.py | 2 +- testing/condprofile/condprof/progress.py | 2 +- .../firefox_ui_harness/arguments/base.py | 2 +- .../safebrowsing/test_initial_download.py | 2 +- .../safebrowsing/test_warning_pages.py | 2 +- testing/gtest/gtest_filter_sets.py | 6 +- testing/gtest/remotegtests.py | 6 +- testing/gtest/rungtests.py | 2 +- testing/mach_commands.py | 18 +- .../client/marionette_driver/addons.py | 2 +- .../marionette/client/marionette_driver/by.py | 2 +- .../marionette_driver/date_time_value.py | 2 +- .../client/marionette_driver/errors.py | 8 +- .../client/marionette_driver/expected.py | 12 +- .../client/marionette_driver/geckoinstance.py | 22 +- .../client/marionette_driver/keys.py | 2 +- .../client/marionette_driver/localization.py | 2 +- .../client/marionette_driver/marionette.py | 50 ++- .../marionette_driver/processhandler.py | 10 +- .../client/marionette_driver/timeout.py | 2 +- .../client/marionette_driver/transport.py | 36 +- .../client/marionette_driver/wait.py | 6 +- .../client/marionette_driver/webauthn.py | 2 +- .../marionette_test/decorators.py | 2 +- .../marionette_test/testcases.py | 22 +- .../harness/marionette_harness/runner/base.py | 65 ++-- .../marionette_harness/runner/httpd.py | 28 +- .../marionette_harness/runner/serve.py | 10 +- .../harness/marionette_harness/runtests.py | 8 +- testing/mochitest/bisection.py | 2 +- testing/mochitest/leaks.py | 4 +- testing/mochitest/mach_commands.py | 4 +- testing/mochitest/mochitest_options.py | 10 +- testing/mochitest/runtests.py | 84 ++--- testing/mochitest/runtestsremote.py | 2 +- testing/mochitest/tests/python/conftest.py | 2 +- .../tests/python/test_build_profile.py | 2 +- .../docs/_static/structured_example.py | 2 +- .../manifestparser/manifestparser/cli.py | 2 +- .../manifestparser/expression.py | 30 +- .../manifestparser/manifestparser/filters.py | 17 +- .../manifestparser/manifestparser/ini.py | 14 +- .../manifestparser/manifestparser/logger.py | 2 +- .../manifestparser/manifestparser.py | 4 +- .../tests/test_manifestparser.py | 10 +- testing/mozbase/mozcrash/mozcrash/mozcrash.py | 48 +-- testing/mozbase/mozcrash/tests/conftest.py | 6 +- testing/mozbase/mozdevice/mozdevice/adb.py | 10 +- .../mozdevice/tests/test_socket_connection.py | 10 +- testing/mozbase/mozfile/mozfile/mozfile.py | 2 +- .../mozfile/tests/test_copycontents.py | 4 +- testing/mozbase/mozfile/tests/test_tree.py | 2 +- .../mozgeckoprofiler/profiling.py | 5 +- .../mozgeckoprofiler/symFileManager.py | 2 +- .../mozgeckoprofiler/symbolication.py | 6 +- .../mozgeckoprofiler/viewgeckoprofile.py | 6 +- testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py | 4 +- testing/mozbase/mozhttpd/tests/api.py | 24 +- testing/mozbase/mozhttpd/tests/baseurl.py | 4 +- testing/mozbase/mozhttpd/tests/filelisting.py | 4 +- testing/mozbase/mozinfo/mozinfo/mozinfo.py | 2 +- .../mozbase/mozinfo/mozinfo/platforminfo.py | 2 +- .../mozinstall/mozinstall/mozinstall.py | 4 +- testing/mozbase/mozinstall/tests/conftest.py | 2 +- testing/mozbase/mozleak/mozleak/leaklog.py | 2 +- testing/mozbase/mozleak/mozleak/lsan.py | 2 +- testing/mozbase/mozlog/mozlog/__init__.py | 2 +- testing/mozbase/mozlog/mozlog/capture.py | 2 +- .../mozlog/mozlog/formatters/html/xmlgen.py | 8 +- .../mozlog/mozlog/formatters/machformatter.py | 25 +- .../mozlog/mozlog/formatters/tbplformatter.py | 14 +- .../mozbase/mozlog/mozlog/handlers/base.py | 2 +- .../mozlog/mozlog/handlers/messagehandler.py | 2 +- .../mozlog/mozlog/handlers/statushandler.py | 2 +- .../mozlog/mozlog/handlers/summaryhandler.py | 2 +- .../mozlog/mozlog/handlers/valgrindhandler.py | 2 +- testing/mozbase/mozlog/mozlog/logtypes.py | 4 +- testing/mozbase/mozlog/mozlog/proxy.py | 2 +- .../mozlog/mozlog/pytest_mozlog/plugin.py | 10 +- testing/mozbase/mozlog/mozlog/reader.py | 2 +- .../mozbase/mozlog/mozlog/scripts/logmerge.py | 2 +- testing/mozbase/mozlog/mozlog/stdadapter.py | 2 +- .../mozbase/mozlog/mozlog/structuredlog.py | 12 +- .../mozlog/unstructured/loggingmixin.py | 2 +- .../mozbase/mozlog/tests/test_formatters.py | 6 +- .../mozbase/mozlog/tests/test_structured.py | 2 +- .../mozlog/tests/test_terminal_colors.py | 2 +- .../mozpower/mozpower/intel_power_gadget.py | 6 +- testing/mozbase/mozpower/mozpower/mozpower.py | 2 +- .../mozbase/mozpower/mozpower/powerbase.py | 2 +- .../mozpower/tests/test_intelpowergadget.py | 8 +- .../mozprocess/mozprocess/processhandler.py | 16 +- testing/mozbase/mozprocess/mozprocess/qijo.py | 4 +- .../mozprocess/mozprocess/winprocess.py | 2 +- .../mozbase/mozprocess/tests/proclaunch.py | 2 +- .../mozbase/mozprocess/tests/test_output.py | 2 +- .../mozbase/mozprofile/mozprofile/addons.py | 2 +- testing/mozbase/mozprofile/mozprofile/cli.py | 2 +- .../mozprofile/mozprofile/permissions.py | 8 +- .../mozbase/mozprofile/mozprofile/prefs.py | 2 +- .../mozbase/mozprofile/mozprofile/profile.py | 14 +- .../mozbase/mozprofile/tests/addon_stubs.py | 2 +- .../mozprofile/tests/test_preferences.py | 4 +- .../mozproxy/mozproxy/backends/base.py | 2 +- .../mozproxy/backends/mitm/android.py | 2 +- .../mozproxy/backends/mitm/desktop.py | 2 +- .../mitm/scripts/alt-serverplayback.py | 4 +- .../mitm/scripts/alternate-server-replay.py | 6 +- .../mitm/scripts/inject-deterministic.py | 20 +- testing/mozbase/mozproxy/mozproxy/utils.py | 4 +- .../mozproxy/tests/test_command_line.py | 2 +- .../mozrunner/mozrunner/application.py | 12 +- .../mozrunner/mozrunner/base/browser.py | 4 +- .../mozrunner/mozrunner/base/device.py | 10 +- .../mozrunner/mozrunner/base/runner.py | 4 +- .../mozrunner/devices/android_device.py | 10 +- .../mozrunner/mozrunner/devices/base.py | 4 +- .../mozrunner/mozrunner/devices/emulator.py | 4 +- .../mozrunner/devices/emulator_battery.py | 2 +- .../mozrunner/devices/emulator_geo.py | 2 +- .../mozrunner/devices/emulator_screen.py | 2 +- testing/mozbase/mozrunner/tests/conftest.py | 4 +- testing/mozbase/mozrunner/tests/test_crash.py | 2 +- testing/mozbase/mozserve/mozserve/servers.py | 14 +- .../mozsystemmonitor/resourcemonitor.py | 4 +- testing/mozbase/moztest/moztest/resolve.py | 8 +- testing/mozbase/moztest/moztest/results.py | 4 +- testing/mozbase/moztest/tests/test_resolve.py | 2 +- .../mozversion/mozversion/mozversion.py | 2 +- .../marionette/windows_taskcluster_config.py | 10 +- testing/mozharness/configs/openh264/win32.py | 24 +- .../configs/openh264/win64-aarch64.py | 24 +- testing/mozharness/configs/openh264/win64.py | 24 +- .../configs/unittests/win_unittest.py | 10 +- .../prod_config_windows_taskcluster.py | 10 +- testing/mozharness/mozharness/base/config.py | 2 +- .../mozharness/mozharness/base/diskutils.py | 4 +- testing/mozharness/mozharness/base/log.py | 4 +- .../mozharness/mozharness/base/parallel.py | 2 +- testing/mozharness/mozharness/base/python.py | 40 +-- testing/mozharness/mozharness/base/script.py | 38 +- .../mozharness/mozharness/base/transfer.py | 2 +- .../mozharness/mozharness/base/vcs/vcsbase.py | 2 +- .../mozharness/lib/python/authentication.py | 2 +- .../mozharness/mozilla/automation.py | 2 +- .../mozharness/mozilla/bouncer/submitter.py | 2 +- .../mozharness/mozilla/building/buildbase.py | 12 +- .../mozharness/mozilla/firefox/autoconfig.py | 2 +- .../mozharness/mozilla/l10n/locales.py | 2 +- .../mozharness/mozharness/mozilla/mozbase.py | 6 +- .../mozharness/mozilla/repo_manipulation.py | 6 +- .../mozharness/mozharness/mozilla/secrets.py | 6 +- .../mozharness/mozilla/testing/android.py | 4 +- .../mozilla/testing/codecoverage.py | 14 +- .../mozilla/testing/per_test_base.py | 4 +- .../mozharness/mozilla/testing/raptor.py | 10 +- .../mozharness/mozilla/testing/talos.py | 4 +- .../mozharness/mozilla/testing/testbase.py | 8 +- .../mozharness/mozharness/mozilla/tooltool.py | 2 +- .../scripts/android_emulator_pgo.py | 2 +- .../scripts/android_emulator_unittest.py | 6 +- .../scripts/android_hardware_unittest.py | 6 +- testing/mozharness/scripts/android_wrench.py | 2 +- testing/mozharness/scripts/awsy_script.py | 2 +- testing/mozharness/scripts/configtest.py | 2 +- .../mozharness/scripts/desktop_unittest.py | 30 +- .../mozharness/scripts/firefox_ui_tests.py | 8 +- .../mozharness/scripts/fx_desktop_build.py | 2 +- testing/mozharness/scripts/marionette.py | 16 +- testing/mozharness/scripts/openh264_build.py | 20 +- .../scripts/release/bouncer_check.py | 8 +- .../scripts/release/generate-checksums.py | 34 +- .../release/update-verify-config-creator.py | 12 +- testing/mozharness/scripts/repackage.py | 2 +- .../scripts/telemetry/telemetry_client.py | 8 +- .../mozharness/scripts/web_platform_tests.py | 8 +- .../mozharness/test/test_base_diskutils.py | 2 +- .../test/test_mozilla_building_buildbase.py | 4 +- testing/parse_reftest.py | 2 +- .../support-scripts/browsertime_benchmark.py | 10 +- .../support-scripts/browsertime_pageload.py | 2 +- .../support-scripts/network_bench.py | 6 +- testing/raptor/logger/logger.py | 16 +- testing/raptor/mach_commands.py | 6 +- testing/raptor/raptor/benchmark.py | 4 +- testing/raptor/raptor/browsertime/android.py | 2 +- testing/raptor/raptor/browsertime/base.py | 22 +- testing/raptor/raptor/browsertime/desktop.py | 2 +- testing/raptor/raptor/chrome_trace.py | 6 +- testing/raptor/raptor/filters.py | 2 +- testing/raptor/raptor/gecko_profile.py | 6 +- testing/raptor/raptor/output.py | 16 +- testing/raptor/raptor/outputhandler.py | 2 +- testing/raptor/raptor/performance_tuning.py | 24 +- testing/raptor/raptor/perftest.py | 32 +- testing/raptor/raptor/raptor.py | 2 +- testing/raptor/raptor/raptor_profiling.py | 2 +- testing/raptor/raptor/results.py | 12 +- testing/raptor/test/conftest.py | 6 +- testing/raptor/test/test_raptor.py | 2 +- testing/raptor/test/test_utils.py | 2 +- testing/remotecppunittests.py | 4 +- testing/runcppunittests.py | 2 +- testing/skipfails.py | 18 +- testing/talos/talos/allowlist.py | 4 +- testing/talos/talos/cmanager.py | 2 +- testing/talos/talos/cmanager_base.py | 2 +- testing/talos/talos/config.py | 2 +- testing/talos/talos/ffsetup.py | 6 +- testing/talos/talos/filter.py | 2 +- testing/talos/talos/gecko_profile.py | 26 +- testing/talos/talos/heavy.py | 2 +- testing/talos/talos/mainthreadio.py | 2 +- testing/talos/talos/output.py | 2 +- testing/talos/talos/results.py | 10 +- testing/talos/talos/talos_process.py | 26 +- testing/talos/talos/test.py | 2 +- testing/talos/talos/ttest.py | 2 +- testing/talos/talos/unittests/conftest.py | 2 +- testing/talos/talos/unittests/test_config.py | 8 +- testing/talos/talos/unittests/test_test.py | 10 +- testing/talos/talos/utils.py | 2 +- testing/talos/talos/xtalos/etlparser.py | 8 +- testing/talos/talos/xtalos/xperf_analyzer.py | 57 ++- testing/talos/talos/xtalos/xtalos.py | 2 +- testing/talos/talos_from_code.py | 2 +- testing/test/test_skipfails.py | 48 +-- testing/testinfo.py | 18 +- testing/tools/mach_test_package_initialize.py | 2 +- testing/tps/tps/cli.py | 2 +- testing/tps/tps/firefoxrunner.py | 4 +- testing/tps/tps/phase.py | 4 +- testing/tps/tps/testrunner.py | 14 +- testing/web-platform/mach_commands_base.py | 2 +- .../mach_test_package_commands.py | 2 +- testing/web-platform/manifestupdate.py | 2 +- testing/web-platform/metamerge.py | 2 +- testing/web-platform/metasummary.py | 6 +- .../classic/addon_install/__init__.py | 4 +- .../classic/addon_uninstall/__init__.py | 4 +- .../element_send_keys/scroll_into_view.py | 4 +- .../classic/element_send_keys/send_keys.py | 4 +- .../execute_async_script/execute_async.py | 8 +- .../webdriver/classic/new_session/conftest.py | 2 +- .../classic/take_full_screenshot/iframe.py | 10 +- .../take_full_screenshot/screenshot.py | 4 +- testing/web-platform/unittestrunner.py | 2 +- testing/web-platform/update/github.py | 8 +- testing/web-platform/update/tree.py | 2 +- testing/web-platform/update/upstream.py | 10 +- testing/web-platform/vcs.py | 4 +- testing/webcompat/client.py | 2 +- .../tests/test_1836872_docs_google_com.py | 4 +- testing/webcompat/mach_commands.py | 8 +- testing/webcompat/runner.py | 4 +- testing/xpcshell/remotexpcshelltests.py | 4 +- testing/xpcshell/runxpcshelltests.py | 32 +- .../components/crashes/gen_CrashManager.py | 2 +- .../webidl-api/GenerateWebIDLBindings.py | 4 +- .../build_scripts/glean_parser_ext/cpp.py | 4 +- .../build_scripts/glean_parser_ext/rust.py | 8 +- .../glean/build_scripts/mach_commands.py | 4 +- .../glean/tests/pytest/expect_helper.py | 2 +- .../tests/pytest/test_no_expired_metrics.py | 2 +- .../pytest/test_no_metadata_use_ohttp.py | 2 +- .../ml/tools/convert_to_external_data.py | 2 +- .../generate/generate_feature_manifest.py | 8 +- .../worker/GeneratePromiseWorkerScript.py | 2 +- .../extract_rfp_targets.py | 4 +- .../build_scripts/gen_histogram_data.py | 4 +- .../build_scripts/gen_scalar_data.py | 4 +- .../build_scripts/gen_userinteraction_data.py | 2 +- .../telemetry/build_scripts/mach_commands.py | 5 +- .../build_scripts/mozparsers/parse_events.py | 6 +- .../mozparsers/parse_histograms.py | 22 +- .../build_scripts/mozparsers/parse_scalars.py | 54 ++- .../mozparsers/parse_user_interactions.py | 35 +- .../mozparsers/shared_telemetry_utils.py | 6 +- .../telemetry/build_scripts/setup.py | 2 +- .../tests/integration/tests/conftest.py | 10 +- .../test_search_counts_across_sessions.py | 8 +- .../telemetry_harness/fog_ping_filters.py | 2 +- .../telemetry_harness/fog_ping_server.py | 2 +- .../harness/telemetry_harness/fog_testcase.py | 2 +- .../harness/telemetry_harness/ping_filters.py | 2 +- .../harness/telemetry_harness/ping_server.py | 6 +- .../harness/telemetry_harness/runner.py | 2 +- .../harness/telemetry_harness/testcase.py | 10 +- .../client/test_fog_deletion_request_ping.py | 8 +- .../tests/client/test_unicode_encoding.py | 7 +- .../unit/test_ping_server_received_ping.py | 4 +- .../tests/python/test_no_expired_probes.py | 2 +- .../bergamot-translator/build-bergamot.py | 4 +- .../bergamot-translator/upload-bergamot.py | 4 +- .../uniffi-bindgen-gecko-js/mach_commands.py | 2 +- .../neterror/gen_aboutneterror_codes.py | 4 +- toolkit/content/widgets/mach_commands.py | 26 +- .../generate_crash_reporter_sources.py | 4 +- toolkit/crashreporter/tools/symbolstore.py | 2 +- .../crashreporter/tools/unit-symbolstore.py | 10 +- toolkit/crashreporter/tools/upload_symbols.py | 40 +-- toolkit/library/gen_buildid.py | 10 +- toolkit/library/libxul.so-gdb.py | 2 +- .../mozglue/gen_dll_blocklist_defs.py | 8 +- .../xre/test/marionette/gen_win32k_tests.py | 22 +- tools/browsertime/mach_commands.py | 6 +- tools/compare-locales/mach_commands.py | 2 +- .../system-symbols/mac/PackageSymbolDumper.py | 30 +- .../system-symbols/mac/get_update_packages.py | 14 +- .../system-symbols/mac/list-packages.py | 4 +- tools/fuzzing/smoke/conftest.py | 2 +- tools/lint/android/lints.py | 26 +- tools/lint/clang-format/__init__.py | 6 +- tools/lint/clippy/__init__.py | 8 +- tools/lint/cpp/mingw-capitalization.py | 2 +- tools/lint/fluent-lint/__init__.py | 2 +- tools/lint/hooks.py | 2 +- tools/lint/hooks_clang_format.py | 2 +- tools/lint/hooks_js_format.py | 2 +- tools/lint/ignorefile/__init__.py | 2 +- tools/lint/libpref/__init__.py | 2 +- tools/lint/license/__init__.py | 8 +- tools/lint/mach_commands.py | 2 +- tools/lint/perfdocs/doc_helpers.py | 2 +- tools/lint/perfdocs/framework_gatherers.py | 6 +- tools/lint/perfdocs/gatherer.py | 2 +- tools/lint/perfdocs/generator.py | 8 +- tools/lint/perfdocs/logger.py | 2 +- tools/lint/perfdocs/utils.py | 6 +- tools/lint/perfdocs/verifier.py | 28 +- tools/lint/python/black.py | 6 +- tools/lint/python/ruff.py | 2 +- tools/lint/rust/__init__.py | 4 +- tools/lint/shell/__init__.py | 6 +- tools/lint/spell/__init__.py | 6 +- tools/lint/test-manifest-alpha/__init__.py | 2 +- tools/lint/test-manifest-toml/__init__.py | 2 +- tools/lint/test/conftest.py | 2 +- tools/lint/test/test_perfdocs.py | 8 +- tools/lint/updatebot/validate_yaml.py | 2 +- tools/lint/yamllint_/__init__.py | 4 +- tools/moztreedocs/__init__.py | 8 +- tools/moztreedocs/mach_commands.py | 10 +- tools/moztreedocs/upload.py | 2 +- tools/rb/find_leakers.py | 8 +- tools/signing/macos/mach_commands.py | 2 +- tools/tryselect/cli.py | 4 +- tools/tryselect/mach_commands.py | 18 +- tools/tryselect/preset.py | 2 +- tools/tryselect/push.py | 11 +- tools/tryselect/selectors/again.py | 11 +- tools/tryselect/selectors/auto.py | 10 +- tools/tryselect/selectors/chooser/__init__.py | 4 +- tools/tryselect/selectors/chooser/app.py | 6 +- tools/tryselect/selectors/coverage.py | 24 +- tools/tryselect/selectors/fuzzy.py | 10 +- tools/tryselect/selectors/perf.py | 9 +- tools/tryselect/selectors/release.py | 14 +- tools/tryselect/selectors/scriptworker.py | 6 +- tools/tryselect/selectors/syntax.py | 2 +- tools/tryselect/task_config.py | 34 +- tools/tryselect/tasks.py | 2 +- tools/tryselect/test/conftest.py | 2 +- tools/tryselect/test/test_again.py | 4 +- .../test/test_mozharness_integration.py | 6 +- tools/tryselect/util/fzf.py | 18 +- tools/tryselect/util/manage_estimates.py | 10 +- .../make_incremental_zucchini.py | 2 +- .../release/compare-directories.py | 30 +- .../release/replace-updater-certs.py | 10 +- tools/update-verify/scripts/async_download.py | 2 +- tools/use-moz-src/mach_commands.py | 6 +- xpcom/base/ErrorList.py | 20 +- xpcom/components/gen_static_components.py | 72 ++-- xpcom/ds/tools/make_dafsa.py | 2 +- xpcom/ds/tools/perfecthash.py | 4 +- xpcom/idl-parser/xpidl/rust.py | 2 +- xpcom/idl-parser/xpidl/xpidl.py | 44 +-- xpcom/reflect/xptcall/md/win32/preprocess.py | 2 +- xpcom/reflect/xptinfo/xptcodegen.py | 2 +- 779 files changed, 2935 insertions(+), 4119 deletions(-) diff --git a/accessible/base/RelationTypeGen.py b/accessible/base/RelationTypeGen.py index 8d9a0f91bfa7..335e45b5cb2b 100644 --- a/accessible/base/RelationTypeGen.py +++ b/accessible/base/RelationTypeGen.py @@ -8,7 +8,7 @@ import re def generate(relH, relIdl): - input = open(relIdl, "rt").read() + input = open(relIdl).read() relations = re.findall( r"const unsigned long RELATION_([A-Z_]+) = ([x0-9a-f]+);", input ) diff --git a/accessible/base/RoleHGen.py b/accessible/base/RoleHGen.py index 374d2f66a90a..9ba245fc423b 100644 --- a/accessible/base/RoleHGen.py +++ b/accessible/base/RoleHGen.py @@ -8,7 +8,7 @@ import re def generate(roleH, roleIdl): - input = open(roleIdl, "rt").read() + input = open(roleIdl).read() roles = re.findall(r"const unsigned long ROLE_([A-Z_]+) = (\d+);", input) roleH.write( diff --git a/browser/app/macversion.py b/browser/app/macversion.py index f6f54df6df5c..c48101c8988d 100644 --- a/browser/app/macversion.py +++ b/browser/app/macversion.py @@ -27,9 +27,7 @@ if not options.version: # builds), but also so that newly-built older versions (e.g. beta build) aren't # considered "newer" than previously-built newer versions (e.g. a trunk nightly) -define, MOZ_BUILDID, buildid = ( - open(options.buildid, "r", encoding="utf-8").read().split() -) +define, MOZ_BUILDID, buildid = open(options.buildid, encoding="utf-8").read().split() # extract only the major version (i.e. "14" from "14.0b1") majorVersion = re.match(r"^(\d+)[^\d].*", options.version).group(1) diff --git a/browser/components/sessionstore/test/marionette/session_store_test_case.py b/browser/components/sessionstore/test/marionette/session_store_test_case.py index fea7eed7de52..36ae675bab5d 100644 --- a/browser/components/sessionstore/test/marionette/session_store_test_case.py +++ b/browser/components/sessionstore/test/marionette/session_store_test_case.py @@ -10,7 +10,7 @@ from marionette_harness import MarionetteTestCase, WindowManagerMixin def inline(doc): - return "data:text/html;charset=utf-8,{}".format(quote(doc)) + return f"data:text/html;charset=utf-8,{quote(doc)}" # Each list element represents a window of tabs loaded at @@ -441,9 +441,7 @@ class SessionStoreTestCase(WindowManagerMixin, MarionetteTestCase): self.assertEqual( current_windows_set, self.all_windows, - msg="Not all requested windows have been opened. Expected {}, got {}.".format( - self.all_windows, current_windows_set - ), + msg=f"Not all requested windows have been opened. Expected {self.all_windows}, got {current_windows_set}.", ) self.marionette.quit(callback=lambda: self.simulate_os_shutdown()) diff --git a/browser/components/sessionstore/test/marionette/test_persist_closed_tabs_restore_manually.py b/browser/components/sessionstore/test/marionette/test_persist_closed_tabs_restore_manually.py index 9aa2a3871f7b..bce2ac1b3609 100644 --- a/browser/components/sessionstore/test/marionette/test_persist_closed_tabs_restore_manually.py +++ b/browser/components/sessionstore/test/marionette/test_persist_closed_tabs_restore_manually.py @@ -13,9 +13,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestSessionRestoreClosedTabs(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_loading_tab.py b/browser/components/sessionstore/test/marionette/test_restore_loading_tab.py index f053081b0216..0070b89bbc60 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_loading_tab.py +++ b/browser/components/sessionstore/test/marionette/test_restore_loading_tab.py @@ -8,7 +8,7 @@ from marionette_harness import MarionetteTestCase, WindowManagerMixin def inline(doc): - return "data:text/html;charset=utf-8,{}".format(quote(doc)) + return f"data:text/html;charset=utf-8,{quote(doc)}" class TestRestoreLoadingPage(WindowManagerMixin, MarionetteTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_manually.py b/browser/components/sessionstore/test/marionette/test_restore_manually.py index e3c0a83607a7..7e69feff0087 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_manually.py +++ b/browser/components/sessionstore/test/marionette/test_restore_manually.py @@ -12,9 +12,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestSessionRestoreManually(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_manually_with_pinned_tabs.py b/browser/components/sessionstore/test/marionette/test_restore_manually_with_pinned_tabs.py index fa00c25a4c74..80b7393b2c83 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_manually_with_pinned_tabs.py +++ b/browser/components/sessionstore/test/marionette/test_restore_manually_with_pinned_tabs.py @@ -14,7 +14,7 @@ from session_store_test_case import SessionStoreTestCase def inline(doc): - return "data:text/html;charset=utf-8,{}".format(quote(doc)) + return f"data:text/html;charset=utf-8,{quote(doc)}" class TestSessionRestoreWithPinnedTabs(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_manually_with_tab_groups.py b/browser/components/sessionstore/test/marionette/test_restore_manually_with_tab_groups.py index 9312909a4910..29b8ab50b0d7 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_manually_with_tab_groups.py +++ b/browser/components/sessionstore/test/marionette/test_restore_manually_with_tab_groups.py @@ -14,7 +14,7 @@ from session_store_test_case import SessionStoreTestCase def inline(doc): - return "data:text/html;charset=utf-8,{}".format(quote(doc)) + return f"data:text/html;charset=utf-8,{quote(doc)}" class TestSessionRestoreWithTabGroups(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_sidebar.py b/browser/components/sessionstore/test/marionette/test_restore_sidebar.py index 63998da2f242..79fac800c622 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_sidebar.py +++ b/browser/components/sessionstore/test/marionette/test_restore_sidebar.py @@ -12,9 +12,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestSessionRestore(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_sidebar_automatic.py b/browser/components/sessionstore/test/marionette/test_restore_sidebar_automatic.py index 58a9b93b4742..0d1722136ec6 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_sidebar_automatic.py +++ b/browser/components/sessionstore/test/marionette/test_restore_sidebar_automatic.py @@ -12,9 +12,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestSessionRestore(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_restore_windows_after_restart_and_quit.py b/browser/components/sessionstore/test/marionette/test_restore_windows_after_restart_and_quit.py index 3dd9dc1bf323..948a855e27af 100644 --- a/browser/components/sessionstore/test/marionette/test_restore_windows_after_restart_and_quit.py +++ b/browser/components/sessionstore/test/marionette/test_restore_windows_after_restart_and_quit.py @@ -12,9 +12,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestSessionStoreEnabledAllWindows(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_taskbartab_restore.py b/browser/components/sessionstore/test/marionette/test_taskbartab_restore.py index 393f55392d95..9fff182fe319 100644 --- a/browser/components/sessionstore/test/marionette/test_taskbartab_restore.py +++ b/browser/components/sessionstore/test/marionette/test_taskbartab_restore.py @@ -14,9 +14,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestManualRestoreWithTaskbarTabs(SessionStoreTestCase): diff --git a/browser/components/sessionstore/test/marionette/test_taskbartab_sessionstate.py b/browser/components/sessionstore/test/marionette/test_taskbartab_sessionstate.py index 2cfe4ee6a848..0f4b84f58c23 100644 --- a/browser/components/sessionstore/test/marionette/test_taskbartab_sessionstate.py +++ b/browser/components/sessionstore/test/marionette/test_taskbartab_sessionstate.py @@ -12,9 +12,7 @@ from session_store_test_case import SessionStoreTestCase def inline(title): - return "data:text/html;charset=utf-8,{}".format( - title - ) + return f"data:text/html;charset=utf-8,{title}" class TestTaskbarTabSessionState(SessionStoreTestCase): diff --git a/browser/components/storybook/mach_commands.py b/browser/components/storybook/mach_commands.py index 36a82aececb1..3bd4421d3c22 100644 --- a/browser/components/storybook/mach_commands.py +++ b/browser/components/storybook/mach_commands.py @@ -97,7 +97,7 @@ def build_storybook_manifest(command_context): config_environment = command_context.config_environment storybook_chrome_map_path = "browser/components/storybook/.storybook/chrome-map.js" chrome_map_path = mozpath.join(config_environment.topobjdir, "chrome-map.json") - with open(chrome_map_path, "r") as chrome_map_f: + with open(chrome_map_path) as chrome_map_f: with open(storybook_chrome_map_path, "w") as storybook_chrome_map_f: storybook_chrome_map_f.write("module.exports = ") storybook_chrome_map_f.write(chrome_map_f.read()) diff --git a/build/build-clang/build-clang.py b/build/build-clang/build-clang.py index a0d967b02e3a..e1801ee245f1 100755 --- a/build/build-clang/build-clang.py +++ b/build/build-clang/build-clang.py @@ -134,7 +134,7 @@ def updated_env(env): def build_tar_package(name, base, directory): name = os.path.realpath(name) - print("tarring {} from {}/{}".format(name, base, directory), file=sys.stderr) + print(f"tarring {name} from {base}/{directory}", file=sys.stderr) assert name.endswith(".tar.zst") cctx = zstandard.ZstdCompressor() @@ -559,16 +559,14 @@ def main(): del config[key] elif type(old_value) is not type(value): raise Exception( - "{} is overriding `{}` with a value of the wrong type".format( - c.name, key - ) + f"{c.name} is overriding `{key}` with a value of the wrong type" ) elif isinstance(old_value, list): for v in value: if v not in old_value: old_value.append(v) elif isinstance(old_value, dict): - raise Exception("{} is setting `{}` to a dict?".format(c.name, key)) + raise Exception(f"{c.name} is setting `{key}` to a dict?") else: config[key] = value diff --git a/build/clang-plugin/import_mozilla_checks.py b/build/clang-plugin/import_mozilla_checks.py index d573dafcf1bf..315ea2e85d38 100755 --- a/build/clang-plugin/import_mozilla_checks.py +++ b/build/clang-plugin/import_mozilla_checks.py @@ -77,7 +77,7 @@ clang_target_link_libraries(clangTidyMozillaModule def add_moz_module(cmake_path): - with open(cmake_path, "r") as f: + with open(cmake_path) as f: lines = f.readlines() f.close() @@ -89,7 +89,7 @@ def add_moz_module(cmake_path): for line in lines: f.write(line) except ValueError: - raise Exception("Unable to find ALL_CLANG_TIDY_CHECKS in {}".format(cmake_path)) + raise Exception(f"Unable to find ALL_CLANG_TIDY_CHECKS in {cmake_path}") def write_third_party_paths(mozilla_path, module_path): diff --git a/build/gn_processor.py b/build/gn_processor.py index d77effc6c108..423b5a4d9a1c 100644 --- a/build/gn_processor.py +++ b/build/gn_processor.py @@ -30,7 +30,7 @@ generated_header = """ """ -class MozbuildWriter(object): +class MozbuildWriter: def __init__(self, fh): self._fh = fh self.indent = "" @@ -745,7 +745,7 @@ def generate_gn_config( if preprocessor: preprocessor.main(gn_config_file) - with open(gn_config_file, "r") as fh: + with open(gn_config_file) as fh: gn_out = json.load(fh) gn_out = filter_gn_config( resolved_tempdir, gn_out, sandbox_variables, input_variables, gn_target @@ -772,7 +772,7 @@ def main(): if not gn_binary: raise Exception("The GN program must be present to generate GN configs.") - with open(args.config, "r") as fh: + with open(args.config) as fh: config = json.load(fh) topsrcdir = Path(__file__).parent.parent.resolve() diff --git a/build/mach_initialize.py b/build/mach_initialize.py index 9cc76bcab63d..dba543279eb2 100644 --- a/build/mach_initialize.py +++ b/build/mach_initialize.py @@ -476,9 +476,7 @@ def _create_state_dir(): if state_dir: if not os.path.exists(state_dir): print( - "Creating global state directory from environment variable: {}".format( - state_dir - ) + f"Creating global state directory from environment variable: {state_dir}" ) else: state_dir = os.path.expanduser("~/.mozbuild") @@ -486,7 +484,7 @@ def _create_state_dir(): if not os.environ.get("MOZ_AUTOMATION"): print(STATE_DIR_FIRST_RUN.format(state_dir)) - print("Creating default state directory: {}".format(state_dir)) + print(f"Creating default state directory: {state_dir}") os.makedirs(state_dir, mode=0o770, exist_ok=True) return state_dir diff --git a/build/midl.py b/build/midl.py index 0770ab820876..ebfb2de51d14 100644 --- a/build/midl.py +++ b/build/midl.py @@ -114,7 +114,7 @@ def preprocess(base, input, flags): subprocess.run(command, stdout=open(preprocessed, "wb"), check=True) # Read the resulting file, and search for imports, that we'll want to # preprocess as well. - with open(preprocessed, "r") as fh: + with open(preprocessed) as fh: for line in fh: if not line.startswith("import"): continue @@ -211,7 +211,7 @@ def merge_dlldata(out, *inputs): # If for some reason, we don't get lines that are entirely different # from each other, we have some unexpected input. print( - "Error while merging dlldata. Last lines read: {}".format(lines), + f"Error while merging dlldata. Last lines read: {lines}", file=sys.stderr, ) return 1 diff --git a/build/pgo/genpgocert.py b/build/pgo/genpgocert.py index e844946466f1..42c84f86c5db 100644 --- a/build/pgo/genpgocert.py +++ b/build/pgo/genpgocert.py @@ -91,7 +91,7 @@ def writeCertspecForServerLocations(fd): fd.write( "issuer:printableString/CN=Temporary Certificate Authority/O=Mozilla Testing/OU=Profile Guided Optimization\n" # NOQA: E501 ) - fd.write("subject:{}\n".format(SAN[0])) + fd.write(f"subject:{SAN[0]}\n") fd.write("extension:subjectAlternativeName:{}\n".format(",".join(SAN))) @@ -100,7 +100,7 @@ def constructCertDatabase(build, srcDir): certutil = build.get_binary_path(what="certutil") pk12util = build.get_binary_path(what="pk12util") except BinaryNotFoundException as e: - print("{}\n\n{}\n".format(e, e.help())) + print(f"{e}\n\n{e.help()}\n") return 1 openssl = shutil.which("openssl") pycert = os.path.join(build.topsrcdir, "security", "manager", "tools", "pycert.py") @@ -124,9 +124,7 @@ def constructCertDatabase(build, srcDir): # Write a certspec for the "server-locations.txt" file to that temporary directory pgoserver_certspec = os.path.join(pemfolder, "pgoserver.certspec") if os.path.exists(pgoserver_certspec): - raise Exception( - "{} already exists, which isn't allowed".format(pgoserver_certspec) - ) + raise Exception(f"{pgoserver_certspec} already exists, which isn't allowed") with open(pgoserver_certspec, "w") as fd: writeCertspecForServerLocations(fd) @@ -134,11 +132,11 @@ def constructCertDatabase(build, srcDir): for root, dirs, files in os.walk(pemfolder): for certspec in [i for i in files if i.endswith(".certspec")]: name = certspec.split(".certspec")[0] - pem = os.path.join(pemfolder, "{}.cert.pem".format(name)) + pem = os.path.join(pemfolder, f"{name}.cert.pem") - print("Generating public certificate {} (pem={})".format(name, pem)) + print(f"Generating public certificate {name} (pem={pem})") - with open(os.path.join(root, certspec), "r") as certspec_file: + with open(os.path.join(root, certspec)) as certspec_file: certspec_data = certspec_file.read() with open(pem, "w") as pem_file: status = runUtil( @@ -172,14 +170,14 @@ def constructCertDatabase(build, srcDir): key_type = parts[1] if key_type not in ["ca", "client", "server"]: raise Exception( - "{}: keyspec filenames must be of the form XXX.client.keyspec " - "or XXX.ca.keyspec (key_type={})".format(keyspec, key_type) + f"{keyspec}: keyspec filenames must be of the form XXX.client.keyspec " + f"or XXX.ca.keyspec (key_type={key_type})" ) - key_pem = os.path.join(pemfolder, "{}.key.pem".format(name)) + key_pem = os.path.join(pemfolder, f"{name}.key.pem") - print("Generating private key {} (pem={})".format(name, key_pem)) + print(f"Generating private key {name} (pem={key_pem})") - with open(os.path.join(root, keyspec), "r") as keyspec_file: + with open(os.path.join(root, keyspec)) as keyspec_file: keyspec_data = keyspec_file.read() with open(key_pem, "w") as pem_file: status = runUtil( @@ -188,17 +186,15 @@ def constructCertDatabase(build, srcDir): if status: return status - cert_pem = os.path.join(pemfolder, "{}.cert.pem".format(name)) + cert_pem = os.path.join(pemfolder, f"{name}.cert.pem") if not os.path.exists(cert_pem): raise Exception( - "There has to be a corresponding certificate named {} for " - "the keyspec {}".format(cert_pem, keyspec) + f"There has to be a corresponding certificate named {cert_pem} for " + f"the keyspec {keyspec}" ) - p12 = os.path.join(pemfolder, "{}.key.p12".format(name)) - print( - "Converting private key {} to PKCS12 (p12={})".format(key_pem, p12) - ) + p12 = os.path.join(pemfolder, f"{name}.key.p12") + print(f"Converting private key {key_pem} to PKCS12 (p12={p12})") status = runUtil( openssl, [ @@ -219,7 +215,7 @@ def constructCertDatabase(build, srcDir): if status: return status - print("Importing private key {} to database".format(key_pem)) + print(f"Importing private key {key_pem} to database") status = runUtil( pk12util, ["-i", p12, "-d", srcDir, "-w", pwfile.name, "-k", pwfile.name], @@ -228,16 +224,14 @@ def constructCertDatabase(build, srcDir): return status if key_type == "ca": - shutil.copyfile( - cert_pem, os.path.join(srcDir, "{}.ca".format(name)) - ) + shutil.copyfile(cert_pem, os.path.join(srcDir, f"{name}.ca")) elif key_type == "client": - shutil.copyfile(p12, os.path.join(srcDir, "{}.client".format(name))) + shutil.copyfile(p12, os.path.join(srcDir, f"{name}.client")) elif key_type == "server": pass # Nothing to do for server keys else: raise Exception( - "State error: Unknown keyspec key_type: {}".format(key_type) + f"State error: Unknown keyspec key_type: {key_type}" ) return 0 diff --git a/build/pgo/profileserver.py b/build/pgo/profileserver.py index c59efbdc5382..6017810c873f 100755 --- a/build/pgo/profileserver.py +++ b/build/pgo/profileserver.py @@ -71,7 +71,7 @@ if __name__ == "__main__": try: binary = build.get_binary_path(where="staged-package") except BinaryNotFoundException as e: - print("{}\n\n{}\n".format(e, e.help())) + print(f"{e}\n\n{e.help()}\n") sys.exit(1) binary = os.path.normpath(os.path.abspath(binary)) @@ -104,7 +104,7 @@ if __name__ == "__main__": with TemporaryDirectory() as profilePath: # TODO: refactor this into mozprofile profile_data_dir = os.path.join(build.topsrcdir, "testing", "profiles") - with open(os.path.join(profile_data_dir, "profiles.json"), "r") as fh: + with open(os.path.join(profile_data_dir, "profiles.json")) as fh: base_profiles = json.load(fh)["profileserver"] prefpaths = [ @@ -215,7 +215,7 @@ if __name__ == "__main__": with open(log) as f: for line in f.readlines(): if "LLVM Profile Error" in line: - print("Error [{}]: '{}'".format(log, line.strip())) + print(f"Error [{log}]: '{line.strip()}'") should_err = True if should_err: diff --git a/build/unix/elfhack/inject/copy_source.py b/build/unix/elfhack/inject/copy_source.py index 02b4f6237e27..1de1cb8704ca 100644 --- a/build/unix/elfhack/inject/copy_source.py +++ b/build/unix/elfhack/inject/copy_source.py @@ -6,5 +6,5 @@ def copy(out_file, in_path): - with open(in_path, "r") as fh: + with open(in_path) as fh: out_file.write(fh.read()) diff --git a/build/upload_generated_sources.py b/build/upload_generated_sources.py index d635ac7c2d3c..aff78b1f311c 100644 --- a/build/upload_generated_sources.py +++ b/build/upload_generated_sources.py @@ -77,14 +77,10 @@ def upload_worker(queue, event, bucket, session_args): "ContentEncoding": "gzip", "ContentType": "text/plain", } - log.info( - 'Uploading "{}" ({} bytes)'.format(pathname, len(compressed.getvalue())) - ) + log.info(f'Uploading "{pathname}" ({len(compressed.getvalue())} bytes)') with timed() as elapsed: s3.upload_fileobj(compressed, bucket, pathname, ExtraArgs=extra_args) - log.info( - 'Finished uploading "{}" in {:0.3f}s'.format(pathname, elapsed()) - ) + log.info(f'Finished uploading "{pathname}" in {elapsed():0.3f}s') queue.task_done() except Exception: log.exception("Thread encountered exception:") @@ -104,9 +100,7 @@ def do_work(artifact, region, bucket): secrets_url = "http://taskcluster/secrets/v1/secret/project/releng/gecko/build/level-{}/gecko-generated-sources-upload".format( # noqa level ) - log.info( - 'Using AWS credentials from the secrets service: "{}"'.format(secrets_url) - ) + log.info(f'Using AWS credentials from the secrets service: "{secrets_url}"') res = session.get(secrets_url) res.raise_for_status() secret = res.json() @@ -118,19 +112,17 @@ def do_work(artifact, region, bucket): log.info("Trying to use your AWS credentials..") # First, fetch the artifact containing the sources. - log.info('Fetching generated sources artifact: "{}"'.format(artifact)) + log.info(f'Fetching generated sources artifact: "{artifact}"') with timed() as elapsed: res = session.get(artifact) log.info( - "Fetch HTTP status: {}, {} bytes downloaded in {:0.3f}s".format( - res.status_code, len(res.content), elapsed() - ) + f"Fetch HTTP status: {res.status_code}, {len(res.content)} bytes downloaded in {elapsed():0.3f}s" ) res.raise_for_status() # Create a queue and worker threads for uploading. q = Queue() event = Event() - log.info("Creating {} worker threads".format(NUM_WORKER_THREADS)) + log.info(f"Creating {NUM_WORKER_THREADS} worker threads") for i in range(NUM_WORKER_THREADS): t = Thread(target=upload_worker, args=(q, event, bucket, session_args)) t.daemon = True @@ -140,7 +132,7 @@ def do_work(artifact, region, bucket): for entry in tar: if event.is_set(): break - log.info('Queueing "{}"'.format(entry.name)) + log.info(f'Queueing "{entry.name}"') q.put((entry.name, tar.extractfile(entry).read())) # Wait until all uploads are finished. # We don't use q.join() here because we want to also monitor event. @@ -161,7 +153,7 @@ def main(argv): with timed() as elapsed: do_work(region=region, bucket=bucket, artifact=args.artifact) - log.info("Finished in {:.03f}s".format(elapsed())) + log.info(f"Finished in {elapsed():.03f}s") return 0 diff --git a/build/valgrind/mach_commands.py b/build/valgrind/mach_commands.py index d7180d64650b..70f535f87ea1 100644 --- a/build/valgrind/mach_commands.py +++ b/build/valgrind/mach_commands.py @@ -59,7 +59,7 @@ def valgrind_test(command_context, suppressions): profile_data_dir = os.path.join( command_context.topsrcdir, "testing", "profiles" ) - with open(os.path.join(profile_data_dir, "profiles.json"), "r") as fh: + with open(os.path.join(profile_data_dir, "profiles.json")) as fh: base_profiles = json.load(fh)["valgrind"] prefpaths = [ diff --git a/build/valgrind/output_handler.py b/build/valgrind/output_handler.py index 613f7f8c1fb8..c20fc09b2a5e 100644 --- a/build/valgrind/output_handler.py +++ b/build/valgrind/output_handler.py @@ -6,7 +6,7 @@ import logging import re -class OutputHandler(object): +class OutputHandler: """ A class for handling Valgrind output. diff --git a/build/variables.py b/build/variables.py index 5996269c03af..8b510b3ed9e8 100644 --- a/build/variables.py +++ b/build/variables.py @@ -14,7 +14,7 @@ def get_buildid(): import buildconfig path = os.path.join(buildconfig.topobjdir, "buildid.h") - _define, _MOZ_BUILDID, buildid = open(path, "r", encoding="utf-8").read().split() + _define, _MOZ_BUILDID, buildid = open(path, encoding="utf-8").read().split() return buildid diff --git a/client.py b/client.py index ea16f95627c9..e662343a76d9 100755 --- a/client.py +++ b/client.py @@ -74,7 +74,7 @@ def toggle_trailing_blank_line(depname): def get_trailing_blank_line_state(depname): - lines = open(depname, "r").readlines() + lines = open(depname).readlines() if not lines: print("unexpected short file", file=sys.stderr) return "no blank line" diff --git a/config/check_js_msg_encoding.py b/config/check_js_msg_encoding.py index 6543405f9044..bbcf4047ccb5 100644 --- a/config/check_js_msg_encoding.py +++ b/config/check_js_msg_encoding.py @@ -25,11 +25,11 @@ ignore_files = [ def log_pass(filename, text): - print("TEST-PASS | {} | {} | {}".format(scriptname, filename, text)) + print(f"TEST-PASS | {scriptname} | {filename} | {text}") def log_fail(filename, text): - print("TEST-UNEXPECTED-FAIL | {} | {} | {}".format(scriptname, filename, text)) + print(f"TEST-UNEXPECTED-FAIL | {scriptname} | {filename} | {text}") def check_single_file(filename): @@ -38,7 +38,7 @@ def check_single_file(filename): try: data.decode(expected_encoding) except Exception: - log_fail(filename, "not in {} encoding".format(expected_encoding)) + log_fail(filename, f"not in {expected_encoding} encoding") log_pass(filename, "ok") return True diff --git a/config/check_js_opcode.py b/config/check_js_opcode.py index b6a6c1f1c834..dec1c6f107fb 100644 --- a/config/check_js_opcode.py +++ b/config/check_js_opcode.py @@ -15,11 +15,11 @@ topsrcdir = os.path.dirname(os.path.dirname(__file__)) def log_pass(text): - print("TEST-PASS | {} | {}".format(scriptname, text)) + print(f"TEST-PASS | {scriptname} | {text}") def log_fail(text): - print("TEST-UNEXPECTED-FAIL | {} | {}".format(scriptname, text)) + print(f"TEST-UNEXPECTED-FAIL | {scriptname} | {text}") def check_opcode(): diff --git a/config/check_source_count.py b/config/check_source_count.py index a0a3f2c6d4f7..11ee53bc1f3d 100755 --- a/config/check_source_count.py +++ b/config/check_source_count.py @@ -30,34 +30,28 @@ for f in files: details[f] = num if count == expected_count: - print( - "TEST-PASS | check_source_count.py {0} | {1}".format( - search_string, expected_count - ) - ) + print(f"TEST-PASS | check_source_count.py {search_string} | {expected_count}") else: print( - "TEST-UNEXPECTED-FAIL | check_source_count.py {0} | ".format(search_string), + f"TEST-UNEXPECTED-FAIL | check_source_count.py {search_string} | ", end="", ) if count < expected_count: print( - "There are fewer occurrences of /{0}/ than expected. " + f"There are fewer occurrences of /{search_string}/ than expected. " "This may mean that you have removed some, but forgotten to " - "account for it {1}.".format(search_string, error_location) + f"account for it {error_location}." ) else: print( - "There are more occurrences of /{0}/ than expected. We're trying " - "to prevent an increase in the number of {1}'s, using {2} if " + f"There are more occurrences of /{search_string}/ than expected. We're trying " + f"to prevent an increase in the number of {search_string}'s, using {replacement} if " "possible. If it is unavoidable, you should update the expected " - "count {3}.".format( - search_string, search_string, replacement, error_location - ) + f"count {error_location}." ) - print("Expected: {0}; found: {1}".format(expected_count, count)) + print(f"Expected: {expected_count}; found: {count}") for k in sorted(details): - print("Found {0} occurences in {1}".format(details[k], k)) + print(f"Found {details[k]} occurences in {k}") sys.exit(-1) diff --git a/config/check_spidermonkey_style.py b/config/check_spidermonkey_style.py index 9dab5638157a..732d6b81084a 100644 --- a/config/check_spidermonkey_style.py +++ b/config/check_spidermonkey_style.py @@ -254,7 +254,7 @@ def error(filename, linenum, *lines): out("") -class FileKind(object): +class FileKind: C = 1 CPP = 2 INL_H = 3 @@ -436,7 +436,7 @@ def is_module_header(enclosing_inclname, header_inclname): return False -class Include(object): +class Include: """Important information for a single #include statement.""" def __init__(self, include_prefix, inclname, line_suffix, linenum, is_system): @@ -503,7 +503,7 @@ class Include(object): return self.include_prefix + self.quote() + self.line_suffix + "\n" -class CppBlock(object): +class CppBlock: """C preprocessor block: a whole file or a single #if/#elif/#else block. A #if/#endif block is the contents of a #if/#endif (or similar) section. @@ -620,7 +620,7 @@ class CppBlock(object): return self.start + "".join(kid.to_source() for kid in self.kids) + self.end -class OrdinaryCode(object): +class OrdinaryCode: """A list of lines of code that aren't #include/#if/#else/#endif lines.""" def __init__(self, lines=None): diff --git a/config/create_rc.py b/config/create_rc.py index 7dd0de534c59..ea290637ba88 100644 --- a/config/create_rc.py +++ b/config/create_rc.py @@ -80,7 +80,7 @@ def preprocess(path, defines): pp.context.update(defines) pp.out = io.StringIO() pp.do_filter("substitution") - pp.do_include(open(path, "r", encoding="latin1")) + pp.do_include(open(path, encoding="latin1")) pp.out.seek(0) return pp.out @@ -265,9 +265,7 @@ def generate_module_rc(binary="", rcinclude=None): overrides = {} if rcinclude: - include = "// From included resource {}\n{}".format( - rcinclude, preprocess(rcinclude, defines).read() - ) + include = f"// From included resource {rcinclude}\n{preprocess(rcinclude, defines).read()}" else: include = "" @@ -303,7 +301,7 @@ def generate_module_rc(binary="", rcinclude=None): manifest_path = os.path.join(srcdir, binary + ".manifest") if os.path.exists(manifest_path): manifest_path = manifest_path.replace("\\", "\\\\") - data += '\n{} RT_MANIFEST "{}"\n'.format(manifest_id, manifest_path) + data += f'\n{manifest_id} RT_MANIFEST "{manifest_path}"\n' with open("{}.rc".format(binary or "module"), "w", encoding="latin1") as fh: fh.write(data) diff --git a/config/createprecomplete.py b/config/createprecomplete.py index 278ad8a7d7af..07139f250033 100644 --- a/config/createprecomplete.py +++ b/config/createprecomplete.py @@ -60,7 +60,7 @@ def generate_precomplete(root_path): precomplete_file_path = os.path.join(root_path, rel_path_precomplete) # Open the file so it exists before building the list of files and open it # in binary mode to prevent OS specific line endings. - precomplete_file = open(precomplete_file_path, mode="wt", newline="\n") + precomplete_file = open(precomplete_file_path, mode="w", newline="\n") rel_file_path_list, rel_dir_path_list = get_build_entries(root_path) for rel_file_path in rel_file_path_list: precomplete_file.write('remove "' + rel_file_path + '"\n') diff --git a/config/external/wasm2c_sandbox_compiler/preprocess_wasm2c_config.py b/config/external/wasm2c_sandbox_compiler/preprocess_wasm2c_config.py index 8be085979897..be61e70ba927 100644 --- a/config/external/wasm2c_sandbox_compiler/preprocess_wasm2c_config.py +++ b/config/external/wasm2c_sandbox_compiler/preprocess_wasm2c_config.py @@ -110,7 +110,7 @@ replaced_variables = """ def generate_config(output, config_h_in): - file_config_h_in = open(config_h_in, "r") + file_config_h_in = open(config_h_in) lines = file_config_h_in.readlines() # Remove the known cmake variables diff --git a/config/make-stl-wrappers.py b/config/make-stl-wrappers.py index ba4d6f74f768..b75c6c32c883 100644 --- a/config/make-stl-wrappers.py +++ b/config/make-stl-wrappers.py @@ -11,7 +11,7 @@ from mozbuild.util import FileAvoidWrite def gen_wrappers(unused, template_file, outdir, compiler, *header_list): - template = open(template_file, "r").read() + template = open(template_file).read() for header in header_list: with FileAvoidWrite(os.path.join(outdir, header)) as f: diff --git a/config/make-windows-h-wrapper.py b/config/make-windows-h-wrapper.py index 91d335ba420c..d6985c0fdd8b 100644 --- a/config/make-windows-h-wrapper.py +++ b/config/make-windows-h-wrapper.py @@ -18,7 +18,7 @@ decl_re = re.compile( def read_decls(filename): """Parse & yield C-style decls from an input file""" - with open(filename, "r") as fd: + with open(filename) as fd: # Strip comments from the source text. text = comment_re.sub("", fd.read()) @@ -37,7 +37,7 @@ def read_decls(filename): def generate(fd, consts_path, unicodes_path, template_path, compiler): # Parse the template - with open(template_path, "r") as template_fd: + with open(template_path) as template_fd: template = string.Template(template_fd.read()) decls = "" @@ -49,15 +49,13 @@ def generate(fd, consts_path, unicodes_path, template_path, compiler): assert args is None, "parameters in const decl!" decls += textwrap.dedent( - """ + f""" #ifdef {name} constexpr {ty} _tmp_{name} = {name}; #undef {name} constexpr {ty} {name} = _tmp_{name}; #endif - """.format( - ty=ty, name=name - ) + """ ) # Each unicode declaration defines a static inline function with the @@ -72,7 +70,7 @@ def generate(fd, consts_path, unicodes_path, template_path, compiler): args = ", ".join("a%d" % i for i in range(len(args))) decls += textwrap.dedent( - """ + f""" #ifdef {name} #undef {name} static inline {ty} WINAPI @@ -85,9 +83,7 @@ def generate(fd, consts_path, unicodes_path, template_path, compiler): = delete; #endif #endif - """.format( - ty=ty, name=name, params=params, args=args - ) + """ ) # Write out the resulting file diff --git a/config/mozunit/mozunit/mozunit.py b/config/mozunit/mozunit/mozunit.py index b4ccddf94fbf..56676787a02b 100644 --- a/config/mozunit/mozunit/mozunit.py +++ b/config/mozunit/mozunit/mozunit.py @@ -80,13 +80,13 @@ class _MozTestResult(_TestResult): def addError(self, test, err): _TestResult.addError(self, test, err) self.printFail(test, err) - self.stream.writeln("ERROR: {0}".format(self.getDescription(test))) + self.stream.writeln(f"ERROR: {self.getDescription(test)}") self.stream.writeln(self.errors[-1][1]) def addFailure(self, test, err): _TestResult.addFailure(self, test, err) self.printFail(test, err) - self.stream.writeln("FAIL: {0}".format(self.getDescription(test))) + self.stream.writeln(f"FAIL: {self.getDescription(test)}") self.stream.writeln(self.failures[-1][1]) def printFail(self, test, err): @@ -99,7 +99,7 @@ class _MozTestResult(_TestResult): tb = tb.tb_next if tb: _, ln, _ = inspect.getframeinfo(tb)[:3] - message = "line {0}: {1}".format(ln, message) + message = f"line {ln}: {message}" self.printStatus("TEST-UNEXPECTED-FAIL", test, message) @@ -151,7 +151,7 @@ def normcase(path): return path -class _MockBaseOpen(object): +class _MockBaseOpen: """Callable that acts like the open() function; see MockedOpen for more info. """ @@ -221,7 +221,7 @@ class _MockOpen(_MockBaseOpen): return MockedStringFile(self, name, content) -class MockedOpen(object): +class MockedOpen: """ Context manager diverting the open builtin such that opening files can open "virtual" file instances given when creating a MockedOpen. diff --git a/config/nsinstall.py b/config/nsinstall.py index 7d0a8594813a..b8f853b3224d 100644 --- a/config/nsinstall.py +++ b/config/nsinstall.py @@ -42,7 +42,7 @@ def _nsinstall_internal(argv): # The remaining arguments are not used in our tree, thus they're not # implented. def BadArg(option, opt, value, parser): - parser.error("option not supported: {0}".format(opt)) + parser.error(f"option not supported: {opt}") p.add_option( "-C", action="callback", metavar="CWD", callback=BadArg, help="NOT SUPPORTED" @@ -69,7 +69,7 @@ def _nsinstall_internal(argv): try: options.m = int(options.m, 8) except Exception: - sys.stderr.write("nsinstall: {0} is not a valid mode\n".format(options.m)) + sys.stderr.write(f"nsinstall: {options.m} is not a valid mode\n") return 1 # just create one directory? @@ -77,7 +77,7 @@ def _nsinstall_internal(argv): dir = os.path.abspath(dir) if os.path.exists(dir): if not os.path.isdir(dir): - print("nsinstall: {0} is not a directory".format(dir), file=sys.stderr) + print(f"nsinstall: {dir} is not a directory", file=sys.stderr) return 1 if mode: os.chmod(dir, mode) @@ -92,7 +92,7 @@ def _nsinstall_internal(argv): # We might have hit EEXIST due to a race condition (see bug 463411) -- try again once if try_again: return maybe_create_dir(dir, mode, False) - print("nsinstall: failed to create directory {0}: {1}".format(dir, e)) + print(f"nsinstall: failed to create directory {dir}: {e}") return 1 else: return 0 diff --git a/config/tests/unit-mozunit.py b/config/tests/unit-mozunit.py index 6915d86718d6..7d9dbd4534c5 100644 --- a/config/tests/unit-mozunit.py +++ b/config/tests/unit-mozunit.py @@ -25,26 +25,26 @@ class TestMozUnit(unittest.TestCase): self.assertFalse(os.path.exists("foo/file1")) # Check the contents of the files given at MockedOpen creation. - self.assertEqual(open("file1", "r").read(), "content1") - self.assertEqual(open("file2", "r").read(), "content2") + self.assertEqual(open("file1").read(), "content1") + self.assertEqual(open("file2").read(), "content2") # Check that overwriting these files alters their content. with open("file1", "w") as file: file.write("foo") self.assertTrue(os.path.exists("file1")) - self.assertEqual(open("file1", "r").read(), "foo") + self.assertEqual(open("file1").read(), "foo") # ... but not until the file is closed. file = open("file2", "w") file.write("bar") - self.assertEqual(open("file2", "r").read(), "content2") + self.assertEqual(open("file2").read(), "content2") file.close() - self.assertEqual(open("file2", "r").read(), "bar") + self.assertEqual(open("file2").read(), "bar") # Check that appending to a file does append with open("file1", "a") as file: file.write("bar") - self.assertEqual(open("file1", "r").read(), "foobar") + self.assertEqual(open("file1").read(), "foobar") self.assertFalse(os.path.exists("file3")) @@ -55,27 +55,27 @@ class TestMozUnit(unittest.TestCase): # Check that writing a new file does create the file. with open("file3", "w") as file: file.write("baz") - self.assertEqual(open("file3", "r").read(), "baz") + self.assertEqual(open("file3").read(), "baz") self.assertTrue(os.path.exists("file3")) # Check the content of the file created outside MockedOpen. - self.assertEqual(open(path, "r").read(), "foobar") + self.assertEqual(open(path).read(), "foobar") # Check that overwriting a file existing on the file system # does modify its content. with open(path, "w") as file: file.write("bazqux") - self.assertEqual(open(path, "r").read(), "bazqux") + self.assertEqual(open(path).read(), "bazqux") with MockedOpen(): # Check that appending to a file existing on the file system # does modify its content. with open(path, "a") as file: file.write("bazqux") - self.assertEqual(open(path, "r").read(), "foobarbazqux") + self.assertEqual(open(path).read(), "foobarbazqux") # Check that the file was not actually modified on the file system. - self.assertEqual(open(path, "r").read(), "foobar") + self.assertEqual(open(path).read(), "foobar") os.remove(path) # Check that the file created inside MockedOpen wasn't actually diff --git a/config/tests/unit-nsinstall.py b/config/tests/unit-nsinstall.py index 250cb56c2dc0..6c5c094a845c 100644 --- a/config/tests/unit-nsinstall.py +++ b/config/tests/unit-nsinstall.py @@ -120,9 +120,7 @@ class TestNsinstall(unittest.TestCase): mode = 0o600 os.chmod(testfile, mode) testdir = self.mkdirs("testdir") - self.assertEqual( - nsinstall(["-m", "{0:04o}".format(mode), testfile, testdir]), 0 - ) + self.assertEqual(nsinstall(["-m", f"{mode:04o}", testfile, testdir]), 0) destfile = os.path.join(testdir, "testfile") self.assertTrue(os.path.isfile(destfile)) self.assertEqual(os.stat(testfile).st_mode, os.stat(destfile).st_mode) diff --git a/config/tests/unitMozZipFile.py b/config/tests/unitMozZipFile.py index 32c994ded7f6..d08e4518ea36 100644 --- a/config/tests/unitMozZipFile.py +++ b/config/tests/unitMozZipFile.py @@ -197,7 +197,7 @@ allfiles = reduce( ) for first in allfiles: - testbasename = "test{0}_".format(getid(first)) + testbasename = f"test{getid(first)}_" test = [None, "_write" + getid(first), None] for second in atomics: test[0] = testbasename + getid([second]) diff --git a/configure.py b/configure.py index b3b89d419679..c7759d643286 100644 --- a/configure.py +++ b/configure.py @@ -45,7 +45,7 @@ else: def main(argv): # Check for CRLF line endings. - with open(__file__, "r") as fh: + with open(__file__) as fh: data = fh.read() if "\r" in data: print( diff --git a/devtools/rename.py b/devtools/rename.py index 01383867e773..122ac4d4cef3 100644 --- a/devtools/rename.py +++ b/devtools/rename.py @@ -7,6 +7,6 @@ # Put the content of `filenames[0]` file into `output` file pointer def main(output, *filenames): - with open(filenames[0], "r", encoding="utf-8") as f: + with open(filenames[0], encoding="utf-8") as f: content = f.read() output.write(content) diff --git a/dom/base/usecounters.py b/dom/base/usecounters.py index ec2c8e43daa0..d425e0428c30 100644 --- a/dom/base/usecounters.py +++ b/dom/base/usecounters.py @@ -7,7 +7,7 @@ import re def read_conf(conf_filename): # Can't read/write from a single StringIO, so make a new one for reading. - stream = open(conf_filename, "r") + stream = open(conf_filename) def parse_counters(stream): for line_num, full_line in enumerate(stream): diff --git a/dom/bindings/mozwebidlcodegen/__init__.py b/dom/bindings/mozwebidlcodegen/__init__.py index f657a098ebe9..292b06726a67 100644 --- a/dom/bindings/mozwebidlcodegen/__init__.py +++ b/dom/bindings/mozwebidlcodegen/__init__.py @@ -67,7 +67,7 @@ class WebIDLPool: return WebIDLPool.GeneratorState._generate_build_files_for_webidl(filename) -class BuildResult(object): +class BuildResult: """Represents the result of processing WebIDL files. This holds a summary of output file generation during code generation. @@ -283,7 +283,7 @@ class WebIDLCodegenManager(LoggingMixin): self._state = WebIDLCodegenManagerState() if os.path.exists(state_path): - with open(state_path, "r") as fh: + with open(state_path) as fh: try: self._state = WebIDLCodegenManagerState(fh=fh) except Exception as e: @@ -442,7 +442,7 @@ class WebIDLCodegenManager(LoggingMixin): parser = WebIDL.Parser(self._cache_dir, lexer=None) for path in sorted(self._input_paths): - with open(path, "r", encoding="utf-8") as fh: + with open(path, encoding="utf-8") as fh: data = fh.read() hashes[path] = hashlib.sha1(data.encode()).hexdigest() parser.parse(data, path) @@ -716,7 +716,7 @@ def create_build_system_manager(topsrcdir=None, topobjdir=None, dist_dir=None): obj_dir = os.path.join(topobjdir, "dom", "bindings") webidl_root = os.path.join(topsrcdir, "dom", "webidl") - with open(os.path.join(obj_dir, "file-lists.json"), "r") as fh: + with open(os.path.join(obj_dir, "file-lists.json")) as fh: files = json.load(fh) inputs = ( diff --git a/dom/bindings/mozwebidlcodegen/test/test_mozwebidlcodegen.py b/dom/bindings/mozwebidlcodegen/test/test_mozwebidlcodegen.py index ef2cea345665..5c222f6320d4 100644 --- a/dom/bindings/mozwebidlcodegen/test/test_mozwebidlcodegen.py +++ b/dom/bindings/mozwebidlcodegen/test/test_mozwebidlcodegen.py @@ -126,7 +126,7 @@ class TestWebIDLCodegenManager(unittest.TestCase): self.assertTrue(os.path.isfile(manager._state_path)) - with open(manager._state_path, "r") as fh: + with open(manager._state_path) as fh: state = json.load(fh) self.assertEqual(state["version"], 3) self.assertIn("webidls", state) @@ -192,7 +192,7 @@ class TestWebIDLCodegenManager(unittest.TestCase): break self.assertIsNotNone(child_path) - child_content = open(child_path, "r").read() + child_content = open(child_path).read() with MockedOpen({child_path: child_content + "\n/* */"}): m2 = WebIDLCodegenManager(**args) @@ -216,7 +216,7 @@ class TestWebIDLCodegenManager(unittest.TestCase): child_path = p self.assertIsNotNone(parent_path) - parent_content = open(parent_path, "r").read() + parent_content = open(parent_path).read() with MockedOpen({parent_path: parent_content + "\n/* */"}): m2 = WebIDLCodegenManager(**args) @@ -253,7 +253,7 @@ class TestWebIDLCodegenManager(unittest.TestCase): result = m1.generate_build_files(processes=1) l = len(result.inputs) - with open(fake_path, "wt", newline="\n") as fh: + with open(fake_path, "w", newline="\n") as fh: fh.write("# Modified content") m2 = WebIDLCodegenManager(**args) diff --git a/dom/bindings/parser/runtests.py b/dom/bindings/parser/runtests.py index 5161c87ea72b..a9a68952f9a0 100644 --- a/dom/bindings/parser/runtests.py +++ b/dom/bindings/parser/runtests.py @@ -12,7 +12,7 @@ import traceback import WebIDL -class TestHarness(object): +class TestHarness: def __init__(self, test, verbose): self.test = test self.verbose = verbose diff --git a/dom/canvas/test/webgl-conf/generate-wrappers-and-manifest.py b/dom/canvas/test/webgl-conf/generate-wrappers-and-manifest.py index 0f6a38feb5b7..f42da77c5b9c 100755 --- a/dom/canvas/test/webgl-conf/generate-wrappers-and-manifest.py +++ b/dom/canvas/test/webgl-conf/generate-wrappers-and-manifest.py @@ -66,7 +66,7 @@ def ChooseSubsuite(name): elif split[1] == "textures" and split[2] != "misc": category = "ext" - return "webgl{}-{}".format(version, category) + return f"webgl{version}-{category}" ######################################################################## @@ -133,7 +133,7 @@ def AccumTests(pathStr, listFile, allowWebGL1, allowWebGL2, out_testList): listPath = listPathStr.replace("/", os.sep) assert os.path.exists(listPath), "Bad `listPath`: " + listPath - with open(listPath, "r") as fIn: + with open(listPath) as fIn: lineNum = 0 for line in fIn: lineNum += 1 @@ -164,9 +164,7 @@ def AccumTests(pathStr, listFile, allowWebGL1, allowWebGL2, out_testList): elif flag == "--slow": continue # TODO else: - text = "Unknown flag '{}': {}:{}: {}".format( - flag, listPath, lineNum, line - ) + text = f"Unknown flag '{flag}': {listPath}:{lineNum}: {line}" assert False, text continue @@ -210,7 +208,7 @@ def FillTemplate(inFilePath, templateDict, outFilePath): def ImportTemplate(inFilePath): - with open(inFilePath, "r") as f: + with open(inFilePath) as f: return TemplateShell(f) @@ -379,7 +377,7 @@ def WriteWrappers(testEntryList): WriteWrapper(entry.path, True, templateShell, wrapperPathList) continue - print("{} wrappers written.\n".format(len(wrapperPathList))) + print(f"{len(wrapperPathList)} wrappers written.\n") return wrapperPathList @@ -469,7 +467,7 @@ def LoadTOML(path): key = "" val = "" - with open(path, "r") as f: + with open(path) as f: for rawLine in f: lineNum += 1 if multiLineVal: @@ -484,11 +482,11 @@ def LoadTOML(path): if line[0] in [";", "#"]: continue if line[0] == "[": - assert line[-1] == "]", "{}:{}".format(path, lineNum) + assert line[-1] == "]", f"{path}:{lineNum}" curSectionName = line[1:-1].strip('"') assert ( curSectionName not in ret - ), "Line {}: Duplicate section: {}".format(lineNum, line) + ), f"Line {lineNum}: Duplicate section: {line}" curSectionMap = {} ret[curSectionName] = (lineNum, curSectionMap) continue @@ -517,14 +515,14 @@ def LoadErrata(): continue elif sectionName != "DEFAULT": path = sectionName.replace("/", os.sep) - assert os.path.exists(path), "Errata line {}: Invalid file: {}".format( - sectionLineNum, sectionName - ) + assert os.path.exists( + path + ), f"Errata line {sectionLineNum}: Invalid file: {sectionName}" for key, (lineNum, val) in sectionMap.items(): - assert key in ACCEPTABLE_ERRATA_KEYS, "Line {}: {}".format(lineNum, key) + assert key in ACCEPTABLE_ERRATA_KEYS, f"Line {lineNum}: {key}" - curLine = "{} = {}".format(key, val) + curLine = f"{key} = {val}" curLines.append(curLine) continue diff --git a/dom/media/test/reftest/gen_combos.py b/dom/media/test/reftest/gen_combos.py index 400652d87a45..2a9468add8d5 100644 --- a/dom/media/test/reftest/gen_combos.py +++ b/dom/media/test/reftest/gen_combos.py @@ -214,7 +214,7 @@ for c in COMBOS: # - -with open(DIR / "reftest.list", "r") as f: +with open(DIR / "reftest.list") as f: reftest_list_text = f.read() for args in todo: diff --git a/dom/media/tools/checkGmpBalrog.py b/dom/media/tools/checkGmpBalrog.py index 3731c89cbea7..c5a8e362046f 100644 --- a/dom/media/tools/checkGmpBalrog.py +++ b/dom/media/tools/checkGmpBalrog.py @@ -96,9 +96,9 @@ def fetch_balrog_xml( for channel in results: print(", ".join(matching_channels[channel])) for target in targets: - print("\t{}".format(target)) + print(f"\t{target}") for url in results[channel][target]: - print("\t\t{}".format(url)) + print(f"\t\t{url}") def main(): diff --git a/dom/media/tools/generateGmpJson.py b/dom/media/tools/generateGmpJson.py index 2f91b15ec817..8ff3f143807d 100644 --- a/dom/media/tools/generateGmpJson.py +++ b/dom/media/tools/generateGmpJson.py @@ -163,14 +163,14 @@ def calculate_gmpopenh264_json(version: str, version_hash: str, url_base: str) - return ( "{\n" + ' "hashFunction": "sha512",\n' - + ' "name": "OpenH264-{}",\n'.format(version) + + f' "name": "OpenH264-{version}",\n' + ' "schema_version": 1000,\n' + ' "vendors": {\n' + ' "gmp-gmpopenh264": {\n' + ' "platforms": {\n' + generate_json_for_cdms(cdms) + " },\n" - + ' "version": "{}"\n'.format(version) + + f' "version": "{version}"\n' + " }\n" + " }\n" + "}" @@ -203,14 +203,14 @@ def calculate_widevinecdm_json(version: str, url_base: str) -> str: return ( "{\n" + ' "hashFunction": "sha512",\n' - + ' "name": "Widevine-{}",\n'.format(version) + + f' "name": "Widevine-{version}",\n' + ' "schema_version": 1000,\n' + ' "vendors": {\n' + ' "gmp-widevinecdm": {\n' + ' "platforms": {\n' + generate_json_for_cdms(cdms) + " },\n" - + ' "version": "{}"\n'.format(version) + + f' "version": "{version}"\n' + " }\n" + " }\n" + "}" @@ -232,14 +232,14 @@ def calculate_chrome_component_json( return ( "{\n" + ' "hashFunction": "sha512",\n' - + ' "name": "{}-{}",\n'.format(name, version) + + f' "name": "{name}-{version}",\n' + ' "schema_version": 1000,\n' + ' "vendors": {\n' - + ' "gmp-{}": {{\n'.format(altname) + + f' "gmp-{altname}": {{\n' + ' "platforms": {\n' + generate_json_for_cdms(cdms) + " },\n" - + ' "version": "{}"\n'.format(version) + + f' "version": "{version}"\n' + " }\n" + " }\n" + "}" diff --git a/dom/media/webaudio/test/generate-test-files.py b/dom/media/webaudio/test/generate-test-files.py index af4bc3bb4932..024cd6803fbd 100755 --- a/dom/media/webaudio/test/generate-test-files.py +++ b/dom/media/webaudio/test/generate-test-files.py @@ -33,10 +33,8 @@ formats = { for rate in rates: for channel_count in channels: - wav_filename = "{}-{}ch-{}.wav".format(name, channel_count, rate) - wav_command = "sox -V -r {} -n -b 16 -c {} {} synth {} sin {} vol {}".format( - rate, channel_count, wav_filename, duration, frequency, volume - ) + wav_filename = f"{name}-{channel_count}ch-{rate}.wav" + wav_command = f"sox -V -r {rate} -n -b 16 -c {channel_count} {wav_filename} synth {duration} sin {frequency} vol {volume}" print(wav_command) os.system(wav_command) for container, codecs in formats.items(): diff --git a/dom/media/webrtc/third_party_build/gn-configs/abseil_preprocessor.py b/dom/media/webrtc/third_party_build/gn-configs/abseil_preprocessor.py index b840b3d8fdfa..a84c1706fdc8 100644 --- a/dom/media/webrtc/third_party_build/gn-configs/abseil_preprocessor.py +++ b/dom/media/webrtc/third_party_build/gn-configs/abseil_preprocessor.py @@ -6,7 +6,7 @@ def main(gn_config_file): target_dir = "abseil-cpp" raw_file_contents = "" - with open(gn_config_file, "r") as fh: + with open(gn_config_file) as fh: raw_file_contents = fh.read() raw_file_contents = raw_file_contents.replace(f"{target_dir}/", "") raw_file_contents = raw_file_contents.replace(f"{target_dir}:", ":") diff --git a/dom/media/webrtc/third_party_build/gn-configs/webrtc_preprocessor.py b/dom/media/webrtc/third_party_build/gn-configs/webrtc_preprocessor.py index 163773e531f4..e5caeb089abf 100644 --- a/dom/media/webrtc/third_party_build/gn-configs/webrtc_preprocessor.py +++ b/dom/media/webrtc/third_party_build/gn-configs/webrtc_preprocessor.py @@ -6,7 +6,7 @@ def main(gn_config_file): target_dir = "libwebrtc" raw_file_contents = "" - with open(gn_config_file, "r") as fh: + with open(gn_config_file) as fh: raw_file_contents = fh.read() raw_file_contents = raw_file_contents.replace(f"{target_dir}/", "") raw_file_contents = raw_file_contents.replace(f"{target_dir}:", ":") diff --git a/dom/media/webrtc/third_party_build/lookup_branch_head.py b/dom/media/webrtc/third_party_build/lookup_branch_head.py index eba2e47e8588..9343db54cd03 100644 --- a/dom/media/webrtc/third_party_build/lookup_branch_head.py +++ b/dom/media/webrtc/third_party_build/lookup_branch_head.py @@ -37,7 +37,7 @@ def fetch_branch_head_dict(): def read_dict_from_cache(cache_path): if cache_path is not None and os.path.exists(cache_path): - with open(cache_path, "r") as ifile: + with open(cache_path) as ifile: return json.loads(ifile.read(), object_hook=jsonKeys2int) return {} diff --git a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/fn_anchors.py b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/fn_anchors.py index 13e3802399fe..2280b0b2fce6 100644 --- a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/fn_anchors.py +++ b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/fn_anchors.py @@ -62,7 +62,7 @@ def getFunctionName(location): pieces = location.split("#l") src_url = pieces[0] line = int(pieces[1]) - closest_name = "".format(line) + closest_name = f"" closest_start = 0 functions = getSourceFunctions(src_url) for fn in functions: diff --git a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/telemetry.py b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/telemetry.py index 26debd0546c3..f8aa42a84f6a 100644 --- a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/telemetry.py +++ b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/telemetry.py @@ -12,7 +12,7 @@ TELEMETRY_BASE_URL = "https://sql.telemetry.mozilla.org/api/" def query(key, query, p_params): - headers = {"Authorization": "Key {}".format(key)} + headers = {"Authorization": f"Key {key}"} start_url = TELEMETRY_BASE_URL + f"queries/{query}/refresh?{p_params}" info(f"Starting job using url {start_url}") resp = requests.post(url=start_url, headers=headers) diff --git a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/utils.py b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/utils.py index 485dbf66f532..f06b13ef8e21 100644 --- a/dom/quota/scripts/qm-try-analysis/qm_try_analysis/utils.py +++ b/dom/quota/scripts/qm-try-analysis/qm_try_analysis/utils.py @@ -11,7 +11,7 @@ from qm_try_analysis.logging import error, info, warning def readJSONFile(FileName): - f = open(FileName, "r") + f = open(FileName) p = json.load(f) f.close() return p @@ -57,7 +57,7 @@ def fetchBuildRevisions(buildids): def readExecutionFile(workdir): - exefile = "{}/qmexecutions.json".format(workdir) + exefile = f"{workdir}/qmexecutions.json" try: return readJSONFile(exefile) except OSError: @@ -65,7 +65,7 @@ def readExecutionFile(workdir): def writeExecutionFile(workdir, executions): - exefile = "{}/qmexecutions.json".format(workdir) + exefile = f"{workdir}/qmexecutions.json" try: writeJSONFile(exefile, executions) except OSError: diff --git a/dom/quota/scripts/qm-try-analysis/tests/test_reporting.py b/dom/quota/scripts/qm-try-analysis/tests/test_reporting.py index f3be6d9cf030..279fe9142647 100644 --- a/dom/quota/scripts/qm-try-analysis/tests/test_reporting.py +++ b/dom/quota/scripts/qm-try-analysis/tests/test_reporting.py @@ -3,7 +3,7 @@ import copy from qm_try_analysis.report import remove_duplicates -class MockClient(object): +class MockClient: def __init__(self, search_results, remote_bugs): self.search_results = copy.deepcopy(search_results) self.remote_bugs = copy.deepcopy(remote_bugs) diff --git a/dom/websocket/tests/websocket_hybi/file_check-binary-messages_wsh.py b/dom/websocket/tests/websocket_hybi/file_check-binary-messages_wsh.py index ee03dfc37c8f..074cf6feda2c 100644 --- a/dom/websocket/tests/websocket_hybi/file_check-binary-messages_wsh.py +++ b/dom/websocket/tests/websocket_hybi/file_check-binary-messages_wsh.py @@ -12,13 +12,11 @@ def web_socket_transfer_data(request): expected_message = expected_message.encode("latin-1") message = msgutil.receive_message(request) if message == expected_message: - msgutil.send_message(request, "PASS: Message #{:d}.".format(test_number)) + msgutil.send_message(request, f"PASS: Message #{test_number:d}.") else: msgutil.send_message( request, - "FAIL: Message #{:d}: Received unexpected message: {!r}".format( - test_number, message - ), + f"FAIL: Message #{test_number:d}: Received unexpected message: {message!r}", ) diff --git a/gfx/layers/d3d11/genshaders.py b/gfx/layers/d3d11/genshaders.py index b9701978d5c2..ee0812207dea 100644 --- a/gfx/layers/d3d11/genshaders.py +++ b/gfx/layers/d3d11/genshaders.py @@ -78,10 +78,10 @@ def run_fxc(shader_model, shader_file, shader_name, output_fp): argv = [ fxc_location, "-nologo", - "-T{0}".format(shader_model), + f"-T{shader_model}", os.path.relpath(shader_file), - "-E{0}".format(shader_name), - "-Vn{0}".format(shader_name), + f"-E{shader_name}", + f"-Vn{shader_name}", "-Vi", ] if "WINNT" not in buildconfig.substs["HOST_OS_ARCH"]: @@ -93,7 +93,7 @@ def run_fxc(shader_model, shader_file, shader_name, output_fp): deps = None with ScopedTempFilename() as temp_filename: - argv += ["-Fh{0}".format(os.path.relpath(temp_filename))] + argv += [f"-Fh{os.path.relpath(temp_filename)}"] sys.stdout.write("{0}\n".format(" ".join(argv))) sys.stdout.flush() @@ -102,10 +102,12 @@ def run_fxc(shader_model, shader_file, shader_name, output_fp): deps = find_dependencies(proc_stdout) assert "fxc2" in fxc_location or len(deps) > 0 - with open(temp_filename, "r") as temp_fp: + with open(temp_filename) as temp_fp: output_fp.write(temp_fp.read()) - output_fp.write("ShaderBytes s{0} = {{ {0}, sizeof({0}) }};\n".format(shader_name)) + output_fp.write( + f"ShaderBytes s{shader_name} = {{ {shader_name}, sizeof({shader_name}) }};\n" + ) return deps @@ -154,7 +156,7 @@ def decode_console_text(pipe, text): # wrapper for this since TemporaryNamedFile holds the file open. -class ScopedTempFilename(object): +class ScopedTempFilename: def __init__(self): self.name = None diff --git a/intl/locale/props2arrays.py b/intl/locale/props2arrays.py index 0572cb1c5f26..3a31fdb80b33 100644 --- a/intl/locale/props2arrays.py +++ b/intl/locale/props2arrays.py @@ -6,7 +6,7 @@ def main(header, propFile): mappings = {} - with open(propFile, "r") as f: + with open(propFile) as f: for line in f: line = line.strip() if not line.startswith("#"): diff --git a/intl/unicharutil/util/base_chars.py b/intl/unicharutil/util/base_chars.py index 91d3ba335255..20c21a75371c 100644 --- a/intl/unicharutil/util/base_chars.py +++ b/intl/unicharutil/util/base_chars.py @@ -126,12 +126,7 @@ def main(header, fallback_table): header.write("\n") header.write("static const uint16_t BASE_CHAR_MAPPING_LIST[] = {\n") for char, base_char in mappings: - header.write( - " /* {:#06x}".format(char) - + " */ " - + "{:#06x}".format(base_char & 0xFFFF) - + "," - ) + header.write(f" /* {char:#06x}" + " */ " + f"{base_char & 0xFFFF:#06x}" + ",") if char != base_char: header.write(" /* " + chr(char) + " → " + chr(base_char) + " */") header.write("\n") @@ -143,20 +138,18 @@ def main(header, fallback_table): for block in blocks: header.write( " {" - + "{:#04x}".format(block.first) + + f"{block.first:#04x}" + ", " - + "{:#04x}".format(block.last) + + f"{block.last:#04x}" + ", " + str(block.offset).rjust(4) + "}, // " - + "{:#04x}".format(mappings[block.offset].char >> 8) + + f"{mappings[block.offset].char >> 8:#04x}" + "xx\n" ) header.write("};\n") header.write("\n") header.write("static const uint8_t BASE_CHAR_MAPPING_BLOCK_INDEX[] = {\n") for i, index in enumerate(indexes): - header.write( - " " + str(index).rjust(3) + ", // " + "{:#04x}".format(i) + "xx\n" - ) + header.write(" " + str(index).rjust(3) + ", // " + f"{i:#04x}" + "xx\n") header.write("};\n") diff --git a/ipc/ipdl/test/ipdl/runtests.py b/ipc/ipdl/test/ipdl/runtests.py index 4296eab65ce6..fb6f7a61cdb5 100644 --- a/ipc/ipdl/test/ipdl/runtests.py +++ b/ipc/ipdl/test/ipdl/runtests.py @@ -58,7 +58,7 @@ class ErrorTestCase(IPDLTestCase): IPDLTestCase.__init__(self, ipdlargv, filename) # Look for expected errors in the input file. - f = open(filename, "r") + f = open(filename) self.expectedErrorMessage = [] for l in f: if l.startswith("//error:"): diff --git a/js/src/GeneratePrefs.py b/js/src/GeneratePrefs.py index 2a49a986fa49..2a16c7a6e805 100644 --- a/js/src/GeneratePrefs.py +++ b/js/src/GeneratePrefs.py @@ -57,7 +57,7 @@ def get_cpp_type(type): return "uint32_t" if type in ("int32_t", "RelaxedAtomicInt32"): return "int32_t" - raise Exception("Unexpected type: {}".format(type)) + raise Exception(f"Unexpected type: {type}") # Returns a C++ expression for the default pref value. Booleans in the YAML file @@ -117,10 +117,10 @@ def generate_prefs_header(c_out, yaml_path): # after startup. field_type = type if not is_startup_pref: - field_type = "mozilla::Atomic<{}, mozilla::Relaxed>".format(field_type) - class_fields.append("static {} {}_;".format(field_type, cpp_name)) + field_type = f"mozilla::Atomic<{field_type}, mozilla::Relaxed>" + class_fields.append(f"static {field_type} {cpp_name}_;") class_fields_inits.append( - "{} JS::Prefs::{}_{{{}}};".format(field_type, cpp_name, init_value) + f"{field_type} JS::Prefs::{cpp_name}_{{{init_value}}};" ) is_startup_pref_bool = "true" if is_startup_pref else "false" @@ -128,9 +128,7 @@ def generate_prefs_header(c_out, yaml_path): # Generate a MACRO invocation like this: # MACRO("arraybuffer_transfer", arraybuffer_transfer, bool, setAtStartup_arraybuffer_transfer, true) macro_entries.append( - 'MACRO("{}", {}, {}, {}, {})'.format( - name, cpp_name, type, setter_name, is_startup_pref_bool - ) + f'MACRO("{name}", {cpp_name}, {type}, {setter_name}, {is_startup_pref_bool})' ) # Generate a C++ statement to set the JS pref based on Gecko's StaticPrefs: @@ -139,9 +137,7 @@ def generate_prefs_header(c_out, yaml_path): if pref.get("do_not_use_directly", False): browser_pref_cpp_name += "_DoNotUseDirectly" - statement = "JS::Prefs::{}(mozilla::StaticPrefs::{}());".format( - setter_name, browser_pref_cpp_name - ) + statement = f"JS::Prefs::{setter_name}(mozilla::StaticPrefs::{browser_pref_cpp_name}());" browser_set_statements.append(statement) # For non-startup prefs, also generate code to update the pref after startup. @@ -151,25 +147,23 @@ def generate_prefs_header(c_out, yaml_path): contents = "" contents += "#define JS_PREF_CLASS_FIELDS \\\n" - contents += "".join(map(lambda s: " {}\\\n".format(s), class_fields)) + contents += "".join(map(lambda s: f" {s}\\\n", class_fields)) contents += "\n\n" contents += "#define JS_PREF_CLASS_FIELDS_INIT \\\n" - contents += "".join(map(lambda s: " {}\\\n".format(s), class_fields_inits)) + contents += "".join(map(lambda s: f" {s}\\\n", class_fields_inits)) contents += "\n\n" contents += "#define FOR_EACH_JS_PREF(MACRO) \\\n" - contents += "".join(map(lambda s: " {}\\\n".format(s), macro_entries)) + contents += "".join(map(lambda s: f" {s}\\\n", macro_entries)) contents += "\n\n" contents += "#define SET_JS_PREFS_FROM_BROWSER_PREFS \\\n" - contents += "".join(map(lambda s: " {}\\\n".format(s), browser_set_statements)) + contents += "".join(map(lambda s: f" {s}\\\n", browser_set_statements)) contents += "\n\n" contents += "#define SET_NON_STARTUP_JS_PREFS_FROM_BROWSER_PREFS \\\n" - contents += "".join( - map(lambda s: " {}\\\n".format(s), browser_set_non_startup_statements) - ) + contents += "".join(map(lambda s: f" {s}\\\n", browser_set_non_startup_statements)) contents += "\n\n" c_out.write( diff --git a/js/src/builtin/embedjs.py b/js/src/builtin/embedjs.py index 685f511e4983..989b6cfbff45 100644 --- a/js/src/builtin/embedjs.py +++ b/js/src/builtin/embedjs.py @@ -148,7 +148,7 @@ def preprocess(cxx, preprocessorOption, source, args=[]): result = subprocess.Popen(cxx + outputArg + args + [tmpIn]).wait() if result != 0: sys.exit(result) - with open(tmpOut, "r") as output: + with open(tmpOut) as output: processed = output.read() os.remove(tmpIn) os.remove(tmpOut) diff --git a/js/src/builtin/intl/make_intl_data.py b/js/src/builtin/intl/make_intl_data.py index 3d26ae8ac9b3..df11b2b4d6d0 100755 --- a/js/src/builtin/intl/make_intl_data.py +++ b/js/src/builtin/intl/make_intl_data.py @@ -70,9 +70,9 @@ def writeMappingHeader(println, description, source, url): if type(description) is not list: description = [description] for desc in description: - println("// {0}".format(desc)) - println("// Derived from {0}.".format(source)) - println("// {0}".format(url)) + println(f"// {desc}") + println(f"// Derived from {source}.") + println(f"// {url}") def writeMappingsVar(println, mapping, name, description, source, url): @@ -84,9 +84,9 @@ def writeMappingsVar(println, mapping, name, description, source, url): """ println("") writeMappingHeader(println, description, source, url) - println("var {0} = {{".format(name)) + println(f"var {name} = {{") for key, value in sorted(mapping.items(), key=itemgetter(0)): - println(' "{0}": "{1}",'.format(key, value)) + println(f' "{key}": "{value}",') println("};") @@ -111,13 +111,11 @@ def writeMappingsBinarySearch( println("") writeMappingHeader(println, description, source, url) println( - """ -bool mozilla::intl::Locale::{0}({1} {2}) {{ - MOZ_ASSERT({3}({2}.Span())); - MOZ_ASSERT({4}({2}.Span())); -""".format( - fn_name, type_name, name, validate_fn, validate_case_fn - ).strip() + f""" +bool mozilla::intl::Locale::{fn_name}({type_name} {name}) {{ + MOZ_ASSERT({validate_fn}({name}.Span())); + MOZ_ASSERT({validate_case_fn}({name}.Span())); +""".strip() ) writeMappingsBinarySearchBody(println, name, name, mappings, tag_maxlength) @@ -134,20 +132,14 @@ def writeMappingsBinarySearchBody( ): def write_array(subtags, name, length, fixed): if fixed: - println( - " static const char {}[{}][{}] = {{".format( - name, len(subtags), length + 1 - ) - ) + println(f" static const char {name}[{len(subtags)}][{length + 1}] = {{") else: - println(" static const char* {}[{}] = {{".format(name, len(subtags))) + println(f" static const char* {name}[{len(subtags)}] = {{") # Group in pairs of ten to not exceed the 80 line column limit. for entries in grouper(subtags, 10): entries = ( - '"{}"'.format(tag).rjust(length + 2) - for tag in entries - if tag is not None + f'"{tag}"'.rjust(length + 2) for tag in entries if tag is not None ) println(" {},".format(", ".join(entries))) @@ -163,11 +155,9 @@ def writeMappingsBinarySearchBody( # Omit the length check if the current length is the maximum length. if length != tag_maxlength: println( - """ - if ({}.Length() == {}) {{ -""".format( - source_name, length - ).rstrip( + f""" + if ({source_name}.Length() == {length}) {{ +""".rstrip( "\n" ) ) @@ -185,31 +175,27 @@ def writeMappingsBinarySearchBody( subtags = sorted(subtags) def equals(subtag): - return """{}.EqualTo("{}")""".format(source_name, subtag) + return f"""{source_name}.EqualTo("{subtag}")""" # Don't emit a binary search for short lists. if len(subtags) == 1: if type(mappings) is dict: println( - """ - if ({}) {{ - {}.Set(mozilla::MakeStringSpan("{}")); + f""" + if ({equals(subtags[0])}) {{ + {target_name}.Set(mozilla::MakeStringSpan("{mappings[subtags[0]]}")); return true; }} return false; -""".format( - equals(subtags[0]), target_name, mappings[subtags[0]] - ).strip( +""".strip( "\n" ) ) else: println( - """ - return {}; -""".format( - equals(subtags[0]) - ).strip( + f""" + return {equals(subtags[0])}; +""".strip( "\n" ) ) @@ -217,14 +203,12 @@ def writeMappingsBinarySearchBody( if type(mappings) is dict: for subtag in subtags: println( - """ - if ({}) {{ - {}.Set("{}"); + f""" + if ({equals(subtag)}) {{ + {target_name}.Set("{mappings[subtag]}"); return true; }} -""".format( - equals(subtag), target_name, mappings[subtag] - ).strip( +""".strip( "\n" ) ) @@ -240,11 +224,9 @@ def writeMappingsBinarySearchBody( cond = (equals(subtag) for subtag in subtags) cond = (" ||\n" + " " * (4 + len("return "))).join(cond) println( - """ - return {}; -""".format( - cond - ).strip( + f""" + return {cond}; +""".strip( "\n" ) ) @@ -255,23 +237,19 @@ def writeMappingsBinarySearchBody( write_array([mappings[k] for k in subtags], "aliases", length, False) println( - """ - if (const char* replacement = SearchReplacement({0}s, aliases, {0})) {{ - {1}.Set(mozilla::MakeStringSpan(replacement)); + f""" + if (const char* replacement = SearchReplacement({source_name}s, aliases, {source_name})) {{ + {target_name}.Set(mozilla::MakeStringSpan(replacement)); return true; }} return false; -""".format( - source_name, target_name - ).rstrip() +""".rstrip() ) else: println( - """ - return HasReplacement({0}s, {0}); -""".format( - source_name - ).rstrip() + f""" + return HasReplacement({source_name}s, {source_name}); +""".rstrip() ) println( @@ -325,48 +303,40 @@ void mozilla::intl::Locale::PerformComplexLanguageMappings() { first_language = False cond = ( - 'Language().EqualTo("{}")'.format(lang) + f'Language().EqualTo("{lang}")' for lang in [deprecated_language] + language_aliases[key] ) cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond) println( - """ - {} ({}) {{""".format( - if_kind, cond - ).strip( + f""" + {if_kind} ({cond}) {{""".strip( "\n" ) ) println( - """ - SetLanguage("{}");""".format( - language - ).strip( + f""" + SetLanguage("{language}");""".strip( "\n" ) ) if script is not None: println( - """ + f""" if (Script().Missing()) {{ - SetScript("{}"); - }}""".format( - script - ).strip( + SetScript("{script}"); + }}""".strip( "\n" ) ) if region is not None: println( - """ + f""" if (Region().Missing()) {{ - SetRegion("{}"); - }}""".format( - region - ).strip( + SetRegion("{region}"); + }}""".strip( "\n" ) ) @@ -429,16 +399,14 @@ void mozilla::intl::Locale::PerformComplexRegionMappings() { first_region = False cond = ( - 'Region().EqualTo("{}")'.format(region) + f'Region().EqualTo("{region}")' for region in [deprecated_region] + region_aliases[key] ) cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond) println( - """ - {} ({}) {{""".format( - if_kind, cond - ).strip( + f""" + {if_kind} ({cond}) {{""".strip( "\n" ) ) @@ -460,10 +428,8 @@ void mozilla::intl::Locale::PerformComplexRegionMappings() { def compare_tags(language, script): if script is None: - return 'Language().EqualTo("{}")'.format(language) - return '(Language().EqualTo("{}") && Script().EqualTo("{}"))'.format( - language, script - ) + return f'Language().EqualTo("{language}")' + return f'(Language().EqualTo("{language}") && Script().EqualTo("{script}"))' cond = ( compare_tags(language, script) @@ -472,26 +438,22 @@ void mozilla::intl::Locale::PerformComplexRegionMappings() { cond = (" ||\n" + " " * (4 + len(if_kind) + 2)).join(cond) println( - """ - {} ({}) {{ - SetRegion("{}"); - }}""".format( - if_kind, cond, replacement_region + f""" + {if_kind} ({cond}) {{ + SetRegion("{replacement_region}"); + }}""".rstrip().strip( + "\n" ) - .rstrip() - .strip("\n") ) println( - """ + f""" else {{ - SetRegion("{}"); + SetRegion("{default}"); }} - }}""".format( - default + }}""".rstrip().strip( + "\n" ) - .rstrip() - .strip("\n") ) println( @@ -1485,7 +1447,7 @@ def readUnicodeExtensions(core_file): extension = keyword.get("extension", "u") assert ( extension == "u" or extension == "t" - ), "unknown extension type: {}".format(extension) + ), f"unknown extension type: {extension}" extension_name = keyword.get("name") @@ -1517,7 +1479,7 @@ def readUnicodeExtensions(core_file): # All other names should match the 'type' production. assert ( typeRE.match(name) is not None - ), "{} matches the 'type' production".format(name) + ), f"{name} matches the 'type' production" # : # @@ -1593,7 +1555,7 @@ def readUnicodeExtensions(core_file): type = alias.get("type") assert ( typeRE.match(type) is not None - ), "{} matches the 'type' production".format(type) + ), f"{type} matches the 'type' production" # Take the first replacement when multiple ones are present. replacement = alias.get("replacement").split(" ")[0].lower() @@ -1605,7 +1567,7 @@ def readUnicodeExtensions(core_file): # Assert the replacement is syntactically correct. assert ( typeRE.match(replacement) is not None - ), "replacement {} matches the 'type' production".format(replacement) + ), f"replacement {replacement} matches the 'type' production" # 'subdivisionAlias' applies to 'rg' and 'sd' keys. mapping["u"].setdefault("rg", {})[type] = replacement @@ -1630,7 +1592,7 @@ def writeCLDRLanguageTagData(println, data, url): println(generatedFileWarning) println("// Version: CLDR-{}".format(data["version"])) - println("// URL: {}".format(url)) + println(f"// URL: {url}") println( """ @@ -1897,7 +1859,7 @@ def writeCLDRLanguageTagLikelySubtagsTest(println, data, url): # Assume no complex region mappings are needed for now. assert ( region not in complex_region_mappings - ), "unexpected region with complex mappings: {}".format(region) + ), f"unexpected region with complex mappings: {region}" return (language, script, region) @@ -2020,7 +1982,7 @@ if (typeof reportCompare === "function") def readCLDRVersionFromICU(): icuDir = os.path.join(topsrcdir, "intl/icu/source") if not os.path.isdir(icuDir): - raise RuntimeError("not a directory: {}".format(icuDir)) + raise RuntimeError(f"not a directory: {icuDir}") reVersion = re.compile(r'\s*cldrVersion\{"(\d+(?:\.\d+)?)"\}') @@ -2098,13 +2060,13 @@ def updateCLDRLangTags(args): def flines(filepath, encoding="utf-8"): """Open filepath and iterate over its content.""" - with open(filepath, mode="r", encoding=encoding) as f: + with open(filepath, encoding=encoding) as f: for line in f: yield line @total_ordering -class Zone(object): +class Zone: """Time zone with optional file name.""" def __init__(self, name, filename=""): @@ -2127,7 +2089,7 @@ class Zone(object): return self.name -class TzDataDir(object): +class TzDataDir: """tzdata source from a directory.""" def __init__(self, obj): @@ -2139,7 +2101,7 @@ class TzDataDir(object): self.readlines = flines -class TzDataFile(object): +class TzDataFile: """tzdata source from a file (tar or gzipped).""" def __init__(self, obj): @@ -2667,7 +2629,6 @@ def availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory): with open( os.path.join(js_src_builtin_intl_dir, "TimeZoneMapping.yaml"), - mode="r", encoding="utf-8", ) as f: time_zone_mapping = yaml.safe_load(f) @@ -2930,7 +2891,7 @@ def generateTzDataTestVersion(tzdataDir, version, testDir): println("") println(generatedFileWarning) println(tzdataVersionComment.format(version)) - println("""const tzdata = "{0}";""".format(version)) + println(f"""const tzdata = "{version}";""") println( """ @@ -3192,7 +3153,7 @@ def writeCurrencyFile(published, currencies, out): println = partial(print, file=f) println(generatedFileWarning) - println("// Version: {}".format(published)) + println(f"// Version: {published}") println( """ @@ -3209,8 +3170,8 @@ def writeCurrencyFile(published, currencies, out): sorted(currencies, key=itemgetter(0)), itemgetter(0) ): for _, minorUnits, currencyName, countryName in entries: - println(" // {} ({})".format(currencyName, countryName)) - println(" {}: {},".format(currency, minorUnits)) + println(f" // {currencyName} ({countryName})") + println(f" {currency}: {minorUnits},") println("};") @@ -3261,24 +3222,22 @@ def updateCurrency(topsrcdir, args): def writeUnicodeExtensionsMappings(println, mapping, extension): println( - """ + f""" template -static inline bool Is{0}Key(mozilla::Span key, const char (&str)[Length]) {{ - static_assert(Length == {0}KeyLength + 1, - "{0} extension key is two characters long"); +static inline bool Is{extension}Key(mozilla::Span key, const char (&str)[Length]) {{ + static_assert(Length == {extension}KeyLength + 1, + "{extension} extension key is two characters long"); return memcmp(key.data(), str, Length - 1) == 0; }} template -static inline bool Is{0}Type(mozilla::Span type, const char (&str)[Length]) {{ - static_assert(Length > {0}KeyLength + 1, - "{0} extension type contains more than two characters"); +static inline bool Is{extension}Type(mozilla::Span type, const char (&str)[Length]) {{ + static_assert(Length > {extension}KeyLength + 1, + "{extension} extension type contains more than two characters"); return type.size() == (Length - 1) && memcmp(type.data(), str, Length - 1) == 0; }} -""".format( - extension - ).rstrip( +""".rstrip( "\n" ) ) @@ -3292,8 +3251,8 @@ static inline bool Is{0}Type(mozilla::Span type, const char (&str)[L if needs_binary_search: println( - """ -static int32_t Compare{0}Type(const char* a, mozilla::Span b) {{ + f""" +static int32_t Compare{extension}Type(const char* a, mozilla::Span b) {{ MOZ_ASSERT(!std::char_traits::find(b.data(), b.size(), '\\0'), "unexpected null-character in string"); @@ -3313,45 +3272,41 @@ static int32_t Compare{0}Type(const char* a, mozilla::Span b) {{ }} template -static inline const char* Search{0}Replacement( +static inline const char* Search{extension}Replacement( const char* (&types)[Length], const char* (&aliases)[Length], mozilla::Span type) {{ auto p = std::lower_bound(std::begin(types), std::end(types), type, [](const auto& a, const auto& b) {{ - return Compare{0}Type(a, b) < 0; + return Compare{extension}Type(a, b) < 0; }}); - if (p != std::end(types) && Compare{0}Type(*p, type) == 0) {{ + if (p != std::end(types) && Compare{extension}Type(*p, type) == 0) {{ return aliases[std::distance(std::begin(types), p)]; }} return nullptr; }} -""".format( - extension - ).rstrip( +""".rstrip( "\n" ) ) println( - """ + f""" /** - * Mapping from deprecated BCP 47 {0} extension types to their preferred + * Mapping from deprecated BCP 47 {extension} extension types to their preferred * values. * * Spec: https://www.unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files * Spec: https://www.unicode.org/reports/tr35/#t_Extension */ -const char* mozilla::intl::Locale::Replace{0}ExtensionType( +const char* mozilla::intl::Locale::Replace{extension}ExtensionType( mozilla::Span key, mozilla::Span type) {{ - MOZ_ASSERT(key.size() == {0}KeyLength); - MOZ_ASSERT(IsCanonicallyCased{0}Key(key)); + MOZ_ASSERT(key.size() == {extension}KeyLength); + MOZ_ASSERT(IsCanonicallyCased{extension}Key(key)); - MOZ_ASSERT(type.size() > {0}KeyLength); - MOZ_ASSERT(IsCanonicallyCased{0}Type(type)); -""".format( - extension - ) + MOZ_ASSERT(type.size() > {extension}KeyLength); + MOZ_ASSERT(IsCanonicallyCased{extension}Type(type)); +""" ) def to_hash_key(replacements): @@ -3360,13 +3315,11 @@ const char* mozilla::intl::Locale::Replace{0}ExtensionType( def write_array(subtags, name, length): max_entries = (80 - len(" ")) // (length + len('"", ')) - println(" static const char* {}[{}] = {{".format(name, len(subtags))) + println(f" static const char* {name}[{len(subtags)}] = {{") for entries in grouper(subtags, max_entries): entries = ( - '"{}"'.format(tag).center(length + 2) - for tag in entries - if tag is not None + f'"{tag}"'.center(length + 2) for tag in entries if tag is not None ) println(" {},".format(", ".join(entries))) @@ -3387,18 +3340,13 @@ const char* mozilla::intl::Locale::Replace{0}ExtensionType( if key in key_aliases[hash_key]: continue - cond = ( - 'Is{}Key(key, "{}")'.format(extension, k) - for k in [key] + key_aliases[hash_key] - ) + cond = (f'Is{extension}Key(key, "{k}")' for k in [key] + key_aliases[hash_key]) if_kind = "if" if first_key else "else if" cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond) println( - """ - {} ({}) {{""".format( - if_kind, cond - ).strip( + f""" + {if_kind} ({cond}) {{""".strip( "\n" ) ) @@ -3414,23 +3362,19 @@ const char* mozilla::intl::Locale::Replace{0}ExtensionType( write_array(types, "types", max_len) write_array(preferred, "aliases", max_len) println( - """ - return Search{}Replacement(types, aliases, type); -""".format( - extension - ).strip( + f""" + return Search{extension}Replacement(types, aliases, type); +""".strip( "\n" ) ) else: for type, replacement in replacements: println( - """ - if (Is{}Type(type, "{}")) {{ - return "{}"; - }}""".format( - extension, type, replacement - ).strip( + f""" + if (Is{extension}Type(type, "{type}")) {{ + return "{replacement}"; + }}""".strip( "\n" ) ) @@ -3540,7 +3484,7 @@ def readICUUnitResourceFile(filepath): table[entry_key] = entry_value continue - raise Exception("unexpected line: '{}' in {}".format(line, filepath)) + raise Exception(f"unexpected line: '{line}' in {filepath}") assert len(parents) == 0, "Not all tables closed" assert len(table) == 1, "More than one root table" @@ -3579,7 +3523,7 @@ def computeSupportedUnits(all_units, sanctioned_units): def compound_unit_identifiers(): for numerator in sanctioned_units: for denominator in sanctioned_units: - yield "{}-per-{}".format(numerator, denominator) + yield f"{numerator}-per-{denominator}" supported_simple_units = {find_match(unit) for unit in sanctioned_units} assert None not in supported_simple_units @@ -3594,7 +3538,7 @@ def computeSupportedUnits(all_units, sanctioned_units): def readICUDataFilterForUnits(data_filter_file): - with open(data_filter_file, mode="r", encoding="utf-8") as f: + with open(data_filter_file, encoding="utf-8") as f: data_filter = json.load(f) # Find the rule set for the "unit_tree". @@ -3651,9 +3595,7 @@ def writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units): ) println("// prettier-ignore") - println( - "var sanctionedSimpleUnitIdentifiers = {};".format(sanctioned_units_object) - ) + println(f"var sanctionedSimpleUnitIdentifiers = {sanctioned_units_object};") sanctioned_h_file = os.path.join(intl_components_src_dir, "MeasureUnitGenerated.h") with open(sanctioned_h_file, mode="w", encoding="utf-8", newline="") as f: @@ -3683,7 +3625,7 @@ inline constexpr SimpleMeasureUnit simpleMeasureUnits[] = { ) for unit_name in sorted(sanctioned_units): - println(' {{"{}", "{}"}},'.format(find_unit_type(unit_name), unit_name)) + println(f' {{"{find_unit_type(unit_name)}", "{unit_name}"}},') println( """ @@ -3726,9 +3668,7 @@ def writeUnitTestFiles(all_units, sanctioned_units): ) println( - "const sanctionedSimpleUnitIdentifiers = {};".format( - sanctioned_units_array - ) + f"const sanctionedSimpleUnitIdentifiers = {sanctioned_units_array};" ) println(test_content) @@ -3762,11 +3702,9 @@ for (const numerator of sanctionedSimpleUnitIdentifiers) { write_test( "unit-well-formed.js", - """ -const allUnits = {}; -""".format( - all_units_array - ) + f""" +const allUnits = {all_units_array}; +""" + r""" // Test only sanctioned unit identifiers are allowed. @@ -3841,7 +3779,6 @@ def updateUnits(topsrcdir, args): with open( os.path.join(js_src_builtin_intl_dir, "SanctionedSimpleUnitIdentifiers.yaml"), - mode="r", encoding="utf-8", ) as f: sanctioned_units = yaml.safe_load(f) @@ -3865,13 +3802,13 @@ def updateUnits(topsrcdir, args): missing = supported_units - filtered_units if missing: - raise RuntimeError("Missing units: {}".format(units_to_string(missing))) + raise RuntimeError(f"Missing units: {units_to_string(missing)}") # Not exactly an error, but we currently don't have a use case where we need to support # more units than required by ECMA-402. extra = filtered_units - supported_units if extra: - raise RuntimeError("Unnecessary units: {}".format(units_to_string(extra))) + raise RuntimeError(f"Unnecessary units: {units_to_string(extra)}") writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units) @@ -3957,7 +3894,7 @@ def readICUNumberingSystemsResourceFile(filepath): table[entry_key] = entry_value continue - raise Exception("unexpected line: '{}' in {}".format(line, filepath)) + raise Exception(f"unexpected line: '{line}' in {filepath}") assert len(parents) == 0, "Not all tables closed" assert len(table) == 1, "More than one root table" @@ -4012,9 +3949,7 @@ def writeNumberingSystemFiles(numbering_systems): println("#define NUMBERING_SYSTEMS_WITH_SIMPLE_DIGIT_MAPPINGS \\") println( "{}".format( - ", \\\n".join( - ' "{}"'.format(name) for name in simple_numbering_systems - ) + ", \\\n".join(f' "{name}"' for name in simple_numbering_systems) ) ) println("// clang-format on") @@ -4033,13 +3968,11 @@ def writeNumberingSystemFiles(numbering_systems): println(generatedFileWarning) println( - """ -// source: CLDR file common/bcp47/number.xml; version CLDR {}. + f""" +// source: CLDR file common/bcp47/number.xml; version CLDR {readCLDRVersionFromICU()}. // https://github.com/unicode-org/cldr/blob/master/common/bcp47/number.xml // https://github.com/unicode-org/cldr/blob/master/common/supplemental/numberingSystems.xml -""".format( - readCLDRVersionFromICU() - ).rstrip() +""".rstrip() ) numbering_systems_object = json.dumps( @@ -4049,7 +3982,7 @@ def writeNumberingSystemFiles(numbering_systems): sort_keys=True, ensure_ascii=False, ) - println("const numberingSystems = {};".format(numbering_systems_object)) + println(f"const numberingSystems = {numbering_systems_object};") def updateNumberingSystems(topsrcdir, args): @@ -4059,7 +3992,6 @@ def updateNumberingSystems(topsrcdir, args): with open( os.path.join(js_src_builtin_intl_dir, "NumberingSystems.yaml"), - mode="r", encoding="utf-8", ) as f: numbering_systems = yaml.safe_load(f) @@ -4078,14 +4010,14 @@ def updateNumberingSystems(topsrcdir, args): # something is broken in ICU. assert all_numbering_systems_simple_digits.issuperset( numbering_systems - ), "{}".format(numbering_systems.difference(all_numbering_systems_simple_digits)) + ), f"{numbering_systems.difference(all_numbering_systems_simple_digits)}" # Assert the spec requires support for all numbering systems with simple digit mappings. If # this assertion fails, file a PR at to include any new # numbering systems. - assert all_numbering_systems_simple_digits.issubset(numbering_systems), "{}".format( - all_numbering_systems_simple_digits.difference(numbering_systems) - ) + assert all_numbering_systems_simple_digits.issubset( + numbering_systems + ), f"{all_numbering_systems_simple_digits.difference(numbering_systems)}" writeNumberingSystemFiles(all_numbering_systems) diff --git a/js/src/devtools/automation/autospider.py b/js/src/devtools/automation/autospider.py index edd7c5597fab..8260b4c7c122 100755 --- a/js/src/devtools/automation/autospider.py +++ b/js/src/devtools/automation/autospider.py @@ -183,7 +183,7 @@ MAKE = env.get("MAKE", "make") PYTHON = sys.executable for d in DIR._fields: - info("DIR.{name} = {dir}".format(name=d, dir=getattr(DIR, d))) + info(f"DIR.{d} = {getattr(DIR, d)}") def ensure_dir_exists( @@ -428,17 +428,17 @@ if use_minidump: if injector_lib is None: use_minidump = False - info("use_minidump is {}".format(use_minidump)) + info(f"use_minidump is {use_minidump}") info(" MINIDUMP_SAVE_PATH={}".format(env["MINIDUMP_SAVE_PATH"])) - info(" injector lib is {}".format(injector_lib)) + info(f" injector lib is {injector_lib}") info(" MINIDUMP_STACKWALK={}".format(env.get("MINIDUMP_STACKWALK"))) mozconfig = os.path.join(DIR.source, "mozconfig.autospider") -CONFIGURE_ARGS += " --prefix={OBJDIR}/dist".format(OBJDIR=quote(OBJDIR)) +CONFIGURE_ARGS += f" --prefix={quote(OBJDIR)}/dist" # Generate a mozconfig. -with open(mozconfig, "wt") as fh: +with open(mozconfig, "w") as fh: if AUTOMATION and platform.system() == "Windows": fh.write('. "$topsrcdir/build/mozconfig.clang-cl"\n') fh.write("ac_add_options --enable-project=js\n") @@ -497,7 +497,7 @@ def run_jsapitests(args): " ".join(["jsapi-tests"] + args) ) ) - print("Return code: {}".format(st)) + print(f"Return code: {st}") return st @@ -549,11 +549,11 @@ jstest_workers = worker_max jittest_workers = worker_max if platform.system() == "Windows": jstest_workers = min(worker_max, 16) - env["JSTESTS_EXTRA_ARGS"] = "-j{} ".format(jstest_workers) + env.get( + env["JSTESTS_EXTRA_ARGS"] = f"-j{jstest_workers} " + env.get( "JSTESTS_EXTRA_ARGS", "" ) jittest_workers = min(worker_max, 8) - env["JITTEST_EXTRA_ARGS"] = "-j{} ".format(jittest_workers) + env.get( + env["JITTEST_EXTRA_ARGS"] = f"-j{jittest_workers} " + env.get( "JITTEST_EXTRA_ARGS", "" ) print( diff --git a/js/src/devtools/gc/gc-test.py b/js/src/devtools/gc/gc-test.py index 80a8d78b7700..1f9874f8d299 100644 --- a/js/src/devtools/gc/gc-test.py +++ b/js/src/devtools/gc/gc-test.py @@ -185,7 +185,7 @@ if __name__ == "__main__": if OPTIONS.baseline_path: baseline_map = [] - fh = open(OPTIONS.baseline_path, "r") + fh = open(OPTIONS.baseline_path) baseline_map = json.load(fh) fh.close() compare(current=bench_map, baseline=baseline_map) diff --git a/js/src/devtools/rootAnalysis/analyze.py b/js/src/devtools/rootAnalysis/analyze.py index ddde20f857f9..961d2d36ad36 100755 --- a/js/src/devtools/rootAnalysis/analyze.py +++ b/js/src/devtools/rootAnalysis/analyze.py @@ -262,7 +262,7 @@ def run_job(name, config): raise if final_status != 0: - raise Exception("job {} returned status {}".format(name, final_status)) + raise Exception(f"job {name} returned status {final_status}") def spawn_command(cmdspec, job, name, config): diff --git a/js/src/devtools/rootAnalysis/mach_commands.py b/js/src/devtools/rootAnalysis/mach_commands.py index ee588de1e831..4036d99ebaa0 100644 --- a/js/src/devtools/rootAnalysis/mach_commands.py +++ b/js/src/devtools/rootAnalysis/mach_commands.py @@ -325,7 +325,7 @@ def gather_hazard_data(command_context, **kwargs): work_dir = get_work_dir(command_context, project, kwargs["work_dir"]) ensure_dir_exists(work_dir) - with open(os.path.join(work_dir, "defaults.py"), "wt") as fh: + with open(os.path.join(work_dir, "defaults.py"), "w") as fh: data = textwrap.dedent( """\ analysis_scriptdir = "{script_dir}" @@ -545,7 +545,7 @@ def annotated_source(filename, query): line0 = int(line0) line1 = int(line1) - fh = open(filename, "rt") + fh = open(filename) out = "
"
     for lineno, line in enumerate(fh, 1):
diff --git a/js/src/devtools/rootAnalysis/run-test.py b/js/src/devtools/rootAnalysis/run-test.py
index b4835efec5e4..9301fd8fbcc6 100755
--- a/js/src/devtools/rootAnalysis/run-test.py
+++ b/js/src/devtools/rootAnalysis/run-test.py
@@ -131,7 +131,7 @@ for path in tests:
     os.chdir(outdir)
     for xdb in glob("*.xdb"):
         os.unlink(xdb)
-    print("START TEST {}".format(name), flush=True)
+    print(f"START TEST {name}", flush=True)
     testpath = os.path.join(indir, "test.py")
     testscript = open(testpath).read()
     testcode = compile(testscript, testpath, "exec")
diff --git a/js/src/devtools/rootAnalysis/t/graph/test.py b/js/src/devtools/rootAnalysis/t/graph/test.py
index f78500f200eb..5589b784bfdf 100644
--- a/js/src/devtools/rootAnalysis/t/graph/test.py
+++ b/js/src/devtools/rootAnalysis/t/graph/test.py
@@ -24,7 +24,7 @@ assert callgraph.calleeGraph[f][h]
 assert callgraph.calleeGraph[g][f]
 assert callgraph.calleeGraph[g][h]
 
-node = ["void n{}(int32)".format(i) for i in range(10)]
+node = [f"void n{i}(int32)" for i in range(10)]
 mnode = [callgraph.unmangledToMangled.get(f) for f in node]
 for src, dst in [
     (1, 2),
@@ -51,4 +51,4 @@ rroots = set(
 )
 assert len(set([node[1], node[2]]) & rroots) == 1
 assert len(set([node[4], node[5]]) & rroots) == 1
-assert len(rroots) == 4, "rroots = {}".format(rroots)  # n1, n4, f, self_recursive
+assert len(rroots) == 4, f"rroots = {rroots}"  # n1, n4, f, self_recursive
diff --git a/js/src/devtools/rootAnalysis/t/testlib.py b/js/src/devtools/rootAnalysis/t/testlib.py
index e08b236e4f39..7d7bf181512d 100644
--- a/js/src/devtools/rootAnalysis/t/testlib.py
+++ b/js/src/devtools/rootAnalysis/t/testlib.py
@@ -38,7 +38,7 @@ def extract_unmangled(func):
     return func.split("$")[-1]
 
 
-class Test(object):
+class Test:
     def __init__(self, indir, outdir, cfg, verbose=0):
         self.indir = indir
         self.outdir = outdir
@@ -56,12 +56,7 @@ class Test(object):
         env["CCACHE_DISABLE"] = "1"
         if "-fexceptions" not in options and "-fno-exceptions" not in options:
             options += " -fno-exceptions"
-        cmd = "{CXX} -c {source} -O3 -std=c++17 -fplugin={sixgill} -fplugin-arg-xgill-mangle=1 {options}".format(  # NOQA: E501
-            source=self.infile(source),
-            CXX=self.cfg.cxx,
-            sixgill=self.cfg.sixgill_plugin,
-            options=options,
-        )
+        cmd = f"{self.cfg.cxx} -c {self.infile(source)} -O3 -std=c++17 -fplugin={self.cfg.sixgill_plugin} -fplugin-arg-xgill-mangle=1 {options}"
         if self.cfg.verbose > 0:
             print("Running %s" % cmd)
         subprocess.check_call(["sh", "-c", cmd])
@@ -89,12 +84,10 @@ class Test(object):
 
     def run_analysis_script(self, startPhase="gcTypes", upto=None):
         open("defaults.py", "w").write(
-            """\
+            f"""\
 analysis_scriptdir = '{scriptdir}'
-sixgill_bin = '{bindir}'
-""".format(
-                scriptdir=scriptdir, bindir=self.cfg.sixgill_bin
-            )
+sixgill_bin = '{self.cfg.sixgill_bin}'
+"""
         )
         cmd = [
             sys.executable,
@@ -118,7 +111,7 @@ sixgill_bin = '{bindir}'
 
     def load_text_file(self, filename, extract=lambda l: l):
         fullpath = os.path.join(self.outdir, filename)
-        values = (extract(line.strip()) for line in open(fullpath, "r"))
+        values = (extract(line.strip()) for line in open(fullpath))
         return list(filter(lambda _: _ is not None, values))
 
     def load_json_file(self, filename, reviver=None):
diff --git a/js/src/frontend/GenerateReservedWords.py b/js/src/frontend/GenerateReservedWords.py
index 5a4456389e7e..3811edcaed7e 100644
--- a/js/src/frontend/GenerateReservedWords.py
+++ b/js/src/frontend/GenerateReservedWords.py
@@ -13,7 +13,7 @@ def read_reserved_word_list(
 
     reserved_word_list = []
     index = 0
-    with open(filename, "r") as f:
+    with open(filename) as f:
         for line in f:
             m = macro_pat.search(line)
             if m:
@@ -107,22 +107,22 @@ def generate_letter_switch(opt, unprocessed_columns, reserved_word_list, columns
         index, word = reserved_word_list[0]
 
         if unprocessed_columns == 0:
-            line(opt, "JSRW_GOT_MATCH({}) /* {} */".format(index, word))
+            line(opt, f"JSRW_GOT_MATCH({index}) /* {word} */")
             return
 
         if unprocessed_columns > opt["char_tail_test_threshold"]:
-            line(opt, "JSRW_TEST_GUESS({}) /* {} */".format(index, word))
+            line(opt, f"JSRW_TEST_GUESS({index}) /* {word} */")
             return
 
         conds = []
         for column in columns[0:unprocessed_columns]:
             quoted = repr(word[column])
-            conds.append("JSRW_AT({})=={}".format(column, quoted))
+            conds.append(f"JSRW_AT({column})=={quoted}")
 
         line(opt, "if ({}) {{".format(" && ".join(conds)))
 
         indent(opt)
-        line(opt, "JSRW_GOT_MATCH({}) /* {} */".format(index, word))
+        line(opt, f"JSRW_GOT_MATCH({index}) /* {word} */")
         dedent(opt)
 
         line(opt, "}")
@@ -143,14 +143,14 @@ def generate_letter_switch(opt, unprocessed_columns, reserved_word_list, columns
     list_per_column = split_list_per_column(reserved_word_list, optimal_column)
 
     if not use_if:
-        line(opt, "switch (JSRW_AT({})) {{".format(optimal_column))
+        line(opt, f"switch (JSRW_AT({optimal_column})) {{")
 
     for char, reserved_word_list_per_column in list_per_column:
         quoted = repr(char)
         if use_if:
-            line(opt, "if (JSRW_AT({}) == {}) {{".format(optimal_column, quoted))
+            line(opt, f"if (JSRW_AT({optimal_column}) == {quoted}) {{")
         else:
-            line(opt, "  case {}:".format(quoted))
+            line(opt, f"  case {quoted}:")
 
         indent(opt)
         generate_letter_switch(
@@ -185,12 +185,10 @@ def generate_switch(opt, reserved_word_list):
     line(opt, "/*")
     line(
         opt,
-        " * Generating switch for the list of {} entries:".format(
-            len(reserved_word_list)
-        ),
+        f" * Generating switch for the list of {len(reserved_word_list)} entries:",
     )
     for index, word in reserved_word_list:
-        line(opt, " * {}".format(word))
+        line(opt, f" * {word}")
     line(opt, " */")
 
     list_per_length = split_list_per_length(reserved_word_list)
@@ -204,9 +202,9 @@ def generate_switch(opt, reserved_word_list):
 
     for length, reserved_word_list_per_length in list_per_length:
         if use_if:
-            line(opt, "if (JSRW_LENGTH() == {}) {{".format(length))
+            line(opt, f"if (JSRW_LENGTH() == {length}) {{")
         else:
-            line(opt, "  case {}:".format(length))
+            line(opt, f"  case {length}:")
 
         indent(opt)
         generate_letter_switch(opt, length, reserved_word_list_per_length)
diff --git a/js/src/frontend/align_stack_comment.py b/js/src/frontend/align_stack_comment.py
index 6e279a90c632..60895f9630ff 100755
--- a/js/src/frontend/align_stack_comment.py
+++ b/js/src/frontend/align_stack_comment.py
@@ -49,18 +49,14 @@ def align_stack_comment(path):
 
                 if head_len > ALIGNMENT_COLUMN:
                     print(
-                        "Warning: line {} overflows from alignment column {}: {}".format(
-                            line_num, ALIGNMENT_COLUMN, head_len
-                        ),
+                        f"Warning: line {line_num} overflows from alignment column {ALIGNMENT_COLUMN}: {head_len}",
                         file=sys.stderr,
                     )
 
                 line_len = max(head_len, ALIGNMENT_COLUMN) + comment_len
                 if line_len > MAX_CHARS_PER_LINE:
                     print(
-                        "Warning: line {} overflows from {} chars: {}".format(
-                            line_num, MAX_CHARS_PER_LINE, line_len
-                        ),
+                        f"Warning: line {line_num} overflows from {MAX_CHARS_PER_LINE} chars: {line_len}",
                         file=sys.stderr,
                     )
 
@@ -78,15 +74,15 @@ def align_stack_comment(path):
                 lines.append(line)
 
         print(
-            "Info: Minimum column number for [stack]: {}".format(max_head_len),
+            f"Info: Minimum column number for [stack]: {max_head_len}",
             file=sys.stderr,
         )
         print(
-            "Info: Alignment column number for [stack]: {}".format(ALIGNMENT_COLUMN),
+            f"Info: Alignment column number for [stack]: {ALIGNMENT_COLUMN}",
             file=sys.stderr,
         )
         print(
-            "Info: Max length of stack transition comments: {}".format(max_comment_len),
+            f"Info: Max length of stack transition comments: {max_comment_len}",
             file=sys.stderr,
         )
 
diff --git a/js/src/gdb/mozilla/ExecutableAllocator.py b/js/src/gdb/mozilla/ExecutableAllocator.py
index 5187e2d1f182..ceb121fcfd60 100644
--- a/js/src/gdb/mozilla/ExecutableAllocator.py
+++ b/js/src/gdb/mozilla/ExecutableAllocator.py
@@ -17,7 +17,7 @@ from mozilla.prettyprinters import pretty_printer, ptr_pretty_printer
 mozilla.prettyprinters.clear_module_printers(__name__)
 
 
-class jsjitExecutableAllocatorCache(object):
+class jsjitExecutableAllocatorCache:
     """Cache information about the ExecutableAllocator type for this objfile."""
 
     def __init__(self):
@@ -36,7 +36,7 @@ class jsjitExecutableAllocatorCache(object):
 
 
 @pretty_printer("js::jit::ExecutableAllocator")
-class jsjitExecutableAllocator(object):
+class jsjitExecutableAllocator:
     def __init__(self, value, cache):
         if not cache.mod_ExecutableAllocator:
             cache.mod_ExecutableAllocator = jsjitExecutableAllocatorCache()
@@ -49,7 +49,7 @@ class jsjitExecutableAllocator(object):
     def __iter__(self):
         return self.PoolIterator(self)
 
-    class PoolIterator(object):
+    class PoolIterator:
         def __init__(self, allocator):
             self.allocator = allocator
             self.entryType = allocator.cache.ExecutablePool.pointer()
diff --git a/js/src/gdb/mozilla/GCCellPtr.py b/js/src/gdb/mozilla/GCCellPtr.py
index e42ecfa8939b..1b755abf6be4 100644
--- a/js/src/gdb/mozilla/GCCellPtr.py
+++ b/js/src/gdb/mozilla/GCCellPtr.py
@@ -15,7 +15,7 @@ mozilla.prettyprinters.clear_module_printers(__name__)
 # Cache information about the types for this objfile.
 
 
-class GCCellPtrTypeCache(object):
+class GCCellPtrTypeCache:
     def __init__(self, cache):
         self.TraceKind_t = gdb.lookup_type("JS::TraceKind")
         self.AllocKind_t = gdb.lookup_type("js::gc::AllocKind")
@@ -76,7 +76,7 @@ class GCCellPtrTypeCache(object):
 
 
 @pretty_printer("JS::GCCellPtr")
-class GCCellPtr(object):
+class GCCellPtr:
     def __init__(self, value, cache):
         self.value = value
         if not cache.mod_GCCellPtr:
@@ -120,6 +120,4 @@ class GCCellPtr(object):
             # Map the AllocKind to a TraceKind.
             kind = self.cache.mod_GCCellPtr.alloc_kind_to_trace_kind[alloc_idx]
         type_name = self.cache.mod_GCCellPtr.trace_kind_to_type[int(kind)]
-        return "JS::GCCellPtr(({}*) {})".format(
-            type_name, ptr.cast(self.cache.void_ptr_t)
-        )
+        return f"JS::GCCellPtr(({type_name}*) {ptr.cast(self.cache.void_ptr_t)})"
diff --git a/js/src/gdb/mozilla/Interpreter.py b/js/src/gdb/mozilla/Interpreter.py
index 825ae40e9d9a..c32e4cf8172a 100644
--- a/js/src/gdb/mozilla/Interpreter.py
+++ b/js/src/gdb/mozilla/Interpreter.py
@@ -13,7 +13,7 @@ prettyprinters.clear_module_printers(__name__)
 from mozilla.prettyprinters import pretty_printer
 
 
-class InterpreterTypeCache(object):
+class InterpreterTypeCache:
     # Cache information about the Interpreter types for this objfile.
     def __init__(self):
         self.tValue = gdb.lookup_type("JS::Value")
@@ -32,7 +32,7 @@ class InterpreterTypeCache(object):
 
 
 @pretty_printer("js::InterpreterRegs")
-class InterpreterRegs(object):
+class InterpreterRegs:
     def __init__(self, value, cache):
         self.value = value
         self.cache = cache
@@ -48,11 +48,11 @@ class InterpreterRegs(object):
         slots = (self.value["fp_"] + 1).cast(self.itc.tValue.pointer())
         sp = "sp = fp_.slots() + {}".format(self.value["sp"] - slots)
         pc = "pc = {}".format(self.value["pc"])
-        return "{{ {}, {}, {} }}".format(fp_, sp, pc)
+        return f"{{ {fp_}, {sp}, {pc} }}"
 
 
 @pretty_printer("js::AbstractFramePtr")
-class AbstractFramePtr(object):
+class AbstractFramePtr:
     Tag_InterpreterFrame = 0x0
     Tag_BaselineFrame = 0x1
     Tag_RematerializedFrame = 0x2
@@ -82,7 +82,7 @@ class AbstractFramePtr(object):
         if tag == AbstractFramePtr.Tag_WasmDebugFrame:
             label = "js::wasm::DebugFrame"
             ptr = ptr.cast(self.itc.tDebugFrame.pointer())
-        return "AbstractFramePtr (({} *) {})".format(label, ptr)
+        return f"AbstractFramePtr (({label} *) {ptr})"
 
     # Provide the ptr_ field as a child, so it prints after the pretty string
     # provided above.
diff --git a/js/src/gdb/mozilla/IonGraph.py b/js/src/gdb/mozilla/IonGraph.py
index 639baf3acee0..51ec8f7243c5 100644
--- a/js/src/gdb/mozilla/IonGraph.py
+++ b/js/src/gdb/mozilla/IonGraph.py
@@ -27,7 +27,7 @@ mozilla.prettyprinters.clear_module_printers(__name__)
 # Cache information about the JSString type for this objfile.
 
 
-class jsvmPrinterCache(object):
+class jsvmPrinterCache:
     def __init__(self):
         self.d = None
 
@@ -45,13 +45,13 @@ class jsvmPrinterCache(object):
 # iongraph command, which uses the jsvmLSprinter.
 
 
-class ModuleCache(object):
+class ModuleCache:
     def __init__(self):
         self.mod_IonGraph = None
 
 
 @pretty_printer("js::vm::LSprinter")
-class jsvmLSprinter(object):
+class jsvmLSprinter:
     def __init__(self, value, cache):
         self.value = value
         if not cache.mod_IonGraph:
diff --git a/js/src/gdb/mozilla/JSObject.py b/js/src/gdb/mozilla/JSObject.py
index 95accc93b957..7370b80894e9 100644
--- a/js/src/gdb/mozilla/JSObject.py
+++ b/js/src/gdb/mozilla/JSObject.py
@@ -16,7 +16,7 @@ from mozilla.prettyprinters import ptr_pretty_printer, ref_pretty_printer
 prettyprinters.clear_module_printers(__name__)
 
 
-class JSObjectTypeCache(object):
+class JSObjectTypeCache:
     def __init__(self):
         object_flag = gdb.lookup_type("js::ObjectFlag")
         self.objectflag_IsUsedAsPrototype = prettyprinters.enum_value(
@@ -65,7 +65,7 @@ class JSObjectPtrOrRef(prettyprinters.Pointer):
             class_name = m.group(1)
 
         if non_native:
-            return "[object {}]".format(class_name)
+            return f"[object {class_name}]"
         else:
             flags = shape["objectFlags_"]["flags_"]
             used_as_prototype = bool(flags & self.otc.objectflag_IsUsedAsPrototype)
diff --git a/js/src/gdb/mozilla/JSString.py b/js/src/gdb/mozilla/JSString.py
index 3c758e0352e9..7efe1812f107 100644
--- a/js/src/gdb/mozilla/JSString.py
+++ b/js/src/gdb/mozilla/JSString.py
@@ -19,7 +19,7 @@ except ValueError:  # yuck, we are in Python 2.x, so chr() is 8-bit
 mozilla.prettyprinters.clear_module_printers(__name__)
 
 
-class JSStringTypeCache(object):
+class JSStringTypeCache:
     # Cache information about the JSString type for this objfile.
     def __init__(self, cache):
         dummy = gdb.Value(0).cast(cache.JSString_ptr_t)
diff --git a/js/src/gdb/mozilla/JSSymbol.py b/js/src/gdb/mozilla/JSSymbol.py
index db96898c9151..f2cf97ab7419 100644
--- a/js/src/gdb/mozilla/JSSymbol.py
+++ b/js/src/gdb/mozilla/JSSymbol.py
@@ -27,11 +27,11 @@ class JSSymbolPtr(mozilla.prettyprinters.Pointer):
         code = int(self.value["code_"]) & 0xFFFFFFFF
         desc = str(get_header_ptr(self.value, self.cache.JSString_ptr_t))
         if code == InSymbolRegistry:
-            return "Symbol.for({})".format(desc)
+            return f"Symbol.for({desc})"
         elif code == UniqueSymbol:
-            return "Symbol({})".format(desc)
+            return f"Symbol({desc})"
         elif code == PrivateNameSymbol:
-            return "#{}".format(desc)
+            return f"#{desc}"
         else:
             # Well-known symbol. Strip off the quotes added by the JSString *
             # pretty-printer.
diff --git a/js/src/gdb/mozilla/PropertyKey.py b/js/src/gdb/mozilla/PropertyKey.py
index 517976a6da95..e5cea15d3f2f 100644
--- a/js/src/gdb/mozilla/PropertyKey.py
+++ b/js/src/gdb/mozilla/PropertyKey.py
@@ -13,7 +13,7 @@ mozilla.prettyprinters.clear_module_printers(__name__)
 
 
 @pretty_printer("JS::PropertyKey")
-class PropertyKey(object):
+class PropertyKey:
     # Since people don't always build with macro debugging info, I can't
     # think of any way to avoid copying these values here, short of using
     # inferior calls for every operation (which, I hear, is broken from
diff --git a/js/src/gdb/mozilla/Root.py b/js/src/gdb/mozilla/Root.py
index fa80f3fec640..37e3f927141e 100644
--- a/js/src/gdb/mozilla/Root.py
+++ b/js/src/gdb/mozilla/Root.py
@@ -12,7 +12,7 @@ from mozilla.prettyprinters import template_pretty_printer
 mozilla.prettyprinters.clear_module_printers(__name__)
 
 
-class Common(object):
+class Common:
     # Common base class for all the rooting template pretty-printers. All these
     # templates have one member holding the referent (or a pointer to it), so
     # there's not much to it.
diff --git a/js/src/gdb/mozilla/jsop.py b/js/src/gdb/mozilla/jsop.py
index 635acb752856..d7c71288af18 100644
--- a/js/src/gdb/mozilla/jsop.py
+++ b/js/src/gdb/mozilla/jsop.py
@@ -14,7 +14,7 @@ from mozilla.prettyprinters import pretty_printer, ptr_pretty_printer
 mozilla.prettyprinters.clear_module_printers(__name__)
 
 
-class JSOpTypeCache(object):
+class JSOpTypeCache:
     # Cache information about the JSOp type for this objfile.
     def __init__(self, cache):
         self.tJSOp = gdb.lookup_type("JSOp")
@@ -27,7 +27,7 @@ class JSOpTypeCache(object):
 
 
 @pretty_printer("JSOp")
-class JSOp(object):
+class JSOp:
     def __init__(self, value, cache):
         self.value = value
         self.cache = cache
@@ -43,7 +43,7 @@ class JSOp(object):
         fields = self.jotc.tJSOp.fields()
         if idx < len(fields):
             return fields[idx].name
-        return "(JSOp) {:d}".format(idx)
+        return f"(JSOp) {idx:d}"
 
 
 @ptr_pretty_printer("jsbytecode")
@@ -57,4 +57,4 @@ class JSBytecodePtr(mozilla.prettyprinters.Pointer):
             opcode = str(self.value.dereference().cast(self.jotc.tJSOp))
         except Exception:
             opcode = "bad pc"
-        return "{} ({})".format(self.value.cast(self.cache.void_ptr_t), opcode)
+        return f"{self.value.cast(self.cache.void_ptr_t)} ({opcode})"
diff --git a/js/src/gdb/mozilla/jsval.py b/js/src/gdb/mozilla/jsval.py
index ffabf6004f16..2cc85f59253d 100644
--- a/js/src/gdb/mozilla/jsval.py
+++ b/js/src/gdb/mozilla/jsval.py
@@ -19,7 +19,7 @@ mozilla.prettyprinters.clear_module_printers(__name__)
 # formats handled below.
 
 
-class Box(object):
+class Box:
     def __init__(self, asBits, jtc):
         self.asBits = asBits
         self.jtc = jtc
@@ -90,7 +90,7 @@ class Nunbox(Box):
         return gdb.Value(self.asBits & Nunbox.PAYLOAD_MASK)
 
 
-class JSValueTypeCache(object):
+class JSValueTypeCache:
     # Cache information about the Value type for this objfile.
 
     def __init__(self, cache):
@@ -128,7 +128,7 @@ class JSValueTypeCache(object):
 
 
 @pretty_printer("JS::Value")
-class JSValue(object):
+class JSValue:
     def __init__(self, value, cache):
         # Save the generic typecache, and create our own, if we haven't already.
         self.cache = cache
diff --git a/js/src/gdb/mozilla/prettyprinters.py b/js/src/gdb/mozilla/prettyprinters.py
index 12847cae7ca2..e8f358c4f5e1 100644
--- a/js/src/gdb/mozilla/prettyprinters.py
+++ b/js/src/gdb/mozilla/prettyprinters.py
@@ -204,7 +204,7 @@ class NotSpiderMonkeyObjfileError(TypeError):
 # metadata in the TypeCache's mod_JSString attribute.
 
 
-class TypeCache(object):
+class TypeCache:
     def __init__(self, objfile):
         self.objfile = objfile
 
@@ -386,7 +386,7 @@ def lookup_for_objfile(objfile):
 #     including the type name and address, as string contents.
 
 
-class Pointer(object):
+class Pointer:
     def __new__(cls, value, cache):
         # Don't try to provide pretty-printers for NULL pointers.
         if value.type.strip_typedefs().code == gdb.TYPE_CODE_PTR and value == 0:
diff --git a/js/src/gdb/mozilla/unwind.py b/js/src/gdb/mozilla/unwind.py
index a9f99d47ecf9..72ba89a5c7b6 100644
--- a/js/src/gdb/mozilla/unwind.py
+++ b/js/src/gdb/mozilla/unwind.py
@@ -59,7 +59,7 @@ SizeOfFramePrefix = {
 
 # We cannot have semi-colon as identifier names, so use a colon instead,
 # and forward the name resolution to the type cache class.
-class UnwinderTypeCacheFrameType(object):
+class UnwinderTypeCacheFrameType:
     def __init__(self, tc):
         self.tc = tc
 
@@ -144,7 +144,7 @@ class UnwinderTypeCache(TypeCache):
             self.frame_class_types[enumval] = class_type.pointer()
 
 
-class FrameSymbol(object):
+class FrameSymbol:
     "A symbol/value pair as expected from gdb frame decorators."
 
     def __init__(self, sym, val):
@@ -253,7 +253,7 @@ class JitFrameDecorator(FrameDecorator):
         return result
 
 
-class SpiderMonkeyFrameFilter(object):
+class SpiderMonkeyFrameFilter:
     "A frame filter for SpiderMonkey."
 
     # |state_holder| is either None, or an instance of
@@ -280,7 +280,7 @@ class SpiderMonkeyFrameFilter(object):
         return imap(self.maybe_wrap_frame, frame_iter)
 
 
-class SpiderMonkeyFrameId(object):
+class SpiderMonkeyFrameId:
     "A frame id class, as specified by the gdb unwinder API."
 
     def __init__(self, sp, pc):
@@ -288,7 +288,7 @@ class SpiderMonkeyFrameId(object):
         self.pc = pc
 
 
-class UnwinderState(object):
+class UnwinderState:
     """This holds all the state needed during a given unwind.  Each time a
     new unwind is done, a new instance of this class is created.  It
     keeps track of all the state needed to unwind JIT frames.  Note that
diff --git a/js/src/gdb/progressbar.py b/js/src/gdb/progressbar.py
index 04be825c9557..eae9016ecf53 100644
--- a/js/src/gdb/progressbar.py
+++ b/js/src/gdb/progressbar.py
@@ -9,7 +9,7 @@ import sys
 import time
 
 
-class ProgressBar(object):
+class ProgressBar:
     def __init__(self, label, limit, label_width=12):
         self.label = label
         self.limit = limit
diff --git a/js/src/gdb/run-tests.py b/js/src/gdb/run-tests.py
index 4989577bced1..517282735445 100644
--- a/js/src/gdb/run-tests.py
+++ b/js/src/gdb/run-tests.py
@@ -58,7 +58,7 @@ def make_shell_cmd(l):
 
 # An instance of this class collects the lists of passing, failing, and
 # timing-out tests, runs the progress bar, and prints a summary at the end.
-class Summary(object):
+class Summary:
     class SummaryBar(progressbar.ProgressBar):
         def __init__(self, limit):
             super(Summary.SummaryBar, self).__init__("", limit, 24)
diff --git a/js/src/gdb/taskpool.py b/js/src/gdb/taskpool.py
index 38254af6b32d..304e3c1bdf3d 100644
--- a/js/src/gdb/taskpool.py
+++ b/js/src/gdb/taskpool.py
@@ -11,7 +11,7 @@ import time
 from subprocess import PIPE, Popen
 
 
-class TaskPool(object):
+class TaskPool:
     # Run a series of subprocesses. Try to keep up to a certain number going in
     # parallel at any given time. Enforce time limits.
     #
@@ -25,7 +25,7 @@ class TaskPool(object):
 
     # A task we should run in a subprocess. Users should subclass this and
     # fill in the methods as given.
-    class Task(object):
+    class Task:
         def __init__(self):
             self.pipe = None
             self.start_time = None
@@ -78,7 +78,7 @@ class TaskPool(object):
     def run_all(self):
         # The currently running tasks: a set of Task instances.
         running = set()
-        with open(os.devnull, "r") as devnull:
+        with open(os.devnull) as devnull:
             while True:
                 while len(running) < self.job_limit and self.next_pending:
                     task = self.next_pending
diff --git a/js/src/gdb/tests/enum-printers.py b/js/src/gdb/tests/enum-printers.py
index 105ff00e5931..617145c7a003 100644
--- a/js/src/gdb/tests/enum-printers.py
+++ b/js/src/gdb/tests/enum-printers.py
@@ -5,7 +5,7 @@ import mozilla.prettyprinters
 
 
 @mozilla.prettyprinters.pretty_printer("unscoped_no_storage")
-class UnscopedNoStoragePrinter(object):
+class UnscopedNoStoragePrinter:
     def __init__(self, value, cache):
         pass
 
@@ -14,7 +14,7 @@ class UnscopedNoStoragePrinter(object):
 
 
 @mozilla.prettyprinters.pretty_printer("unscoped_with_storage")
-class UnscopedWithStoragePrinter(object):
+class UnscopedWithStoragePrinter:
     def __init__(self, value, cache):
         pass
 
@@ -23,7 +23,7 @@ class UnscopedWithStoragePrinter(object):
 
 
 @mozilla.prettyprinters.pretty_printer("scoped_no_storage")
-class ScopedNoStoragePrinter(object):
+class ScopedNoStoragePrinter:
     def __init__(self, value, cache):
         pass
 
@@ -32,7 +32,7 @@ class ScopedNoStoragePrinter(object):
 
 
 @mozilla.prettyprinters.pretty_printer("scoped_with_storage")
-class ScopedWithStoragePrinter(object):
+class ScopedWithStoragePrinter:
     def __init__(self, value, cache):
         pass
 
diff --git a/js/src/gdb/tests/typedef-printers.py b/js/src/gdb/tests/typedef-printers.py
index 888379ee6378..bbf27874ee7d 100644
--- a/js/src/gdb/tests/typedef-printers.py
+++ b/js/src/gdb/tests/typedef-printers.py
@@ -6,7 +6,7 @@ import mozilla.prettyprinters
 
 
 @mozilla.prettyprinters.pretty_printer("my_typedef")
-class my_typedef(object):
+class my_typedef:
     def __init__(self, value, cache):
         pass
 
diff --git a/js/src/irregexp/import-irregexp.py b/js/src/irregexp/import-irregexp.py
index 96fe7b0cb5c6..dd95a1fe7e4f 100755
--- a/js/src/irregexp/import-irregexp.py
+++ b/js/src/irregexp/import-irregexp.py
@@ -48,7 +48,7 @@ def copy_and_update_includes(src_path, dst_path):
         "special-case.h",
     ]
 
-    src = open(str(src_path), "r")
+    src = open(str(src_path))
     dst = open(str(dst_path), "w")
 
     # 1. Rewrite includes of V8 regexp headers:
diff --git a/js/src/jit-test/jit_test.py b/js/src/jit-test/jit_test.py
index 83adc5a6a524..19cf78066d93 100755
--- a/js/src/jit-test/jit_test.py
+++ b/js/src/jit-test/jit_test.py
@@ -61,16 +61,16 @@ def choose_item(jobs, max_items):
         flags = ""
         if len(job.jitflags) != 0:
             flags = "({})".format(" ".join(job.jitflags))
-        return "{} {}".format(job.path, flags)
+        return f"{job.path} {flags}"
 
     for i, job in enumerate(jobs, 1):
-        print("{}) {}".format(i, display_job(job)))
+        print(f"{i}) {display_job(job)}")
 
     item = read_input("Which one:\n")
     try:
         item = int(item)
         if item > job_count or item < 1:
-            raise Exception("Input isn't between 1 and {}".format(job_count))
+            raise Exception(f"Input isn't between 1 and {job_count}")
     except ValueError:
         raise Exception("Unrecognized input")
 
@@ -426,7 +426,7 @@ def main(argv):
             else:
                 sys.stderr.write(
                     "Exception thrown trying to read test file"
-                    " '{}'\n".format(options.read_tests)
+                    f" '{options.read_tests}'\n"
                 )
                 traceback.print_exc()
                 sys.stderr.write("---\n")
@@ -589,7 +589,7 @@ def main(argv):
     except OSError:
         if not os.path.exists(prefix[0]):
             print(
-                "JS shell argument: file does not exist:" " '{}'".format(prefix[0]),
+                "JS shell argument: file does not exist:" f" '{prefix[0]}'",
                 file=sys.stderr,
             )
             sys.exit(1)
diff --git a/js/src/jit/GenerateCacheIRFiles.py b/js/src/jit/GenerateCacheIRFiles.py
index 839052defef3..70f940ea9d4a 100644
--- a/js/src/jit/GenerateCacheIRFiles.py
+++ b/js/src/jit/GenerateCacheIRFiles.py
@@ -133,17 +133,17 @@ def gen_writer_method(name, args, custom_writer):
             cpp_type, write_method = arg_writer_info[arg_type]
             if arg_name == "result":
                 ret_type = cpp_type
-                args_code += "  {} result(newOperandId());\\\n".format(cpp_type)
+                args_code += f"  {cpp_type} result(newOperandId());\\\n"
                 args_code += "  writeOperandId(result);\\\n"
             else:
-                method_args.append("{} {}".format(cpp_type, arg_name))
-                args_code += "  {}({});\\\n".format(write_method, arg_name)
+                method_args.append(f"{cpp_type} {arg_name}")
+                args_code += f"  {write_method}({arg_name});\\\n"
 
     code = ""
     if custom_writer:
         code += "private:\\\n"
     code += "{} {}({}) {{\\\n".format(ret_type, method_name, ", ".join(method_args))
-    code += "  writeOp(CacheOp::{});\\\n".format(name)
+    code += f"  writeOp(CacheOp::{name});\\\n"
     code += args_code
     code += "  assertLengthMatches();\\\n"
     if ret_type != "void":
@@ -236,14 +236,14 @@ def gen_compiler_method(name, args):
             cpp_type, suffix, readexpr = arg_reader_info[arg_type]
             cpp_name = arg_name + suffix
             cpp_args.append(cpp_name)
-            method_args.append("{} {}".format(cpp_type, cpp_name))
-            args_code += "  {} {} = {};\\\n".format(cpp_type, cpp_name, readexpr)
+            method_args.append(f"{cpp_type} {cpp_name}")
+            args_code += f"  {cpp_type} {cpp_name} = {readexpr};\\\n"
 
     # Generate signature.
     code = "[[nodiscard]] bool {}({});\\\n".format(method_name, ", ".join(method_args))
 
     # Generate the method forwarding to it.
-    code += "[[nodiscard]] bool {}(CacheIRReader& reader) {{\\\n".format(method_name)
+    code += f"[[nodiscard]] bool {method_name}(CacheIRReader& reader) {{\\\n"
     code += args_code
     code += "  return {}({});\\\n".format(method_name, ", ".join(cpp_args))
     code += "}\\\n"
@@ -327,11 +327,11 @@ def gen_spewer_method(name, args):
             spew_method = arg_spewer_method[arg_type]
             if not is_first:
                 args_code += "  spewArgSeparator();\\\n"
-            args_code += '  {}("{}", {});\\\n'.format(spew_method, arg_name, readexpr)
+            args_code += f'  {spew_method}("{arg_name}", {readexpr});\\\n'
             is_first = False
 
-    code = "void {}(CacheIRReader& reader) {{\\\n".format(method_name)
-    code += "  spewOp(CacheOp::{});\\\n".format(name)
+    code = f"void {method_name}(CacheIRReader& reader) {{\\\n"
+    code += f"  spewOp(CacheOp::{name});\\\n"
     code += args_code
     code += "  spewOpEnd();\\\n"
     code += "}\\\n"
@@ -365,7 +365,7 @@ def gen_clone_method(name, args):
             read_type, suffix, readexpr = arg_reader_info[arg_type]
             read_name = arg_name + suffix
             value_name = read_name
-            args_code += "  {} {} = {};\\\n".format(read_type, read_name, readexpr)
+            args_code += f"  {read_type} {read_name} = {readexpr};\\\n"
 
             write_type, write_method = arg_writer_info[arg_type]
             if arg_name == "result":
@@ -376,14 +376,14 @@ def gen_clone_method(name, args):
                 if write_type.endswith("&"):
                     write_type = write_type[:-1]
                 value_name = arg_name
-                args_code += "  {} {} = get{}({});\\\n".format(
-                    write_type, value_name, arg_type, read_name
+                args_code += (
+                    f"  {write_type} {value_name} = get{arg_type}({read_name});\\\n"
                 )
-            args_code += "  writer.{}({});\\\n".format(write_method, value_name)
+            args_code += f"  writer.{write_method}({value_name});\\\n"
 
-    code = "void {}".format(method_name)
+    code = f"void {method_name}"
     code += "(CacheIRReader& reader, CacheIRWriter& writer) {{\\\n"
-    code += "  writer.writeOp(CacheOp::{});\\\n".format(name)
+    code += f"  writer.writeOp(CacheOp::{name});\\\n"
     code += args_code
     code += "  writer.assertLengthMatches();\\\n"
     code += "}}\\\n"
@@ -501,9 +501,7 @@ def generate_cacheirops_header(c_out, yaml_path):
             args_length = "0"
 
         transpile_str = "true" if transpile else "false"
-        ops_items.append(
-            "_({}, {}, {}, {})".format(name, args_length, transpile_str, cost_estimate)
-        )
+        ops_items.append(f"_({name}, {args_length}, {transpile_str}, {cost_estimate})")
 
         writer_methods.append(gen_writer_method(name, args, custom_writer))
 
@@ -514,7 +512,7 @@ def generate_cacheirops_header(c_out, yaml_path):
 
         if transpile:
             transpiler_methods.append(gen_compiler_method(name, args))
-            transpiler_ops.append("_({})".format(name))
+            transpiler_ops.append(f"_({name})")
 
         spewer_methods.append(gen_spewer_method(name, args))
 
diff --git a/js/src/jit/GenerateLIRFiles.py b/js/src/jit/GenerateLIRFiles.py
index 62d47148672c..c7cae0047d99 100644
--- a/js/src/jit/GenerateLIRFiles.py
+++ b/js/src/jit/GenerateLIRFiles.py
@@ -462,7 +462,7 @@ def generate_lir_header(c_out, yaml_path, mir_yaml_path):
                 )
             )
 
-        ops.append("_({})".format(name))
+        ops.append(f"_({name})")
 
     # Generate LIR instructions for MIR instructions with 'generate_lir': true
     mir_data = load_yaml(mir_yaml_path)
@@ -521,7 +521,7 @@ def generate_lir_header(c_out, yaml_path, mir_yaml_path):
                 )
             )
 
-            ops.append("_({})".format(name))
+            ops.append(f"_({name})")
 
     contents = "#define LIR_OPCODE_LIST(_)\\\n"
     contents += "\\\n".join(ops)
diff --git a/js/src/jit/GenerateMIRFiles.py b/js/src/jit/GenerateMIRFiles.py
index ea11ca08b51e..14674f9d204d 100644
--- a/js/src/jit/GenerateMIRFiles.py
+++ b/js/src/jit/GenerateMIRFiles.py
@@ -67,13 +67,13 @@ def decide_type_policy(types, no_type_policy):
         return "public NoTypePolicy::Data"
 
     if len(types) == 1:
-        return "public {}<0>::Data".format(type_policies[types[0]])
+        return f"public {type_policies[types[0]]}<0>::Data"
 
     type_num = 0
     mixed_type_policies = []
     for mir_type in types:
         policy = type_policies[mir_type]
-        mixed_type_policies.append("{}<{}>".format(policy, type_num))
+        mixed_type_policies.append(f"{policy}<{type_num}>")
         type_num += 1
 
     return "public MixPolicy<{}>::Data".format(", ".join(mixed_type_policies))
@@ -167,7 +167,7 @@ def gen_mir_class(
             # ops type policy.
             mir_types.append(operands[oper_name])
             # Collecting named operands for defining accessors.
-            named_operands.append("({}, {})".format(current_oper_num, oper_name))
+            named_operands.append(f"({current_oper_num}, {oper_name})")
             current_oper_num += 1
         type_policy = decide_type_policy(mir_types, no_type_policy)
 
@@ -179,7 +179,7 @@ def gen_mir_class(
     if base_class != "MNullaryInstruction":
         assert type_policy
         type_policy = ", " + type_policy
-    code = "class {} : public {}{} {{\\\n".format(class_name, base_class, type_policy)
+    code = f"class {class_name} : public {base_class}{type_policy} {{\\\n"
 
     # Arguments to class constructor that require accessors.
     mir_args = []
@@ -208,13 +208,13 @@ def gen_mir_class(
     if movable:
         code += "    setMovable();\\\n"
     if result:
-        code += "    setResultType(MIRType::{});\\\n".format(result)
+        code += f"    setResultType(MIRType::{result});\\\n"
     code += "  }\\\n public:\\\n"
     if arguments:
         for arg_name in arguments:
             code += "  " + arguments[arg_name] + " " + arg_name + "() const { "
             code += "return " + arg_name + "_; }\\\n"
-    code += "  INSTRUCTION_HEADER({})\\\n".format(name)
+    code += f"  INSTRUCTION_HEADER({name})\\\n"
     code += "  TRIVIAL_NEW_WRAPPERS\\\n"
     if named_operands:
         code += "  NAMED_OPERANDS({})\\\n".format(", ".join(named_operands))
@@ -302,7 +302,7 @@ def generate_mir_header(c_out, yaml_path):
     for op in data:
         name = op["name"]
 
-        ops_items.append("_({})".format(name))
+        ops_items.append(f"_({name})")
 
         gen_boilerplate = op.get("gen_boilerplate", True)
         assert isinstance(gen_boilerplate, bool)
diff --git a/js/src/make-source-package.py b/js/src/make-source-package.py
index 8816519bb7f3..873425291237 100755
--- a/js/src/make-source-package.py
+++ b/js/src/make-source-package.py
@@ -31,7 +31,7 @@ def assert_command(env_var, name):
     The command name comes from either environment variable or find_command.
     """
     if not name:
-        logging.error("{} command not found".format(env_var))
+        logging.error(f"{env_var} command not found")
         sys.exit(1)
 
 
@@ -88,25 +88,25 @@ version = "{}-{}.{}.{}".format(
     mozjs_name, major_version, minor_version, patch_version or alpha or "0"
 )
 target_dir = staging_dir / version
-package_name = "{}.tar.xz".format(version)
+package_name = f"{version}.tar.xz"
 package_file = dist_dir / package_name
 tar_opts = ["-Jcf"]
 
 # Given there might be some external program that reads the following output,
 # use raw `print`, instead of logging.
 print("Environment:")
-print("    TAR = {}".format(tar))
-print("    RSYNC = {}".format(rsync))
-print("    M4 = {}".format(m4))
-print("    AWK = {}".format(awk))
-print("    STAGING = {}".format(staging_dir))
-print("    DIST = {}".format(dist_dir))
-print("    SRC_DIR = {}".format(src_dir))
-print("    MOZJS_NAME = {}".format(mozjs_name))
-print("    MOZJS_MAJOR_VERSION = {}".format(major_version))
-print("    MOZJS_MINOR_VERSION = {}".format(minor_version))
-print("    MOZJS_PATCH_VERSION = {}".format(patch_version))
-print("    MOZJS_ALPHA = {}".format(alpha))
+print(f"    TAR = {tar}")
+print(f"    RSYNC = {rsync}")
+print(f"    M4 = {m4}")
+print(f"    AWK = {awk}")
+print(f"    STAGING = {staging_dir}")
+print(f"    DIST = {dist_dir}")
+print(f"    SRC_DIR = {src_dir}")
+print(f"    MOZJS_NAME = {mozjs_name}")
+print(f"    MOZJS_MAJOR_VERSION = {major_version}")
+print(f"    MOZJS_MINOR_VERSION = {minor_version}")
+print(f"    MOZJS_PATCH_VERSION = {patch_version}")
+print(f"    MOZJS_ALPHA = {alpha}")
 print("")
 
 rsync_filter_list = """
@@ -272,7 +272,7 @@ ac_add_options --enable-optimize
 mk_add_options MOZ_OBJDIR=obj-opt
 """
 
-README_CONTENT = """\
+README_CONTENT = f"""\
 This directory contains SpiderMonkey {major_version}.
 
 This release is based on a revision of Mozilla {major_version}:
@@ -280,9 +280,7 @@ This release is based on a revision of Mozilla {major_version}:
 The changes in the patches/ directory were applied.
 
 See https://spidermonkey.dev/ for documentation, examples, and release notes.
-""".format(
-    major_version=major_version
-)
+"""
 
 
 def is_mozjs_cargo_member(line):
@@ -301,7 +299,7 @@ def is_mozjs_crates_io_local_patch(line):
 
 def clean():
     """Remove temporary directory and package file."""
-    logging.info("Cleaning {} and {} ...".format(package_file, target_dir))
+    logging.info(f"Cleaning {package_file} and {target_dir} ...")
     if package_file.exists():
         package_file.unlink()
     if target_dir.exists():
@@ -318,7 +316,7 @@ def assert_clean():
 
 def create_target_dir():
     if target_dir.exists():
-        logging.warning("dist tree {} already exists!".format(target_dir))
+        logging.warning(f"dist tree {target_dir} already exists!")
     else:
         target_dir.mkdir(parents=True)
 
@@ -332,8 +330,8 @@ def sync_files():
             "--prune-empty-dirs",
             "--quiet",
             "--recursive",
-            "{}/".format(topsrc_dir),
-            "{}/".format(target_dir),
+            f"{topsrc_dir}/",
+            f"{target_dir}/",
             "--filter=. -",
         ],
         stdin=subprocess.PIPE,
@@ -403,7 +401,7 @@ def generate_configure():
             [
                 "sh",
                 str(topsrc_dir / "build" / "autoconf" / "autoconf.sh"),
-                "--localdir={}".format(js_src_dir),
+                f"--localdir={js_src_dir}",
                 str(src_old_configure_in_file),
             ],
             stdout=f,
@@ -449,7 +447,7 @@ def remove_python_cache():
 
 def stage():
     """Stage source tarball content."""
-    logging.info("Staging source tarball in {}...".format(target_dir))
+    logging.info(f"Staging source tarball in {target_dir}...")
 
     create_target_dir()
     sync_files()
@@ -466,7 +464,7 @@ def stage():
 def create_tar():
     """Roll the tarball."""
 
-    logging.info("Packaging source tarball at {}...".format(package_file))
+    logging.info(f"Packaging source tarball at {package_file}...")
 
     subprocess.run(
         [str(tar)] + tar_opts + [str(package_file), "-C", str(staging_dir), version],
diff --git a/js/src/shell/js-gdb.py b/js/src/shell/js-gdb.py
index 2fbb50b5487a..dd4ae7b0cd1f 100644
--- a/js/src/shell/js-gdb.py
+++ b/js/src/shell/js-gdb.py
@@ -16,6 +16,6 @@ import gdb
 devel_objdir = abspath(os.path.join(dirname(__file__), "..", ".."))
 m = re.search(r"[\w ]+: (.*)", gdb.execute("show directories", False, True))
 if m and devel_objdir not in m.group(1).split(":"):
-    gdb.execute("set directories {}:{}".format(devel_objdir, m.group(1)))
+    gdb.execute(f"set directories {devel_objdir}:{m.group(1)}")
 
 gdb.execute("source -s build/.gdbinit.loader")
diff --git a/js/src/tests/compare_bench.py b/js/src/tests/compare_bench.py
index be8721a2fa5c..ec741682bbae 100644
--- a/js/src/tests/compare_bench.py
+++ b/js/src/tests/compare_bench.py
@@ -29,22 +29,18 @@ def compare(current, baseline):
         if t_worst < base_t_best:
             # Worst takes less time (better) than baseline's best.
             speedup = -((t_worst - base_t_best) / base_t_best) * 100
-            result = "faster: {:6.2f}ms < baseline {:6.2f}ms ({:+6.2f}%)".format(
-                t_worst, base_t_best, speedup
-            )
+            result = f"faster: {t_worst:6.2f}ms < baseline {base_t_best:6.2f}ms ({speedup:+6.2f}%)"
             percent_speedups.append(speedup)
         elif t_best > base_t_worst:
             # Best takes more time (worse) than baseline's worst.
             slowdown = -((t_best - base_t_worst) / base_t_worst) * 100
-            result = "SLOWER: {:6.2f}ms > baseline {:6.2f}ms ({:+6.2f}%) ".format(
-                t_best, base_t_worst, slowdown
-            )
+            result = f"SLOWER: {t_best:6.2f}ms > baseline {base_t_worst:6.2f}ms ({slowdown:+6.2f}%) "
             percent_speedups.append(slowdown)
         else:
             result = "Meh."
-        print("{:30s}: {}".format(key, result))
+        print(f"{key:30s}: {result}")
     if percent_speedups:
-        print("Average speedup: {:.2f}%".format(avg(percent_speedups)))
+        print(f"Average speedup: {avg(percent_speedups):.2f}%")
 
 
 def compare_immediate(current_map, baseline_path):
diff --git a/js/src/tests/jstests.py b/js/src/tests/jstests.py
index 57dc487aa578..5a59efd6eda0 100755
--- a/js/src/tests/jstests.py
+++ b/js/src/tests/jstests.py
@@ -54,7 +54,7 @@ def changedir(dirname):
         os.chdir(pwd)
 
 
-class PathOptions(object):
+class PathOptions:
     def __init__(self, location, requested_paths, excluded_paths):
         self.requested_paths = requested_paths
         self.excluded_files, self.excluded_dirs = PathOptions._split_files_and_dirs(
@@ -466,7 +466,7 @@ def parse_args():
     # excluded tests set.
     if options.exclude_file:
         for filename in options.exclude_file:
-            with open(filename, "r") as fp:
+            with open(filename) as fp:
                 for line in fp:
                     if line.startswith("#"):
                         continue
@@ -788,7 +788,7 @@ def main():
                 " debugger can only run one"
             )
             for tc in test_gen:
-                print("    {}".format(tc.path))
+                print(f"    {tc.path}")
             return 2
 
         with changedir(test_dir), change_env(
@@ -878,7 +878,7 @@ def run_test_remote(test, device, prefix, tempdir, options):
         returncode = e.adb_process.exitcode
         re_ignore = re.compile(r"error: (closed|device .* not found)")
         if returncode == 1 and re_ignore.search(out):
-            print("Skipping {} due to ignorable adb error {}".format(test.path, out))
+            print(f"Skipping {test.path} due to ignorable adb error {out}")
             test.skip_if_cond = "true"
             returncode = test.SKIPPED_EXIT_STATUS
 
diff --git a/js/src/tests/lib/jittests.py b/js/src/tests/lib/jittests.py
index 91ad208f0ffb..73ba27976e13 100755
--- a/js/src/tests/lib/jittests.py
+++ b/js/src/tests/lib/jittests.py
@@ -98,7 +98,7 @@ os.path.relpath = _relpath
 def extend_condition(condition, value):
     if condition:
         condition += " || "
-    condition += "({})".format(value)
+    condition += f"({value})"
     return condition
 
 
@@ -288,20 +288,12 @@ class JitTest:
                             else:
                                 test.expect_status = status
                         except ValueError:
-                            print(
-                                "warning: couldn't parse exit status"
-                                " {}".format(value)
-                            )
+                            print("warning: couldn't parse exit status" f" {value}")
                     elif name == "thread-count":
                         try:
-                            test.jitflags.append(
-                                "--thread-count={}".format(int(value, 0))
-                            )
+                            test.jitflags.append(f"--thread-count={int(value, 0)}")
                         except ValueError:
-                            print(
-                                "warning: couldn't parse thread-count"
-                                " {}".format(value)
-                            )
+                            print("warning: couldn't parse thread-count" f" {value}")
                     elif name == "include":
                         test.other_lib_includes.append(value)
                     elif name == "local-include":
@@ -318,8 +310,8 @@ class JitTest:
                             print("warning: couldn't parse skip-variant-if")
                     else:
                         print(
-                            "{}: warning: unrecognized |jit-test| attribute"
-                            " {}".format(path, part)
+                            f"{path}: warning: unrecognized |jit-test| attribute"
+                            f" {part}"
                         )
                 else:
                     if name == "slow":
@@ -354,7 +346,7 @@ class JitTest:
                         # skipped.
                         assert (
                             "self-test" in path
-                        ), "{}: has an unexpected crash annotation.".format(path)
+                        ), f"{path}: has an unexpected crash annotation."
                         test.expect_crash = True
                     elif name.startswith("--"):
                         # // |jit-test| --ion-gvn=off; --no-sse4
@@ -368,8 +360,8 @@ class JitTest:
                         test.jitflags.append("--setpref=" + prefAndValue[1])
                     else:
                         print(
-                            "{}: warning: unrecognized |jit-test| attribute"
-                            " {}".format(path, part)
+                            f"{path}: warning: unrecognized |jit-test| attribute"
+                            f" {part}"
                         )
 
         if options.valgrind_all:
@@ -408,9 +400,9 @@ class JitTest:
         # Don't merge the expressions: We want separate -e arguments to avoid
         # semicolons in the command line, bug 1351607.
         exprs = [
-            "const platform={}".format(js_quote(quotechar, sys.platform)),
-            "const libdir={}".format(js_quote(quotechar, libdir)),
-            "const scriptdir={}".format(js_quote(quotechar, scriptdir_var)),
+            f"const platform={js_quote(quotechar, sys.platform)}",
+            f"const libdir={js_quote(quotechar, libdir)}",
+            f"const scriptdir={js_quote(quotechar, scriptdir_var)}",
         ]
 
         # We may have specified '-a' or '-d' twice: once via --jitflags, once
@@ -436,7 +428,7 @@ class JitTest:
         if self.skip_if_cond:
             cmd += [
                 "-e",
-                "if ({}) quit({})".format(self.skip_if_cond, self.SKIPPED_EXIT_STATUS),
+                f"if ({self.skip_if_cond}) quit({self.SKIPPED_EXIT_STATUS})",
             ]
         cmd += ["--module-load-path", moduledir]
         if self.is_module:
@@ -585,9 +577,7 @@ def print_automation_format(ok, res, slog):
     message = "Success" if ok else res.describe_failure()
     jitflags = " ".join(res.test.jitflags)
     print(
-        '{} | {} | {} (code {}, args "{}") [{:.1f} s]'.format(
-            result, res.test.relpath_top, message, res.rc, jitflags, res.dt
-        )
+        f'{result} | {res.test.relpath_top} | {message} (code {res.rc}, args "{jitflags}") [{res.dt:.1f} s]'
     )
 
     details = {
@@ -603,8 +593,8 @@ def print_automation_format(ok, res, slog):
     # For failed tests, print as much information as we have, to aid debugging.
     if ok:
         return
-    print("INFO exit-status     : {}".format(res.rc))
-    print("INFO timed-out       : {}".format(res.timed_out))
+    print(f"INFO exit-status     : {res.rc}")
+    print(f"INFO timed-out       : {res.timed_out}")
     warnings = []
     for line in res.out.splitlines():
         # See Bug 1868693
@@ -647,7 +637,7 @@ def print_test_summary(num_tests, failures, complete, slow_tests, doing, options
             except OSError:
                 sys.stderr.write(
                     "Exception thrown trying to write failure"
-                    " file '{}'\n".format(options.write_failures)
+                    f" file '{options.write_failures}'\n"
                 )
                 traceback.print_exc()
                 sys.stderr.write("---\n")
@@ -664,32 +654,26 @@ def print_test_summary(num_tests, failures, complete, slow_tests, doing, options
     else:
         print(
             "PASSED ALL"
-            + (
-                ""
-                if complete
-                else " (partial run -- interrupted by user {})".format(doing)
-            )
+            + ("" if complete else f" (partial run -- interrupted by user {doing})")
         )
 
     if options.format == "automation":
         num_failures = len(failures) if failures else 0
         print("Result summary:")
-        print("Passed: {:d}".format(num_tests - num_failures))
-        print("Failed: {:d}".format(num_failures))
+        print(f"Passed: {num_tests - num_failures:d}")
+        print(f"Failed: {num_failures:d}")
 
     if num_tests != 0 and options.show_slow:
         threshold = options.slow_test_threshold
         fraction_fast = 1 - len(slow_tests) / num_tests
-        print(
-            "{:5.2f}% of tests ran in under {}s".format(fraction_fast * 100, threshold)
-        )
+        print(f"{fraction_fast * 100:5.2f}% of tests ran in under {threshold}s")
 
-        print("Slowest tests that took longer than {}s:".format(threshold))
+        print(f"Slowest tests that took longer than {threshold}s:")
         slow_tests.sort(key=lambda res: res.dt, reverse=True)
         any = False
         for i in range(min(len(slow_tests), 20)):
             res = slow_tests[i]
-            print("  {:6.2f} {}".format(res.dt, test_details(res)))
+            print(f"  {res.dt:6.2f} {test_details(res)}")
             any = True
         if not any:
             print("None")
@@ -744,7 +728,7 @@ def process_test_results(results, num_tests, pb, options, slog):
                 pb.beginline()
                 sys.stdout.write(res.out)
                 sys.stdout.write(res.err)
-                sys.stdout.write("Exit code: {}\n".format(res.rc))
+                sys.stdout.write(f"Exit code: {res.rc}\n")
 
             if res.test.valgrind and not show_output:
                 pb.beginline()
@@ -753,22 +737,20 @@ def process_test_results(results, num_tests, pb, options, slog):
             if options.check_output:
                 if res.test.path in output_dict.keys():
                     if output_dict[res.test.path] != res.out:
-                        pb.message(
-                            "FAIL - OUTPUT DIFFERS {}".format(res.test.relpath_tests)
-                        )
+                        pb.message(f"FAIL - OUTPUT DIFFERS {res.test.relpath_tests}")
                 else:
                     output_dict[res.test.path] = res.out
 
-            doing = "after {}".format(res.test.relpath_tests)
+            doing = f"after {res.test.relpath_tests}"
             if status == OutputStatus.SKIPPED:
                 skipped += 1
             elif status == OutputStatus.FAILED:
                 failures.append(res)
                 if res.timed_out:
-                    pb.message("TIMEOUT - {}".format(res.test.relpath_tests))
+                    pb.message(f"TIMEOUT - {res.test.relpath_tests}")
                     timeouts += 1
                 else:
-                    pb.message("FAIL - {}".format(res.test.relpath_tests))
+                    pb.message(f"FAIL - {res.test.relpath_tests}")
 
             if options.format == "automation":
                 print_automation_format(status, res, slog)
diff --git a/js/src/tests/lib/manifest.py b/js/src/tests/lib/manifest.py
index b82df4610fd9..dcad53b4c167 100644
--- a/js/src/tests/lib/manifest.py
+++ b/js/src/tests/lib/manifest.py
@@ -70,7 +70,7 @@ class XULInfo:
         if path is None:
             print(
                 "Can't find config/autoconf.mk on a directory containing"
-                " the JS shell (searched from {})".format(jsdir)
+                f" the JS shell (searched from {jsdir})"
             )
             sys.exit(1)
 
@@ -135,7 +135,7 @@ class XULInfoTester:
                 "-e",
                 self.js_prologue,
                 "-e",
-                "print(!!({}))".format(cond),
+                f"print(!!({cond}))",
             ]
         )
         cmd = ADBDevice._escape_command_line(cmd)
@@ -157,8 +157,8 @@ class XULInfoTester:
             ans = False
         else:
             raise Exception(
-                "Failed to test XUL condition {!r};"
-                " output was {!r}, stderr was {!r}".format(cond, out, err)
+                f"Failed to test XUL condition {cond!r};"
+                f" output was {out!r}, stderr was {err!r}"
             )
         self.cache[cond] = ans
         return ans
@@ -180,7 +180,7 @@ class XULInfoTester:
                     "-e",
                     self.js_prologue,
                     "-e",
-                    "print(!!({}))".format(cond),
+                    f"print(!!({cond}))",
                 ]
             )
             p = Popen(
@@ -193,8 +193,8 @@ class XULInfoTester:
                 ans = False
             else:
                 raise Exception(
-                    "Failed to test XUL condition {!r};"
-                    " output was {!r}, stderr was {!r}".format(cond, out, err)
+                    f"Failed to test XUL condition {cond!r};"
+                    f" output was {out!r}, stderr was {err!r}"
                 )
             self.cache[cond] = ans
         return ans
@@ -278,7 +278,7 @@ def _parse_one(testcase, terms, xul_tester):
             testcase.is_async = True
             pos += 1
         else:
-            print('warning: invalid manifest line element "{}"'.format(parts[pos]))
+            print(f'warning: invalid manifest line element "{parts[pos]}"')
             pos += 1
 
 
@@ -504,7 +504,7 @@ def _parse_external_manifest(filename, relpath):
 
     entries = []
 
-    with open(filename, "r", encoding="utf-8") as fp:
+    with open(filename, encoding="utf-8") as fp:
         manifest_re = re.compile(
             r"^\s*(?P.*)\s+(?Pinclude|script)\s+(?P\S+)$"
         )
@@ -518,10 +518,7 @@ def _parse_external_manifest(filename, relpath):
             if not matches:
                 matches = include_re.match(line)
                 if not matches:
-                    print(
-                        "warning: unrecognized line in jstests.list:"
-                        " {0}".format(line)
-                    )
+                    print("warning: unrecognized line in jstests.list:" f" {line}")
                     continue
 
                 include_file = matches.group("path")
diff --git a/js/src/tests/lib/progressbar.py b/js/src/tests/lib/progressbar.py
index a37f74af19c8..e38c0a97e2c7 100644
--- a/js/src/tests/lib/progressbar.py
+++ b/js/src/tests/lib/progressbar.py
@@ -10,7 +10,7 @@ else:
     from .terminal_unix import Terminal
 
 
-class NullProgressBar(object):
+class NullProgressBar:
     def update(self, current, data):
         pass
 
@@ -31,7 +31,7 @@ class NullProgressBar(object):
         return timedelta.max
 
 
-class ProgressBar(object):
+class ProgressBar:
     def __init__(self, limit, fmt):
         assert self.conservative_isatty()
 
@@ -81,7 +81,7 @@ class ProgressBar(object):
 
         # Build the bar.
         pct = int(100.0 * current / self.limit)
-        sys.stdout.write("{:3d}% ".format(pct))
+        sys.stdout.write(f"{pct:3d}% ")
 
         barlen = int(1.0 * self.barlen * current / self.limit) - 1
         bar = "=" * barlen + ">" + " " * (self.barlen - barlen - 1)
@@ -91,7 +91,7 @@ class ProgressBar(object):
         now = datetime.now()
         dt = now - self.t0
         dt = dt.seconds + dt.microseconds * 1e-6
-        sys.stdout.write("{:6.1f}s".format(dt))
+        sys.stdout.write(f"{dt:6.1f}s")
         Terminal.clear_right()
 
         # Force redisplay, since we didn't write a \n.
diff --git a/js/src/tests/lib/results.py b/js/src/tests/lib/results.py
index 1d18b9eb69de..f213c5d0bfcc 100644
--- a/js/src/tests/lib/results.py
+++ b/js/src/tests/lib/results.py
@@ -183,9 +183,7 @@ class TestResult:
             expected_rcs.append(3)
             if test.error not in err:
                 failures += 1
-                results.append(
-                    (cls.FAIL, "Expected uncaught error: {}".format(test.error))
-                )
+                results.append((cls.FAIL, f"Expected uncaught error: {test.error}"))
 
         if rc and rc not in expected_rcs:
             if rc == 3:
@@ -299,9 +297,7 @@ class ResultsSink:
 
                 if show_output:
                     print(
-                        "## {}: rc = {:d}, run time = {}".format(
-                            output.test.path, output.rc, output.dt
-                        ),
+                        f"## {output.test.path}: rc = {output.rc:d}, run time = {output.dt}",
                         file=self.fp,
                     )
 
@@ -316,9 +312,7 @@ class ResultsSink:
                         except UnicodeEncodeError as e:
                             # In case the data contains something not directly
                             # encodable, use \uXXXX.
-                            fp.write(
-                                "WARNING: Falling back from exception: {}\n".format(e)
-                            )
+                            fp.write(f"WARNING: Falling back from exception: {e}\n")
                             fp.write("WARNING: The following output is escaped, ")
                             fp.write("and may be different than original one.\n")
                             fp.write(
@@ -361,7 +355,7 @@ class ResultsSink:
                 def singular(label):
                     return "FIXED" if label == "FIXES" else label[:-1]
 
-                self.pb.message("{} - {}".format(singular(dev_label), output.test.path))
+                self.pb.message(f"{singular(dev_label)} - {output.test.path}")
 
         self.pb.update(self.n, self.counts)
 
@@ -433,16 +427,14 @@ class ResultsSink:
     def show_slow_tests(self):
         threshold = self.options.slow_test_threshold
         fraction_fast = 1 - len(self.slow_tests) / self.n
-        self.log_info(
-            "{:5.2f}% of tests ran in under {}s".format(fraction_fast * 100, threshold)
-        )
+        self.log_info(f"{fraction_fast * 100:5.2f}% of tests ran in under {threshold}s")
 
-        self.log_info("Slowest tests that took longer than {}s:".format(threshold))
+        self.log_info(f"Slowest tests that took longer than {threshold}s:")
         slow_tests = sorted(self.slow_tests, key=lambda x: x.duration, reverse=True)
         any = False
         for i in range(min(len(slow_tests), 20)):
             test = slow_tests[i]
-            self.log_info("  {:6.2f} {}".format(test.duration, test.test))
+            self.log_info(f"  {test.duration:6.2f} {test.test}")
             any = True
         if not any:
             self.log_info("None")
@@ -472,7 +464,7 @@ class ResultsSink:
             result += " | (SKIP)"
         if time > self.options.timeout:
             result += " | (TIMEOUT)"
-        result += " [{:.1f} s]".format(time)
+        result += f" [{time:.1f} s]"
         print(result)
 
         details = {"extra": extra.copy() if extra else {}}
diff --git a/js/src/tests/lib/structuredlog.py b/js/src/tests/lib/structuredlog.py
index b00914cc90d8..6d00b106828e 100644
--- a/js/src/tests/lib/structuredlog.py
+++ b/js/src/tests/lib/structuredlog.py
@@ -6,7 +6,7 @@ import os
 from time import time
 
 
-class TestLogger(object):
+class TestLogger:
     def __init__(self, source, threadname="main"):
         self.template = {
             "source": source,
diff --git a/js/src/tests/lib/tasks_adb_remote.py b/js/src/tests/lib/tasks_adb_remote.py
index 1ddc6baa0859..5362a02663ab 100644
--- a/js/src/tests/lib/tasks_adb_remote.py
+++ b/js/src/tests/lib/tasks_adb_remote.py
@@ -95,7 +95,7 @@ def aggregate_script_stdout(stdout_lines, prefix, tempdir, uniq_tag, tests, opti
         assert ended
     except AssertionError as e:
         sys.stderr.write("Metadata history:\n{}\n".format("\n".join(meta_history)))
-        sys.stderr.write("Last line: {}\n".format(last_line))
+        sys.stderr.write(f"Last line: {last_line}\n")
         raise e
 
 
@@ -136,7 +136,7 @@ def script_preamble(tag, prefix, options):
     timeout = int(options.timeout)
     retry = int(options.timeout_retry)
     lib_path = os.path.dirname(prefix[0])
-    return """
+    return f"""
 export LD_LIBRARY_PATH={lib_path}
 
 do_test()
@@ -173,9 +173,7 @@ do_end()
 {{
     echo '\\n{tag}THE_END'
 }}
-""".format(
-        tag=tag, lib_path=lib_path, timeout=timeout, retry=retry
-    )
+"""
 
 
 def setup_script(device, prefix, tempdir, options, uniq_tag, tests):
@@ -208,7 +206,7 @@ def setup_script(device, prefix, tempdir, options, uniq_tag, tests):
                 env["TZ"] = "PST8PDT"
             envStr = "".join(key + "='" + val + "' " for key, val in env.items())
 
-            tmpf.write("{}do_test {} 0 {};\n".format(envStr, i, cmd))
+            tmpf.write(f"{envStr}do_test {i} 0 {cmd};\n")
             script_timeout += timeout
         tmpf.write("do_end;\n")
         tmpf.close()
@@ -238,7 +236,7 @@ def start_script(
     # output produced by each test, and queue TestOutput in the qResult queue.
     try:
         adb_process = device.shell(
-            "sh {}".format(script),
+            f"sh {script}",
             env=env,
             cwd=options.remote_test_root,
             timeout=script_timeout,
@@ -252,7 +250,7 @@ def start_script(
         # After a device error, the device is typically in a
         # state where all further tests will fail so there is no point in
         # continuing here.
-        sys.stderr.write("Error running remote tests: {}".format(repr(e)))
+        sys.stderr.write(f"Error running remote tests: {repr(e)}")
 
 
 def get_remote_results(tests, prefix, pb, options):
diff --git a/js/src/tests/lib/tasks_unix.py b/js/src/tests/lib/tasks_unix.py
index dbceaa294cce..ad43ca02ee2b 100644
--- a/js/src/tests/lib/tasks_unix.py
+++ b/js/src/tests/lib/tasks_unix.py
@@ -14,7 +14,7 @@ from .progressbar import ProgressBar
 from .results import NullTestOutput, TestOutput, escape_cmdline
 
 
-class Task(object):
+class Task:
     def __init__(self, test, prefix, tempdir, pid, stdout, stderr):
         self.test = test
         self.cmd = test.get_command(prefix, tempdir)
@@ -133,7 +133,7 @@ def remove_task(tasks, pid):
             index = i
             break
     else:
-        raise KeyError("No such pid: {}".format(pid))
+        raise KeyError(f"No such pid: {pid}")
 
     out = tasks[index]
     tasks.pop(index)
diff --git a/js/src/tests/lib/terminal_unix.py b/js/src/tests/lib/terminal_unix.py
index cdf799577690..b6dd2ea4ec93 100644
--- a/js/src/tests/lib/terminal_unix.py
+++ b/js/src/tests/lib/terminal_unix.py
@@ -1,7 +1,7 @@
 import sys
 
 
-class Terminal(object):
+class Terminal:
     COLOR = {"red": "31", "green": "32", "blue": "34", "gray": "37"}
     NORMAL_INTENSITY = "1"
     BRIGHT_INTENSITY = "2"
diff --git a/js/src/tests/lib/terminal_win.py b/js/src/tests/lib/terminal_win.py
index a9af46b35189..43c6b455f894 100644
--- a/js/src/tests/lib/terminal_win.py
+++ b/js/src/tests/lib/terminal_win.py
@@ -79,7 +79,7 @@ def get_text_attr():
 DEFAULT_COLORS = get_text_attr()
 
 
-class Terminal(object):
+class Terminal:
     COLOR = {
         "black": 0x0000,
         "blue": 0x0001,
diff --git a/js/src/tests/lib/tests.py b/js/src/tests/lib/tests.py
index d5722c78029c..04e763fb715f 100644
--- a/js/src/tests/lib/tests.py
+++ b/js/src/tests/lib/tests.py
@@ -87,7 +87,7 @@ JITFLAGS = {
 
 def get_jitflags(variant, **kwargs):
     if variant not in JITFLAGS:
-        print('Invalid jitflag: "{}"'.format(variant))
+        print(f'Invalid jitflag: "{variant}"')
         sys.exit(1)
     if variant == "none" and "none" in kwargs:
         return kwargs["none"]
@@ -137,7 +137,7 @@ def change_env(env_overlay):
     for key, val in env_overlay.items():
         prior_env[key] = os.environ.get(key, None)
         if "PATH" in key and key in os.environ:
-            os.environ[key] = "{}{}{}".format(val, os.pathsep, os.environ[key])
+            os.environ[key] = f"{val}{os.pathsep}{os.environ[key]}"
         else:
             os.environ[key] = val
 
@@ -186,7 +186,7 @@ def get_cpu_count():
     return 1
 
 
-class RefTestCase(object):
+class RefTestCase:
     """A test case consisting of a test and an expected result."""
 
     def __init__(self, root, path, extra_helper_paths=None, wpt=None):
diff --git a/js/src/tests/lib/wptreport.py b/js/src/tests/lib/wptreport.py
index 95fa9b1ed716..39aeea212f8f 100644
--- a/js/src/tests/lib/wptreport.py
+++ b/js/src/tests/lib/wptreport.py
@@ -12,7 +12,7 @@ from time import time
 from wptrunner.formatters.wptreport import WptreportFormatter
 
 
-class WptreportHandler(object):
+class WptreportHandler:
     def __init__(self, out):
         """
         Initialize the WptreportHandler handler.
diff --git a/js/src/tests/non262/String/make-normalize-generateddata-input.py b/js/src/tests/non262/String/make-normalize-generateddata-input.py
index 086275e67d35..3fe19b55216e 100644
--- a/js/src/tests/non262/String/make-normalize-generateddata-input.py
+++ b/js/src/tests/non262/String/make-normalize-generateddata-input.py
@@ -14,7 +14,7 @@ sep_pat = re.compile(" +")
 
 
 def to_code_list(codes):
-    return "[" + ", ".join("0x{0}".format(x) for x in re.split(sep_pat, codes)) + "]"
+    return "[" + ", ".join(f"0x{x}" for x in re.split(sep_pat, codes)) + "]"
 
 
 def convert(dir):
@@ -29,8 +29,8 @@ def convert(dir):
 
     part_opened = False
     not_empty = False
-    with open("{dir}/{path}".format(dir=dir, path=txt_path), "r") as f:
-        with open("{dir}/{path}".format(dir=dir, path=js_path), "w") as outf:
+    with open(f"{dir}/{txt_path}") as f:
+        with open(f"{dir}/{js_path}", "w") as outf:
             for line in f:
                 m = test_pat.search(line)
                 if m:
@@ -55,24 +55,20 @@ def convert(dir):
                     part = m.group(2)
                     if part_opened:
                         outf.write("\n];\n")
-                    outf.write("/* {desc} */\n".format(desc=desc))
-                    outf.write("var tests_part{part} = [".format(part=part))
+                    outf.write(f"/* {desc} */\n")
+                    outf.write(f"var tests_part{part} = [")
                     part_opened = True
                     not_empty = False
                     continue
                 m = ver_pat.search(line)
                 if m:
                     ver = m.group(1)
-                    outf.write(
-                        "/* created from NormalizationTest-{ver}.txt */\n".format(
-                            ver=ver
-                        )
-                    )
+                    outf.write(f"/* created from NormalizationTest-{ver}.txt */\n")
                     continue
                 m = ignore_pat.search(line)
                 if m:
                     continue
-                print("Unknown line: {0}".format(line), file=sys.stderr)
+                print(f"Unknown line: {line}", file=sys.stderr)
             if part_opened:
                 outf.write("\n];\n")
 
diff --git a/js/src/tests/parsemark.py b/js/src/tests/parsemark.py
index 5e7652d65da2..4723814f8c91 100644
--- a/js/src/tests/parsemark.py
+++ b/js/src/tests/parsemark.py
@@ -91,7 +91,7 @@ def bench(
     if not stfu:
         print("Runs:", [int(ms) for ms in milliseconds])
         print("Mean:", mean)
-        print("Stddev: {:.2f} ({:.2f}% of mean)".format(sigma, sigma / mean * 100))
+        print(f"Stddev: {sigma:.2f} ({sigma / mean * 100:.2f}% of mean)")
     return mean, sigma
 
 
@@ -101,7 +101,7 @@ def parsemark(filepaths, fbench, stfu=False):
     for filepath in filepaths:
         filename = os.path.split(filepath)[-1]
         if not stfu:
-            print("Parsemarking {}...".format(filename))
+            print(f"Parsemarking {filename}...")
         bench_map[filename] = fbench(filepath)
     print("{")
     for i, (filename, (avg, stddev)) in enumerate(iter(bench_map.items())):
@@ -109,7 +109,7 @@ def parsemark(filepaths, fbench, stfu=False):
         fmt = '    {:30s}: {{"average_ms": {:6.2f}, "stddev_ms": {:6.2f}}}'
         if i != len(bench_map) - 1:
             fmt += ","
-        filename_str = '"{}"'.format(filename)
+        filename_str = f'"{filename}"'
         print(fmt.format(filename_str, avg, stddev))
     print("}")
     return dict(
diff --git a/js/src/tests/test/run.py b/js/src/tests/test/run.py
index 862045a0837c..7bf202100237 100755
--- a/js/src/tests/test/run.py
+++ b/js/src/tests/test/run.py
@@ -121,7 +121,7 @@ class TestExport(unittest.TestCase):
                     )
 
     def compareContents(self, output: bytes, filePath: str, folder: str):
-        with open(filePath, "r") as file:
+        with open(filePath) as file:
             expected = file.read()
 
         expected = expected.replace("{{folder}}", folder)
diff --git a/js/src/tests/test262-update.py b/js/src/tests/test262-update.py
index 3040c2333b2c..902c53c4430e 100755
--- a/js/src/tests/test262-update.py
+++ b/js/src/tests/test262-update.py
@@ -396,7 +396,7 @@ def convertTestFile(test262parser, testSource, testName, includeSet, strictTests
             if shellOptions:
                 refTestSkipIf.append(("!xulRuntime.shell", "requires shell-options"))
                 refTestOptions.extend(
-                    "shell-option({})".format(opt) for opt in sorted(shellOptions)
+                    f"shell-option({opt})" for opt in sorted(shellOptions)
                 )
 
     # Optional shell options. Some tests use feature detection for additional
@@ -409,7 +409,7 @@ def convertTestFile(test262parser, testSource, testName, includeSet, strictTests
             if include in INCLUDE_FEATURE_DETECTED_OPTIONAL_SHELL_OPTIONS
         )
         refTestOptions.extend(
-            "shell-option({})".format(opt) for opt in sorted(optionalShellOptions)
+            f"shell-option({opt})" for opt in sorted(optionalShellOptions)
         )
 
     # Includes for every test file in a directory is collected in a single
diff --git a/js/src/util/make_unicode.py b/js/src/util/make_unicode.py
index ecd893c42612..010f769a82b0 100755
--- a/js/src/util/make_unicode.py
+++ b/js/src/util/make_unicode.py
@@ -258,19 +258,15 @@ def make_non_bmp_convert_macro(out_file, name, convert_map, codepoint_table):
         to_trail = entry["trail"] + entry["length"] - 1
 
         lines.append(
-            "    MACRO(0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, {:d})".format(
-                from_code, to_code, lead, from_trail, to_trail, diff
-            )
+            f"    MACRO(0x{from_code:x}, 0x{to_code:x}, 0x{lead:x}, 0x{from_trail:x}, 0x{to_trail:x}, {diff:d})"
         )
         comment.append(
-            "// {} .. {}".format(
-                codepoint_table.full_name(from_code), codepoint_table.full_name(to_code)
-            )
+            f"// {codepoint_table.full_name(from_code)} .. {codepoint_table.full_name(to_code)}"
         )
 
     out_file.write("\n".join(comment))
     out_file.write("\n")
-    out_file.write("#define FOR_EACH_NON_BMP_{}(MACRO) \\\n".format(name))
+    out_file.write(f"#define FOR_EACH_NON_BMP_{name}(MACRO) \\\n")
     out_file.write(" \\\n".join(lines))
     out_file.write("\n")
 
@@ -679,35 +675,31 @@ def make_non_bmp_file(version, non_bmp_lower_map, non_bmp_upper_map, codepoint_t
 def write_special_casing_methods(unconditional_toupper, codepoint_table, println):
     def hexlit(n):
         """Returns C++ hex-literal for |n|."""
-        return "0x{:04X}".format(n)
+        return f"0x{n:04X}"
 
     def describe_range(ranges, depth):
         indent = depth * "    "
         for start, end in ranges:
             if start == end:
-                println(indent, "// {}".format(codepoint_table.full_name(start)))
+                println(indent, f"// {codepoint_table.full_name(start)}")
             else:
                 println(
                     indent,
-                    "// {} .. {}".format(
-                        codepoint_table.full_name(start), codepoint_table.full_name(end)
-                    ),
+                    f"// {codepoint_table.full_name(start)} .. {codepoint_table.full_name(end)}",
                 )
 
     def out_range(start, end):
         """Tests if the input character isn't a member of the set {x | start <= x <= end}."""
         if start == end:
-            return "ch != {}".format(hexlit(start))
-        return "ch < {} || ch > {}".format(hexlit(start), hexlit(end))
+            return f"ch != {hexlit(start)}"
+        return f"ch < {hexlit(start)} || ch > {hexlit(end)}"
 
     def in_range(start, end, parenthesize=False):
         """Tests if the input character is in the set {x | start <= x <= end}."""
         if start == end:
-            return "ch == {}".format(hexlit(start))
+            return f"ch == {hexlit(start)}"
         (left, right) = ("(", ")") if parenthesize else ("", "")
-        return "{}ch >= {} && ch <= {}{}".format(
-            left, hexlit(start), hexlit(end), right
-        )
+        return f"{left}ch >= {hexlit(start)} && ch <= {hexlit(end)}{right}"
 
     def in_any_range(ranges, spaces):
         """Tests if the input character is included in any of the given ranges."""
@@ -719,7 +711,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
                 lines[-1].append(expr)
             else:
                 lines.append([expr])
-        return " ||\n{}".format(spaces).join(" || ".join(t) for t in lines)
+        return f" ||\n{spaces}".join(" || ".join(t) for t in lines)
 
     def write_range_accept(parent_list, child_list, depth):
         """Accepts the input character if it matches any code unit in |child_list|."""
@@ -737,11 +729,11 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
         if len(child_ranges) == 1:
             describe_range(child_ranges, depth)
             if has_successor:
-                println(indent, "if (ch <= {}) {{".format(hexlit(max_child)))
-                println(indent, "    return ch >= {};".format(hexlit(min_child)))
+                println(indent, f"if (ch <= {hexlit(max_child)}) {{")
+                println(indent, f"    return ch >= {hexlit(min_child)};")
                 println(indent, "}")
             else:
-                println(indent, "return {};".format(in_range(min_child, max_child)))
+                println(indent, f"return {in_range(min_child, max_child)};")
             return
 
         # Otherwise create a disjunction over the subranges in |child_ranges|.
@@ -752,7 +744,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
         range_test_expr = in_any_range(child_ranges, spaces)
 
         if min_child != min_parent:
-            println(indent, "if (ch < {}) {{".format(hexlit(min_child)))
+            println(indent, f"if (ch < {hexlit(min_child)}) {{")
             println(indent, "    return false;")
             println(indent, "}")
 
@@ -760,11 +752,11 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
         # because it was already checked when we emitted the parent range test.
         if not has_successor:
             describe_range(child_ranges, depth)
-            println(indent, "return {};".format(range_test_expr))
+            println(indent, f"return {range_test_expr};")
         else:
-            println(indent, "if (ch <= {}) {{".format(hexlit(max_child)))
+            println(indent, f"if (ch <= {hexlit(max_child)}) {{")
             describe_range(child_ranges, depth + 1)
-            println(indent, "    return {};".format(range_test_expr))
+            println(indent, f"    return {range_test_expr};")
             println(indent, "}")
 
     def write_ChangesWhenUpperCasedSpecialCasing():
@@ -779,7 +771,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
         code_list = sorted(unconditional_toupper.keys())
 
         # Fail-fast if the input character isn't a special casing character.
-        println("    if ({}) {{".format(out_range(code_list[0], code_list[-1])))
+        println(f"    if ({out_range(code_list[0], code_list[-1])}) {{")
         println("        return false;")
         println("    }")
 
@@ -806,9 +798,9 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
             # largest value in the current range.
             is_last_block = matches[-1] == code_list[-1]
             if not is_last_block:
-                println("    if (ch <= {}) {{".format(hexlit(matches[-1])))
+                println(f"    if (ch <= {hexlit(matches[-1])}) {{")
             else:
-                println("    if (ch < {}) {{".format(hexlit(matches[0])))
+                println(f"    if (ch < {hexlit(matches[0])}) {{")
                 println("        return false;")
                 println("    }")
 
@@ -835,9 +827,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
         println("    switch(ch) {")
         for code, converted in sorted(unconditional_toupper.items(), key=itemgetter(0)):
             println(
-                "      case {}: return {}; // {}".format(
-                    hexlit(code), len(converted), codepoint_table.name(code)
-                )
+                f"      case {hexlit(code)}: return {len(converted)}; // {codepoint_table.name(code)}"
             )
         println("    }")
         println("")
@@ -856,14 +846,10 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
 
         println("    switch(ch) {")
         for code, converted in sorted(unconditional_toupper.items(), key=itemgetter(0)):
-            println(
-                "      case {}: // {}".format(hexlit(code), codepoint_table.name(code))
-            )
+            println(f"      case {hexlit(code)}: // {codepoint_table.name(code)}")
             for ch in converted:
                 println(
-                    "        elements[(*index)++] = {}; // {}".format(
-                        hexlit(ch), codepoint_table.name(ch)
-                    )
+                    f"        elements[(*index)++] = {hexlit(ch)}; // {codepoint_table.name(ch)}"
                 )
             println("        return;")
         println("    }")
@@ -896,11 +882,11 @@ def write_ascii_lookup_tables(table, index, write, println):
         return flags & FLAG_SPACE
 
     def write_entries(name, predicate):
-        println("const bool unicode::{}[] = {{".format(name))
-        header = "".join("{0: <6}".format(x) for x in range(0, 10)).rstrip()
-        println("/*       {}  */".format(header))
+        println(f"const bool unicode::{name}[] = {{")
+        header = "".join(f"{x: <6}" for x in range(0, 10)).rstrip()
+        println(f"/*       {header}  */")
         for i in range(0, 13):
-            write("/* {0: >2} */".format(i))
+            write(f"/* {i: >2} */")
             for j in range(0, 10):
                 code = i * 10 + j
                 if code <= 0x7F:
@@ -958,15 +944,15 @@ def write_latin1_lookup_tables(table, index, write, println):
         return lower
 
     def write_entries(name, mapper):
-        println("const JS::Latin1Char unicode::{}[] = {{".format(name))
-        header = "".join("{0: <6}".format(x) for x in range(0, 16)).rstrip()
-        println("/*       {}  */".format(header))
+        println(f"const JS::Latin1Char unicode::{name}[] = {{")
+        header = "".join(f"{x: <6}" for x in range(0, 16)).rstrip()
+        println(f"/*       {header}  */")
         for i in range(0, 16):
-            write("/* {0: >2} */".format(i))
+            write(f"/* {i: >2} */")
             for j in range(0, 16):
                 code = i * 16 + j
                 if code <= 0xFF:
-                    write(" 0x{:02X},".format(mapper(code)))
+                    write(f" 0x{mapper(code):02X},")
             println("")
         println("};")
 
@@ -978,7 +964,7 @@ def make_bmp_mapping_test(
     version, codepoint_table, unconditional_tolower, unconditional_toupper
 ):
     def unicodeEsc(n):
-        return "\\u{:04X}".format(n)
+        return f"\\u{n:04X}"
 
     file_name = "../tests/non262/String/string-upper-lower-mapping.js"
     with open(file_name, mode="w", encoding="utf-8") as output:
@@ -1042,26 +1028,16 @@ def make_non_bmp_mapping_test(
 
         for code in sorted(non_bmp_upper_map.keys()):
             test_non_bmp_mapping.write(
-                """\
-assertEq(String.fromCodePoint(0x{:04X}).toUpperCase().codePointAt(0), 0x{:04X}); // {}, {}
-""".format(
-                    code,
-                    non_bmp_upper_map[code],
-                    codepoint_table.name(code),
-                    codepoint_table.name(non_bmp_upper_map[code]),
-                )
+                f"""\
+assertEq(String.fromCodePoint(0x{code:04X}).toUpperCase().codePointAt(0), 0x{non_bmp_upper_map[code]:04X}); // {codepoint_table.name(code)}, {codepoint_table.name(non_bmp_upper_map[code])}
+"""
             )
 
         for code in sorted(non_bmp_lower_map.keys()):
             test_non_bmp_mapping.write(
-                """\
-assertEq(String.fromCodePoint(0x{:04X}).toLowerCase().codePointAt(0), 0x{:04X}); // {}, {}
-""".format(
-                    code,
-                    non_bmp_lower_map[code],
-                    codepoint_table.name(code),
-                    codepoint_table.name(non_bmp_lower_map[code]),
-                )
+                f"""\
+assertEq(String.fromCodePoint(0x{code:04X}).toLowerCase().codePointAt(0), 0x{non_bmp_lower_map[code]:04X}); // {codepoint_table.name(code)}, {codepoint_table.name(non_bmp_lower_map[code])}
+"""
             )
 
         test_non_bmp_mapping.write(
@@ -1074,7 +1050,7 @@ if (typeof reportCompare === "function")
 
 def make_space_test(version, test_space_table, codepoint_table):
     def hex_and_name(c):
-        return "    0x{:04X} /* {} */".format(c, codepoint_table.name(c))
+        return f"    0x{c:04X} /* {codepoint_table.name(c)} */"
 
     file_name = "../tests/non262/String/string-space-trim.js"
     with open(file_name, mode="w", encoding="utf-8") as test_space:
@@ -1099,7 +1075,7 @@ if (typeof reportCompare === "function")
 
 def make_regexp_space_test(version, test_space_table, codepoint_table):
     def hex_and_name(c):
-        return "    0x{:04X} /* {} */".format(c, codepoint_table.name(c))
+        return f"    0x{c:04X} /* {codepoint_table.name(c)} */"
 
     file_name = "../tests/non262/RegExp/character-class-escape-s.js"
     with open(file_name, mode="w", encoding="utf-8") as test_space:
@@ -1136,7 +1112,7 @@ if (typeof reportCompare === "function")
 
 def make_icase_test(version, folding_tests, codepoint_table):
     def char_hex(c):
-        return "0x{:04X}".format(c)
+        return f"0x{c:04X}"
 
     file_name = "../tests/non262/RegExp/unicode-ignoreCase.js"
     with open(file_name, mode="w", encoding="utf-8") as test_icase:
@@ -1265,7 +1241,7 @@ def make_unicode_file(
 """
 
     def dump(data, name, println):
-        println("const uint8_t unicode::{}[] = {{".format(name))
+        println(f"const uint8_t unicode::{name}[] = {{")
 
         line = pad = " " * 4
         lines = []
@@ -1285,7 +1261,7 @@ def make_unicode_file(
         println("};")
 
     def write_table(data_type, name, tbl, idx1_name, idx1, idx2_name, idx2, println):
-        println("const {} unicode::{}[] = {{".format(data_type, name))
+        println(f"const {data_type} unicode::{name}[] = {{")
         for d in tbl:
             println("    {{ {} }},".format(", ".join(str(e) for e in d)))
         println("};")
@@ -1298,16 +1274,11 @@ def make_unicode_file(
 
     def write_supplemental_identifier_method(name, group_set, println):
         println("bool")
-        println("js::unicode::{}(char32_t codePoint)".format(name))
+        println(f"js::unicode::{name}(char32_t codePoint)")
         println("{")
         for from_code, to_code in int_ranges(group_set.keys()):
             println(
-                "    if (codePoint >= 0x{:X} && codePoint <= 0x{:X}) {{ // {} .. {}".format(
-                    from_code,
-                    to_code,
-                    codepoint_table.name(from_code),
-                    codepoint_table.name(to_code),
-                )
+                f"    if (codePoint >= 0x{from_code:X} && codePoint <= 0x{to_code:X}) {{ // {codepoint_table.name(from_code)} .. {codepoint_table.name(to_code)}"
             )
             println("        return true;")
             println("    }")
@@ -1461,7 +1432,7 @@ def update_unicode(args):
         print("\tVersion: %s" % version)
         print("\tDownload url: %s" % url)
 
-        request_url = "{}/UCD.zip".format(url)
+        request_url = f"{url}/UCD.zip"
         with closing(urlopen(request_url)) as downloaded_file:
             downloaded_data = io.BytesIO(downloaded_file.read())
 
@@ -1483,13 +1454,13 @@ def update_unicode(args):
         return pat_version.match(f.readline()).group("version")
 
     with open(
-        os.path.join(base_path, "UnicodeData.txt"), "r", encoding="utf-8"
+        os.path.join(base_path, "UnicodeData.txt"), encoding="utf-8"
     ) as unicode_data, open(
-        os.path.join(base_path, "CaseFolding.txt"), "r", encoding="utf-8"
+        os.path.join(base_path, "CaseFolding.txt"), encoding="utf-8"
     ) as case_folding, open(
-        os.path.join(base_path, "DerivedCoreProperties.txt"), "r", encoding="utf-8"
+        os.path.join(base_path, "DerivedCoreProperties.txt"), encoding="utf-8"
     ) as derived_core_properties, open(
-        os.path.join(base_path, "SpecialCasing.txt"), "r", encoding="utf-8"
+        os.path.join(base_path, "SpecialCasing.txt"), encoding="utf-8"
     ) as special_casing:
         unicode_version = version_from_file(
             derived_core_properties, "DerivedCoreProperties"
diff --git a/js/src/vm/jsopcode.py b/js/src/vm/jsopcode.py
index 1d44a0ced261..e41a57211ce2 100644
--- a/js/src/vm/jsopcode.py
+++ b/js/src/vm/jsopcode.py
@@ -149,16 +149,12 @@ def find_by_name(list, name):
 def add_to_index(index, opcode):
     types = find_by_name(index, opcode.category_name)
     if types is None:
-        raise Exception(
-            "Category is not listed in index: "
-            "{name}".format(name=opcode.category_name)
-        )
+        raise Exception("Category is not listed in index: " f"{opcode.category_name}")
     opcodes = find_by_name(types, opcode.type_name)
     if opcodes is None:
         if opcode.type_name:
             raise Exception(
-                "Type is not listed in {category}: "
-                "{name}".format(category=opcode.category_name, name=opcode.type_name)
+                f"Type is not listed in {opcode.category_name}: " f"{opcode.type_name}"
             )
         types.append((opcode.type_name, [opcode]))
         return
@@ -213,7 +209,7 @@ def get_opcodes(dir):
     opcodes = dict()
     index = []
 
-    with open("{dir}/js/src/vm/Opcodes.h".format(dir=dir), "r", encoding="utf-8") as f:
+    with open(f"{dir}/js/src/vm/Opcodes.h", encoding="utf-8") as f:
         data = f.read()
 
     comment_info = None
@@ -267,9 +263,7 @@ def get_opcodes(dir):
                         stack += " " + line.strip()
                 else:
                     raise ValueError(
-                        "unrecognized line in comment: {!r}\n\nfull comment was:\n{}".format(
-                            line, comment
-                        )
+                        f"unrecognized line in comment: {line!r}\n\nfull comment was:\n{comment}"
                     )
 
             comment_info.desc = desc
@@ -300,9 +294,7 @@ def get_opcodes(dir):
                 expected_snake += "_"
             if opcode.op_snake != expected_snake:
                 raise ValueError(
-                    "Unexpected snake-case name for {}: expected {!r}, got {!r}".format(
-                        opcode.op, expected_snake, opcode.op_snake
-                    )
+                    f"Unexpected snake-case name for {opcode.op}: expected {expected_snake!r}, got {opcode.op_snake!r}"
                 )
 
             if not group_head:
@@ -310,46 +302,29 @@ def get_opcodes(dir):
 
                 opcode.sort_key = opcode.op
                 if opcode.category_name == "":
-                    raise Exception(
-                        "Category is not specified for " "{op}".format(op=opcode.op)
-                    )
+                    raise Exception("Category is not specified for " f"{opcode.op}")
                 add_to_index(index, opcode)
             else:
                 if group_head.length != opcode.length:
                     raise Exception(
                         "length should be same for opcodes of the"
                         " same group: "
-                        "{value1}({op1}) != "
-                        "{value2}({op2})".format(
-                            op1=group_head.op,
-                            value1=group_head.length,
-                            op2=opcode.op,
-                            value2=opcode.length,
-                        )
+                        f"{group_head.length}({group_head.op}) != "
+                        f"{opcode.length}({opcode.op})"
                     )
                 if group_head.nuses != opcode.nuses:
                     raise Exception(
                         "nuses should be same for opcodes of the"
                         " same group: "
-                        "{value1}({op1}) != "
-                        "{value2}({op2})".format(
-                            op1=group_head.op,
-                            value1=group_head.nuses,
-                            op2=opcode.op,
-                            value2=opcode.nuses,
-                        )
+                        f"{group_head.nuses}({group_head.op}) != "
+                        f"{opcode.nuses}({opcode.op})"
                     )
                 if group_head.ndefs != opcode.ndefs:
                     raise Exception(
                         "ndefs should be same for opcodes of the"
                         " same group: "
-                        "{value1}({op1}) != "
-                        "{value2}({op2})".format(
-                            op1=group_head.op,
-                            value1=group_head.ndefs,
-                            op2=opcode.op,
-                            value2=opcode.ndefs,
-                        )
+                        f"{group_head.ndefs}({group_head.op}) != "
+                        f"{opcode.ndefs}({opcode.op})"
                     )
 
                 group_head.group.append(opcode)
@@ -368,15 +343,15 @@ def get_opcodes(dir):
 
             if nuses != -1 and stack_nuses != -1 and nuses != stack_nuses:
                 raise Exception(
-                    "nuses should match stack notation: {op}: "
-                    "{nuses} != {stack_nuses} "
-                    "(stack_nuses)".format(op=op, nuses=nuses, stack_nuses=stack_nuses)
+                    f"nuses should match stack notation: {op}: "
+                    f"{nuses} != {stack_nuses} "
+                    "(stack_nuses)"
                 )
             if ndefs != -1 and stack_ndefs != -1 and ndefs != stack_ndefs:
                 raise Exception(
-                    "ndefs should match stack notation: {op}: "
-                    "{ndefs} != {stack_ndefs} "
-                    "(stack_ndefs)".format(op=op, ndefs=ndefs, stack_ndefs=stack_ndefs)
+                    f"ndefs should match stack notation: {op}: "
+                    f"{ndefs} != {stack_ndefs} "
+                    "(stack_ndefs)"
                 )
 
     return index, opcodes
diff --git a/js/src/vm/make_opcode_doc.py b/js/src/vm/make_opcode_doc.py
index f84cf63c660f..80547a18f09b 100755
--- a/js/src/vm/make_opcode_doc.py
+++ b/js/src/vm/make_opcode_doc.py
@@ -111,7 +111,7 @@ def print_opcode(opcode):
     stack_uses = maybe_escape(opcode.stack_uses, "{} ")
     stack_defs = maybe_escape(opcode.stack_defs, " {}")
     if stack_uses or stack_defs:
-        stack = "
Stack: {}⇒{}
\n".format(stack_uses, stack_defs) + stack = f"
Stack: {stack_uses}⇒{stack_defs}
\n" else: stack = "" @@ -132,7 +132,7 @@ id_count = dict() def make_element_id(category, type=""): - key = "{}:{}".format(category, type) + key = f"{category}:{type}" if key in id_cache: return id_cache[key] @@ -143,7 +143,7 @@ def make_element_id(category, type=""): if id in id_count: id_count[id] += 1 - id = "{}_{}".format(id, id_count[id]) + id = f"{id}_{id_count[id]}" else: id_count[id] = 1 @@ -153,30 +153,22 @@ def make_element_id(category, type=""): def print_doc(index): print( - """
{{{{SpiderMonkeySidebar("Internals")}}}}
+ f"""
{{{{SpiderMonkeySidebar("Internals")}}}}

Bytecode Listing

This document is automatically generated from -Opcodes.h by -make_opcode_doc.py.

-""".format( - source_base=SOURCE_BASE - ) +Opcodes.h by +make_opcode_doc.py.

+""" ) for category_name, types in index: - print( - '

{name}

'.format( - name=category_name, id=make_element_id(category_name) - ) - ) + print(f'

{category_name}

') for type_name, opcodes in types: if type_name: print( - '

{name}

'.format( - name=type_name, id=make_element_id(category_name, type_name) - ) + f'

{type_name}

' ) print("
") for opcode in opcodes: diff --git a/js/xpconnect/loader/script_cache.py b/js/xpconnect/loader/script_cache.py index 0affa5a088f2..14dce3e2dfb7 100755 --- a/js/xpconnect/loader/script_cache.py +++ b/js/xpconnect/loader/script_cache.py @@ -46,7 +46,7 @@ class ProcessTypes: return "|".join(res) -class InputBuffer(object): +class InputBuffer: def __init__(self, data): self.data = data self.offset = 0 @@ -83,8 +83,8 @@ for filename in sys.argv[1:]: i = 0 while hdr.remaining: i += 1 - print("{}: {}".format(i, hdr.unpack_str())) - print(" Key: {}".format(hdr.unpack_str())) + print(f"{i}: {hdr.unpack_str()}") + print(f" Key: {hdr.unpack_str()}") print(" Offset: {:>9,}".format(*hdr.unpack("9,}".format(*hdr.unpack(" 0 diff --git a/memory/replace/dmd/block_analyzer.py b/memory/replace/dmd/block_analyzer.py index 1f907b38a7c7..99d1df8220a2 100644 --- a/memory/replace/dmd/block_analyzer.py +++ b/memory/replace/dmd/block_analyzer.py @@ -68,7 +68,7 @@ allocatorFns = [ def range_1_24(string): value = int(string) if value < 1 or value > 24: - msg = "{:s} is not in the range 1..24".format(string) + msg = f"{string:s} is not in the range 1..24" raise argparse.ArgumentTypeError(msg) return value @@ -169,9 +169,7 @@ def show_referrers(args, blocks, stacks, block): which_edge += 1 for r in referrers: - sys.stdout.write( - "0x{} size = {} bytes".format(blocks[r].addr, blocks[r].req_size) - ) + sys.stdout.write(f"0x{blocks[r].addr} size = {blocks[r].req_size} bytes") plural = "s" if len(referrers[r]) > 1 else "" print( " at byte offset" @@ -206,13 +204,13 @@ def show_referrers(args, blocks, stacks, block): def show_block_info(args, blocks, stacks, block): b = blocks[block] - sys.stdout.write("block: 0x{}\n".format(b.addr)) - sys.stdout.write("requested size: {} bytes\n".format(b.req_size)) + sys.stdout.write(f"block: 0x{b.addr}\n") + sys.stdout.write(f"requested size: {b.req_size} bytes\n") sys.stdout.write("\n") sys.stdout.write("block contents: ") for c in b.contents: v = "0" if c == 0 else blocks[c].addr - sys.stdout.write("0x{} ".format(v)) + sys.stdout.write(f"0x{v} ") sys.stdout.write("\n\n") sys.stdout.write("allocation stack:\n") print_trace_segment(args, stacks, b) @@ -253,7 +251,7 @@ def loadGraph(options): j = json.load(f) if j["version"] != outputVersion: - raise Exception("'version' property isn't '{:d}'".format(outputVersion)) + raise Exception(f"'version' property isn't '{outputVersion:d}'") block_list = j["blockList"] blocks = {} diff --git a/memory/replace/dmd/dmd.py b/memory/replace/dmd/dmd.py index b2cde0b2ed09..2a53438d80a3 100755 --- a/memory/replace/dmd/dmd.py +++ b/memory/replace/dmd/dmd.py @@ -58,7 +58,7 @@ def cmp(a, b): return (a > b) - (a < b) -class Record(object): +class Record: """A record is an aggregation of heap blocks that have identical stack traces. It can also be used to represent the difference between two records.""" @@ -164,7 +164,7 @@ def parseCommandLine(): def range_1_24(string): value = int(string) if value < 1 or value > 24: - msg = "{:s} is not in the range 1..24".format(string) + msg = f"{string:s} is not in the range 1..24" raise argparse.ArgumentTypeError(msg) return value @@ -320,7 +320,7 @@ def getDigestFromFile(args, inputFile): j = json.load(f) if j["version"] != outputVersion: - raise Exception("'version' property isn't '{:d}'".format(outputVersion)) + raise Exception(f"'version' property isn't '{outputVersion:d}'") # Extract the main parts of the JSON object. invocation = j["invocation"] @@ -345,7 +345,7 @@ def getDigestFromFile(args, inputFile): mode = "live" if mode not in ["live", "dark-matter", "cumulative"]: - raise Exception("bad 'mode' property: '{:s}'".format(mode)) + raise Exception(f"bad 'mode' property: '{mode:s}'") # Remove allocation functions at the start of traces. if args.ignore_alloc_fns: @@ -602,7 +602,7 @@ def printDigest(args, digest): def number(n): """Format a number with comma as a separator.""" - return "{:,d}".format(n) + return f"{n:,d}" def perc(m, n): return 0 if n == 0 else (100 * m / n) @@ -658,26 +658,20 @@ def printDigest(args, digest): # Second iteration: print. if numRecords == 0: - out("# no {:} heap blocks\n".format(recordKind)) + out(f"# no {recordKind} heap blocks\n") kindCumulativeUsableSize = 0 for i, record in enumerate(sortedRecords, start=1): # Stop printing at the |maxRecord|th record. if i == maxRecord: - out( - "# {:}: stopping after {:,d} heap block records\n".format( - RecordKind, i - ) - ) + out(f"# {RecordKind}: stopping after {i:,d} heap block records\n") break kindCumulativeUsableSize += record.usableSize out(RecordKind + " {") out( - " {:} block{:} in heap block record {:,d} of {:,d}".format( - number(record.numBlocks), plural(record.numBlocks), i, numRecords - ) + f" {number(record.numBlocks)} block{plural(record.numBlocks)} in heap block record {i:,d} of {numRecords:,d}" ) if record.addrs: if args.filter_stacks_for_testing: @@ -688,11 +682,7 @@ def printDigest(args, digest): addrsString = ", ".join([f"0x{a}" for a in baseAddrs]) out(" block addresses: " + addrsString) out( - " {:} bytes ({:} requested / {:} slop)".format( - number(record.usableSize), - number(record.reqSize), - number(record.slopSize), - ) + f" {number(record.usableSize)} bytes ({number(record.reqSize)} requested / {number(record.slopSize)} slop)" ) usableSizes = sorted( @@ -709,27 +699,20 @@ def printDigest(args, digest): for usableSize, count in usableSizes: if not isFirst: out("; ", end="") - out("{:}".format(number(usableSize)), end="") + out(f"{number(usableSize)}", end="") if count > 1: - out(" x {:,d}".format(count), end="") + out(f" x {count:,d}", end="") isFirst = False out() out( - " {:4.2f}% of the heap ({:4.2f}% cumulative)".format( - perc(record.usableSize, heapUsableSize), - perc(kindCumulativeUsableSize, heapUsableSize), - ) + f" {perc(record.usableSize, heapUsableSize):4.2f}% of the heap ({perc(kindCumulativeUsableSize, heapUsableSize):4.2f}% cumulative)" ) if mode in ["live", "cumulative"]: pass elif mode == "dark-matter": out( - " {:4.2f}% of {:} ({:4.2f}% cumulative)".format( - perc(record.usableSize, kindUsableSize), - recordKind, - perc(kindCumulativeUsableSize, kindUsableSize), - ) + f" {perc(record.usableSize, kindUsableSize):4.2f}% of {recordKind} ({perc(kindCumulativeUsableSize, kindUsableSize):4.2f}% cumulative)" ) out(" Allocated at {") printStack(record.allocatedAtDesc) @@ -739,7 +722,7 @@ def printDigest(args, digest): elif mode == "dark-matter": for n, reportedAtDesc in enumerate(record.reportedAtDescs): again = "again " if n > 0 else "" - out(" Reported {:}at {{".format(again)) + out(f" Reported {again}at {{") printStack(reportedAtDesc) out(" }") out("}\n") @@ -747,7 +730,7 @@ def printDigest(args, digest): return (kindUsableSize, kindBlocks) def printInvocation(n, dmdEnvVar, mode): - out("Invocation{:} {{".format(n)) + out(f"Invocation{n} {{") if dmdEnvVar is None: out(" $DMD is undefined") else: @@ -790,9 +773,7 @@ def printDigest(args, digest): out("Summary {") if mode in ["live", "cumulative"]: out( - " Total: {:} bytes in {:} blocks".format( - number(liveOrCumulativeUsableSize), number(liveOrCumulativeBlocks) - ) + f" Total: {number(liveOrCumulativeUsableSize)} bytes in {number(liveOrCumulativeBlocks)} blocks" ) elif mode == "dark-matter": fmt = " {:15} {:>12} bytes ({:6.2f}%) in {:>7} blocks ({:6.2f}%)" @@ -853,7 +834,7 @@ def prettyPrintDmdJson(out, j): first = True for k, l in j["traceTable"].items(): out.write("" if first else ",") - out.write('\n "{0}": {1}'.format(k, json.dumps(l))) + out.write(f'\n "{k}": {json.dumps(l)}') first = False out.write("\n },\n") @@ -861,7 +842,7 @@ def prettyPrintDmdJson(out, j): first = True for k, v in j["frameTable"].items(): out.write("" if first else ",") - out.write('\n "{0}": {1}'.format(k, json.dumps(v))) + out.write(f'\n "{k}": {json.dumps(v)}') first = False out.write("\n }\n") @@ -960,7 +941,7 @@ def clampBlockList(args, inputFileName, isZipped, opener): j = json.load(f) if j["version"] != outputVersion: - raise Exception("'version' property isn't '{:d}'".format(outputVersion)) + raise Exception(f"'version' property isn't '{outputVersion:d}'") # Check that the invocation is reasonable for contents clamping. invocation = j["invocation"] diff --git a/memory/replace/dmd/test/scan-test.py b/memory/replace/dmd/test/scan-test.py index c282b026934e..6d540de480e3 100644 --- a/memory/replace/dmd/test/scan-test.py +++ b/memory/replace/dmd/test/scan-test.py @@ -66,13 +66,13 @@ def main(): j = json.load(f) if j["version"] != outputVersion: - raise Exception("'version' property isn't '{:d}'".format(outputVersion)) + raise Exception(f"'version' property isn't '{outputVersion:d}'") invocation = j["invocation"] mode = invocation["mode"] if mode != "scan": - raise Exception("bad 'mode' property: '{:s}'".format(mode)) + raise Exception(f"bad 'mode' property: '{mode:s}'") blockList = j["blockList"] diff --git a/memory/replace/logalloc/replay/logalloc_munge.py b/memory/replace/logalloc/replay/logalloc_munge.py index 52d0032463a8..08e8a5e8dc12 100644 --- a/memory/replace/logalloc/replay/logalloc_munge.py +++ b/memory/replace/logalloc/replay/logalloc_munge.py @@ -22,7 +22,7 @@ import sys from collections import defaultdict, deque -class IdMapping(object): +class IdMapping: """Class to map values to ids. Each value is associated to an increasing id, starting from 1. diff --git a/mobile/android/android-components/automation/taskcluster/androidTest/parse-ui-test-fromfile.py b/mobile/android/android-components/automation/taskcluster/androidTest/parse-ui-test-fromfile.py index 58f6f307dc51..5aa82059ece9 100644 --- a/mobile/android/android-components/automation/taskcluster/androidTest/parse-ui-test-fromfile.py +++ b/mobile/android/android-components/automation/taskcluster/androidTest/parse-ui-test-fromfile.py @@ -117,7 +117,7 @@ def parse_print_failure_results(results): def load_results_file(filename): ret = None try: - f = open(filename, "r") + f = open(filename) try: ret = JUnitXml.fromfile(f) except xml.etree.ElementTree.ParseError as e: diff --git a/mobile/android/android-components/plugins/dependencies/src/main/java/appservices_version_bump.py b/mobile/android/android-components/plugins/dependencies/src/main/java/appservices_version_bump.py index 70d5a8f980a0..eaf0a523cebe 100755 --- a/mobile/android/android-components/plugins/dependencies/src/main/java/appservices_version_bump.py +++ b/mobile/android/android-components/plugins/dependencies/src/main/java/appservices_version_bump.py @@ -206,7 +206,7 @@ def main(): import sys if len(sys.argv) != 2: - print("Usage: {} ".format(sys.argv[0]), file=sys.stderr) + print(f"Usage: {sys.argv[0]} ", file=sys.stderr) sys.exit(1) update_application_services(sys.argv[1]) diff --git a/mobile/android/beta-cut.py b/mobile/android/beta-cut.py index c51e36479fc2..8e791fa46e0e 100755 --- a/mobile/android/beta-cut.py +++ b/mobile/android/beta-cut.py @@ -60,7 +60,7 @@ def get_bug_id(): def get_previous_version(): """Extract the previous version number from the changelog.""" - with open(CHANGELOG_FILE, "r") as file: + with open(CHANGELOG_FILE) as file: content = file.read() match = re.search(r"# (\d+)\.0 \(In Development\)", content) if not match: @@ -73,7 +73,7 @@ def get_previous_version(): def update_changelog(previous_version, new_version): """Update the changelog with the new version number.""" - with open(CHANGELOG_FILE, "r") as file: + with open(CHANGELOG_FILE) as file: content = file.read() updated_content = content.replace( f"# {previous_version}.0 (In Development)", diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/adbrun.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/adbrun.py index 91f4e4cf3d16..4d0788007463 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/adbrun.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/adbrun.py @@ -5,7 +5,7 @@ from pathlib import Path logging.getLogger(__name__).addHandler(logging.NullHandler()) -class ADBrun(object): +class ADBrun: binary = "adbrun" logger = logging.getLogger() here = Path() diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/generate_smoke_tests.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/generate_smoke_tests.py index 3fa4e96db919..a155fc52f3fb 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/generate_smoke_tests.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/generate_smoke_tests.py @@ -29,7 +29,7 @@ def search_for_smoke_tests(tests_name): file_name = name break - with open(file_name, "r") as file: + with open(file_name) as file: code = file.read().split(" ") code = [item for item in code if item != ""] @@ -90,7 +90,7 @@ if __name__ == "__main__": if args.test_files: test_modules = args.test_files else: - with open("variables.yaml", "r") as file: + with open("variables.yaml") as file: tests = yaml.safe_load(file) test_modules = [test for test in tests.get("smoke_tests")] create_test_file() diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/gradlewbuild.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/gradlewbuild.py index 9a994120b540..3bf212c09211 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/gradlewbuild.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/experimentintegration/gradlewbuild.py @@ -8,7 +8,7 @@ here = os.path.dirname(__file__) logging.getLogger(__name__).addHandler(logging.NullHandler()) -class GradlewBuild(object): +class GradlewBuild: binary = "./gradlew" logger = logging.getLogger() adbrun = ADBrun() @@ -24,7 +24,7 @@ class GradlewBuild(object): test_type = "ui" if smoke else "experimentintegration" cmd = f"adb shell am instrument -w -e class org.mozilla.fenix.{test_type}.{identifier} -e EXP_NAME '{os.getenv('EXP_NAME', '').replace('(', '').replace(')', '')}' org.mozilla.fenix.debug.test/androidx.test.runner.AndroidJUnitRunner" - self.logger.info("Running cmd: {}".format(cmd)) + self.logger.info(f"Running cmd: {cmd}") out = "" try: diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/adbrun.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/adbrun.py index be4244674e2c..b220e3e63449 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/adbrun.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/adbrun.py @@ -4,7 +4,7 @@ import os logging.getLogger(__name__).addHandler(logging.NullHandler()) -class ADBrun(object): +class ADBrun: binary = "adbrun" logger = logging.getLogger() diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/conftest.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/conftest.py index 3b68302cde9b..63ea600f0aa1 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/conftest.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/conftest.py @@ -48,10 +48,10 @@ def tps_addon(pytestconfig, tmpdir_factory): "gecko.v2.mozilla-central.latest.firefox.addons.tps" ) task_id = requests.get(task_url).json().get("taskId") - cache_dir = str(pytestconfig.cache.makedir("tps-{}".format(task_id))) + cache_dir = str(pytestconfig.cache.makedir(f"tps-{task_id}")) addon_url = ( "https://firefox-ci-tc.services.mozilla.com/api/queue/v1/task/" - "{}/artifacts/public/tps.xpi".format(task_id) + f"{task_id}/artifacts/public/tps.xpi" ) scraper = DirectScraper(addon_url, destination=cache_dir) return scraper.download() @@ -177,15 +177,15 @@ def pytest_runtest_makereport(item, call): for f in files: path = os.path.join(root, f) if pytest_html is not None: - with open(path, "r", encoding="utf8") as f: + with open(path, encoding="utf8") as f: extra.append(pytest_html.extras.text(f.read(), "Sync")) - report.sections.append(("Sync", "Log: {}".format(path))) + report.sections.append(("Sync", f"Log: {path}")) for log in ("Firefox", "TPS", "GradlewBuild"): - attr = "_{}_log".format(log.lower()) + attr = f"_{log.lower()}_log" path = getattr(item.config, attr, None) if path is not None and os.path.exists(path): if pytest_html is not None: - with open(path, "r", encoding="utf8") as f: + with open(path, encoding="utf8") as f: extra.append(pytest_html.extras.text(f.read(), log)) - report.sections.append((log, "Log: {}".format(path))) + report.sections.append((log, f"Log: {path}")) report.extra = extra diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/gradlewbuild.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/gradlewbuild.py index 1cd65a6f456c..4af53159a9d4 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/gradlewbuild.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/gradlewbuild.py @@ -8,7 +8,7 @@ here = os.path.dirname(__file__) logging.getLogger(__name__).addHandler(logging.NullHandler()) -class GradlewBuild(object): +class GradlewBuild: binary = "./gradlew" logger = logging.getLogger() adbrun = ADBrun() @@ -23,12 +23,10 @@ class GradlewBuild(object): os.chdir("../../../../../../../..") cmd = ( "./gradlew " - + "app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=org.mozilla.fenix.syncintegration.SyncIntegrationTest#{}".format( - identifier - ) + + f"app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=org.mozilla.fenix.syncintegration.SyncIntegrationTest#{identifier}" ) - self.logger.info("Running cmd: {}".format(cmd)) + self.logger.info(f"Running cmd: {cmd}") out = "" try: diff --git a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/tps.py b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/tps.py index af3204c794a3..1ea224dae139 100644 --- a/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/tps.py +++ b/mobile/android/fenix/app/src/androidTest/java/org/mozilla/fenix/syncintegration/tps.py @@ -8,7 +8,7 @@ logging.getLogger(__name__).addHandler(logging.NullHandler()) TIMEOUT = 60 -class TPS(object): +class TPS: logger = logging.getLogger() def __init__(self, firefox, firefox_log, tps_log, profile): @@ -31,7 +31,7 @@ class TPS(object): args = ["-marionette"] process_args = {"processOutputLine": [self._log]} self.logger.info("Running: {} {}".format(self.firefox, " ".join(args))) - self.logger.info("Using profile at: {}".format(self.profile.profile)) + self.logger.info(f"Using profile at: {self.profile.profile}") runner = FirefoxRunner( binary=self.firefox, cmdargs=args, @@ -48,7 +48,7 @@ class TPS(object): raise TPSError(line.partition("CROSSWEAVE ERROR: ")[-1]) with open(self.tps_log) as f: - assert "test phase {}: PASS".format(phase) in f.read() + assert f"test phase {phase}: PASS" in f.read() class TPSError(Exception): diff --git a/mobile/android/fenix/automation/taskcluster/androidTest/parse-ui-test-fromfile.py b/mobile/android/fenix/automation/taskcluster/androidTest/parse-ui-test-fromfile.py index 58f6f307dc51..5aa82059ece9 100644 --- a/mobile/android/fenix/automation/taskcluster/androidTest/parse-ui-test-fromfile.py +++ b/mobile/android/fenix/automation/taskcluster/androidTest/parse-ui-test-fromfile.py @@ -117,7 +117,7 @@ def parse_print_failure_results(results): def load_results_file(filename): ret = None try: - f = open(filename, "r") + f = open(filename) try: ret = JUnitXml.fromfile(f) except xml.etree.ElementTree.ParseError as e: diff --git a/mobile/android/fenix/tools/data_renewal_generate.py b/mobile/android/fenix/tools/data_renewal_generate.py index 4a4f2390ae3f..ae64834a416c 100755 --- a/mobile/android/fenix/tools/data_renewal_generate.py +++ b/mobile/android/fenix/tools/data_renewal_generate.py @@ -111,7 +111,7 @@ def response(last_key, content, expire_version, writer, renewal): response(last_key + "." + key, value, expire_version, writer, renewal) -with open(METRICS_FILENAME, "r") as f: +with open(METRICS_FILENAME) as f: try: arg1 = sys.argv[1] except Exception: diff --git a/mobile/android/fenix/tools/data_renewal_request.py b/mobile/android/fenix/tools/data_renewal_request.py index 5f14292b0d9d..add584059c03 100755 --- a/mobile/android/fenix/tools/data_renewal_request.py +++ b/mobile/android/fenix/tools/data_renewal_request.py @@ -21,7 +21,7 @@ except Exception: expiry_filename = version + "_expiry_list.csv" filled_renewal_filename = version + "_filled_renewal_request.txt" -csv_reader = csv.DictReader(open(expiry_filename, "r")) +csv_reader = csv.DictReader(open(expiry_filename)) output_string = "" total_count = 0 updated_version = int(version) + 13 diff --git a/mobile/android/fenix/tools/run_benchmark.py b/mobile/android/fenix/tools/run_benchmark.py index 527ef2c93242..59a09fb8cc83 100644 --- a/mobile/android/fenix/tools/run_benchmark.py +++ b/mobile/android/fenix/tools/run_benchmark.py @@ -12,7 +12,7 @@ the JSON output file in firefox (or another browser of your choice if you pass t """ ff_browser = "firefox" -target_directory = "{cwd}/app/build/".format(cwd=os.getcwd()) +target_directory = f"{os.getcwd()}/app/build/" output_path = "/storage/emulated/0/benchmark/" output_file = "org.mozilla.fenix-benchmarkData.json" file_url = "file:///" @@ -35,33 +35,27 @@ def run_benchmark(class_to_test): args = ["./gradlew", "-Pbenchmark", "app:connectedCheck"] if class_to_test: args.append( - "-Pandroid.testInstrumentationRunnerArguments.class={clazz}".format( - clazz=class_to_test - ) + f"-Pandroid.testInstrumentationRunnerArguments.class={class_to_test}" ) subprocess.run(args, check=True, text=True) def fetch_benchmark_results(): subprocess.run( - ["adb", "pull", "{path}{file}".format(path=output_path, file=output_file)], + ["adb", "pull", f"{output_path}{output_file}"], cwd=target_directory, check=True, text=True, ) print( "The benchmark results can be seen here: {file_path}".format( - file_path=os.path.abspath("./{file}".format(file=file_url)) + file_path=os.path.abspath(f"./{file_url}") ) ) def open_in_browser(): - abs_path = os.path.abspath( - "{target_directory}{file}".format( - target_directory=target_directory, file=output_file - ) - ) + abs_path = os.path.abspath(f"{target_directory}{output_file}") webbrowser.get(ff_browser).open_new(file_url + abs_path) diff --git a/mobile/android/fenix/tools/setup-startup-profiling.py b/mobile/android/fenix/tools/setup-startup-profiling.py index 788e39f71925..0b74e80266a5 100755 --- a/mobile/android/fenix/tools/setup-startup-profiling.py +++ b/mobile/android/fenix/tools/setup-startup-profiling.py @@ -72,7 +72,7 @@ def push(id, filename): with config.file as f: f.write(GV_CONFIG) - print("Pushing {} to device.".format(filename)) + print(f"Pushing {filename} to device.") run(["adb", "push", config.name, os.path.join(PATH_PREFIX, filename)]) run(["adb", "shell", "am", "set-debug-app", "--persistent", id]) print( @@ -89,7 +89,7 @@ def push(id, filename): def remove(filename): - print("Removing {} from device.".format(filename)) + print(f"Removing {filename} from device.") run(["adb", "shell", "rm", PATH_PREFIX + "/" + filename]) run(["adb", "shell", "am", "clear-debug-app"]) diff --git a/mobile/android/fenix/tools/update-glean-tags.py b/mobile/android/fenix/tools/update-glean-tags.py index c2f649832c2a..b9e9e7e08e76 100755 --- a/mobile/android/fenix/tools/update-glean-tags.py +++ b/mobile/android/fenix/tools/update-glean-tags.py @@ -53,6 +53,6 @@ for label in labels: } open(TAGS_FILENAME, "w").write( - "{}\n{}\n\n".format(LICENSE_HEADER, GENERATED_HEADER) + f"{LICENSE_HEADER}\n{GENERATED_HEADER}\n\n" + yaml.dump(tags, width=78, explicit_start=True) ) diff --git a/mobile/android/focus-android/automation/taskcluster/androidTest/parse-ui-test-fromfile.py b/mobile/android/focus-android/automation/taskcluster/androidTest/parse-ui-test-fromfile.py index 58f6f307dc51..5aa82059ece9 100644 --- a/mobile/android/focus-android/automation/taskcluster/androidTest/parse-ui-test-fromfile.py +++ b/mobile/android/focus-android/automation/taskcluster/androidTest/parse-ui-test-fromfile.py @@ -117,7 +117,7 @@ def parse_print_failure_results(results): def load_results_file(filename): ret = None try: - f = open(filename, "r") + f = open(filename) try: ret = JUnitXml.fromfile(f) except xml.etree.ElementTree.ParseError as e: diff --git a/mobile/android/focus-android/tools/data_renewal_generate.py b/mobile/android/focus-android/tools/data_renewal_generate.py index 43dba385410a..14dc362a1ab7 100755 --- a/mobile/android/focus-android/tools/data_renewal_generate.py +++ b/mobile/android/focus-android/tools/data_renewal_generate.py @@ -113,7 +113,7 @@ def response(last_key, content, expire_version, writer, renewal): response(last_key + "." + key, value, expire_version, writer, renewal) -with open(METRICS_FILENAME, "r") as f: +with open(METRICS_FILENAME) as f: try: arg1 = sys.argv[1] except Exception: diff --git a/mobile/android/focus-android/tools/data_renewal_request.py b/mobile/android/focus-android/tools/data_renewal_request.py index 5f14292b0d9d..add584059c03 100755 --- a/mobile/android/focus-android/tools/data_renewal_request.py +++ b/mobile/android/focus-android/tools/data_renewal_request.py @@ -21,7 +21,7 @@ except Exception: expiry_filename = version + "_expiry_list.csv" filled_renewal_filename = version + "_filled_renewal_request.txt" -csv_reader = csv.DictReader(open(expiry_filename, "r")) +csv_reader = csv.DictReader(open(expiry_filename)) output_string = "" total_count = 0 updated_version = int(version) + 13 diff --git a/mobile/android/focus-android/tools/update-glean-tags.py b/mobile/android/focus-android/tools/update-glean-tags.py index 8e77a8241bfe..0096f3a939ee 100755 --- a/mobile/android/focus-android/tools/update-glean-tags.py +++ b/mobile/android/focus-android/tools/update-glean-tags.py @@ -53,6 +53,6 @@ for label in labels: } open(TAGS_FILENAME, "w").write( - "{}\n{}\n\n".format(LICENSE_HEADER, GENERATED_HEADER) + f"{LICENSE_HEADER}\n{GENERATED_HEADER}\n\n" + yaml.dump(tags, width=78, explicit_start=True) ) diff --git a/mobile/android/gradle.py b/mobile/android/gradle.py index d969c54e5695..5f31cf13a112 100644 --- a/mobile/android/gradle.py +++ b/mobile/android/gradle.py @@ -18,7 +18,7 @@ def gradle_lock(topobjdir, max_wait_seconds=600): # Building the same Gradle root project with multiple concurrent processes # is not well supported, so we use a simple lock file to serialize build # steps. - lock_path = "{}/gradle/mach_android.lockfile".format(topobjdir) + lock_path = f"{topobjdir}/gradle/mach_android.lockfile" ensureParentDir(lock_path) with SoftFileLock(lock_path, timeout=max_wait_seconds): yield diff --git a/modules/libpref/init/generate_static_pref_list.py b/modules/libpref/init/generate_static_pref_list.py index 6be7223d68f1..df14fd4a81a3 100644 --- a/modules/libpref/init/generate_static_pref_list.py +++ b/modules/libpref/init/generate_static_pref_list.py @@ -150,18 +150,18 @@ def check_pref_list(pref_list): # Check all given keys are known ones. for key in pref: if key not in VALID_KEYS: - error("invalid key `{}`".format(key)) + error(f"invalid key `{key}`") # 'name' must be present, valid, and in the right section. if "name" not in pref: error("missing `name` key") name = pref["name"] if type(name) is not str: - error("non-string `name` value `{}`".format(name)) + error(f"non-string `name` value `{name}`") if "." not in name: - error("`name` value `{}` lacks a '.'".format(name)) + error(f"`name` value `{name}` lacks a '.'") if name in seen_names: - error("`{}` pref is defined more than once".format(name)) + error(f"`{name}` pref is defined more than once") seen_names.add(name) # Prefs must be ordered appropriately. @@ -175,41 +175,41 @@ def check_pref_list(pref_list): # 'type' must be present and valid. if "type" not in pref: - error("missing `type` key for pref `{}`".format(name)) + error(f"missing `type` key for pref `{name}`") typ = pref["type"] if typ not in VALID_TYPES: - error("invalid `type` value `{}` for pref `{}`".format(typ, name)) + error(f"invalid `type` value `{typ}` for pref `{name}`") # 'value' must be present and valid. if "value" not in pref: - error("missing `value` key for pref `{}`".format(name)) + error(f"missing `value` key for pref `{name}`") value = pref["value"] if typ == "String" or typ == "DataMutexString": if type(value) is not str: error( - "non-string `value` value `{}` for `{}` pref `{}`; " - "add double quotes".format(value, typ, name) + f"non-string `value` value `{value}` for `{typ}` pref `{name}`; " + "add double quotes" ) elif typ in VALID_BOOL_TYPES: if value not in (True, False): - error("invalid boolean value `{}` for pref `{}`".format(value, name)) + error(f"invalid boolean value `{value}` for pref `{name}`") # 'mirror' must be present and valid. if "mirror" not in pref: - error("missing `mirror` key for pref `{}`".format(name)) + error(f"missing `mirror` key for pref `{name}`") mirror = pref["mirror"] if typ.startswith("DataMutex"): mirror += "_datamutex" if mirror not in MIRROR_TEMPLATES: - error("invalid `mirror` value `{}` for pref `{}`".format(mirror, name)) + error(f"invalid `mirror` value `{mirror}` for pref `{name}`") # Check 'do_not_use_directly' if present. if "do_not_use_directly" in pref: do_not_use_directly = pref["do_not_use_directly"] if type(do_not_use_directly) is not bool: error( - "non-boolean `do_not_use_directly` value `{}` for pref " - "`{}`".format(do_not_use_directly, name) + f"non-boolean `do_not_use_directly` value `{do_not_use_directly}` for pref " + f"`{name}`" ) if do_not_use_directly and mirror == "never": error( @@ -221,22 +221,18 @@ def check_pref_list(pref_list): if "include" in pref: include = pref["include"] if type(include) is not str: - error( - "non-string `include` value `{}` for pref `{}`".format( - include, name - ) - ) + error(f"non-string `include` value `{include}` for pref `{name}`") if include.startswith("<") and not include.endswith(">"): error( - "`include` value `{}` starts with `<` but does not " - "end with `>` for pref `{}`".format(include, name) + f"`include` value `{include}` starts with `<` but does not " + f"end with `>` for pref `{name}`" ) # Check 'rust' if present. if "rust" in pref: rust = pref["rust"] if type(rust) is not bool: - error("non-boolean `rust` value `{}` for pref `{}`".format(rust, name)) + error(f"non-boolean `rust` value `{rust}` for pref `{name}`") if rust and mirror == "never": error( "`rust` uselessly set with `mirror` value `never` for " @@ -290,7 +286,7 @@ def generate_code(pref_list, input_filename): if include: if not include.startswith("<"): # It's not a system header. Add double quotes. - include = '"{}"'.format(include) + include = f'"{include}"' includes[group].add(include) if typ == "String": @@ -361,7 +357,7 @@ def generate_code(pref_list, input_filename): # line per pref group. static_pref_list_all_h = [first_line, ""] static_pref_list_all_h.extend( - '#include "mozilla/StaticPrefList_{}.h"'.format(group) + f'#include "mozilla/StaticPrefList_{group}.h"' for group in sorted(static_pref_list_group_h) ) static_pref_list_all_h.append("") @@ -370,7 +366,7 @@ def generate_code(pref_list, input_filename): # pref group. static_prefs_all_h = [first_line, ""] static_prefs_all_h.extend( - '#include "mozilla/StaticPrefs_{}.h"'.format(group) + f'#include "mozilla/StaticPrefs_{group}.h"' for group in sorted(static_pref_list_group_h) ) static_prefs_all_h.append("") @@ -386,7 +382,7 @@ def generate_code(pref_list, input_filename): if group in includes: # Add any necessary includes, from 'h_include' values. for include in sorted(includes[group]): - static_prefs_group_h[group].append("#include {}".format(include)) + static_prefs_group_h[group].append(f"#include {include}") static_prefs_group_h[group].append("") static_prefs_group_h[group].append( STATIC_PREFS_GROUP_H_TEMPLATE2.format(group=group) @@ -440,7 +436,7 @@ def emit_code(fd, pref_list_filename): ) code = generate_code(pref_list, input_file) except (OSError, ValueError) as e: - print("{}: error:\n {}\n".format(pref_list_filename, e)) + print(f"{pref_list_filename}: error:\n {e}\n") sys.exit(1) # When generating multiple files from a script, the build system treats the @@ -458,12 +454,12 @@ def emit_code(fd, pref_list_filename): fd.write(code["static_prefs_all_h"]) for group, text in sorted(code["static_pref_list_group_h"].items()): - filename = "StaticPrefList_{}.h".format(group) + filename = f"StaticPrefList_{group}.h" with FileAvoidWrite(os.path.join(init_dirname, filename)) as fd: fd.write(text) for group, text in sorted(code["static_prefs_group_h"].items()): - filename = "StaticPrefs_{}.h".format(group) + filename = f"StaticPrefs_{group}.h" with FileAvoidWrite(os.path.join(dirname, filename)) as fd: fd.write(text) diff --git a/moz.configure b/moz.configure index 5e9cc42a9715..8798d30aa0d2 100755 --- a/moz.configure +++ b/moz.configure @@ -368,7 +368,7 @@ def plain_llvm_or_prefixed(name, llvm_name=None): # 2. ${toolchain_prefix}${name} # 3. ${name} - @depends(llvm_tool("llvm-{}".format(llvm_name or name)), toolchain_prefix) + @depends(llvm_tool(f"llvm-{llvm_name or name}"), toolchain_prefix) def plain_llvm_or_prefixed(llvm_tool, toolchain_prefix): commands = [llvm_tool[0], name] for prefix in toolchain_prefix or (): diff --git a/mozglue/baseprofiler/build/generate_profiling_categories.py b/mozglue/baseprofiler/build/generate_profiling_categories.py index fb632d1fcf6d..2d1fc6d6481d 100644 --- a/mozglue/baseprofiler/build/generate_profiling_categories.py +++ b/mozglue/baseprofiler/build/generate_profiling_categories.py @@ -107,9 +107,7 @@ def load_yaml(yaml_path): def generate_category_macro(name, label, color, subcategories): - contents = ' BEGIN_CATEGORY({name}, "{label}", "{color}") \\\n'.format( - name=name, label=label, color=color - ) + contents = f' BEGIN_CATEGORY({name}, "{label}", "{color}") \\\n' subcategory_items = [] @@ -120,9 +118,7 @@ def generate_category_macro(name, label, color, subcategories): assert isinstance(subcat_label, str) subcategory_items.append( - ' SUBCATEGORY({parent_cat}, {name}, "{label}") \\\n'.format( - parent_cat=name, name=subcat_name, label=subcat_label - ) + f' SUBCATEGORY({name}, {subcat_name}, "{subcat_label}") \\\n' ) contents += "".join(subcategory_items) @@ -151,7 +147,7 @@ def generate_macro_header(c_out, yaml_path): subcategories = category.get("subcategories", None) assert ( isinstance(subcategories, list) and len(subcategories) > 0 - ), "At least one subcategory expected as default in {}.".format(name) + ), f"At least one subcategory expected as default in {name}." category_items.append( generate_category_macro(name, label, color, subcategories) @@ -213,14 +209,14 @@ class RustEnum: def append_optional_tuple_field(self, field_name): """Append the enum fields list with an optional tuple field.""" - field = (field_name, " {name}(Option<{name}>),".format(name=field_name)) + field = (field_name, f" {field_name}(Option<{field_name}>),") self.fields.append(field) def append_discriminant_field(self, field_name, field_value): """Append the enum fields list with a discriminant field.""" field = ( field_name, - " {name} = {value},".format(name=field_name, value=field_value), + f" {field_name} = {field_value},", ) self.fields.append(field) @@ -231,9 +227,7 @@ class RustEnum: self.impls.append( RUST_DEFAULT_IMPL_TEMPLATE.format( name=self.name, - content=" {category}::{subcategory}".format( - category=self.name, subcategory=self.default_category - ), + content=f" {self.name}::{self.default_category}", ) ) @@ -278,7 +272,7 @@ def generate_rust_enums(c_out, yaml_path): cat_subcategories = category.get("subcategories", None) assert ( isinstance(cat_subcategories, list) and len(cat_subcategories) > 0 - ), "At least one subcategory expected as default in {}.".format(cat_name) + ), f"At least one subcategory expected as default in {cat_name}." # Create a new enum for this sub category and append it to the enums list. category_enum = RustEnum(cat_label) diff --git a/netwerk/base/makecppstring.py b/netwerk/base/makecppstring.py index 330fcfb04c9e..da62ad08366c 100644 --- a/netwerk/base/makecppstring.py +++ b/netwerk/base/makecppstring.py @@ -6,7 +6,7 @@ import sys def main(output, filename): - file = open(filename, "r") + file = open(filename) output.write('R"(') # insert literal start for line in file: output.write(line) diff --git a/pyproject.toml b/pyproject.toml index 06e54266f488..d89a7f52b191 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,15 +21,6 @@ lint.ignore = [ # These are handled by black. "E1", "E4", "E5", "W2", "W5", - - # These pyupgrade rules are currently disabled because applying them via autofix causes failures. - # Each rule can be revisited and re-enabled once the underlying issues are identified and resolved. - # See bug 1715287 - # https://docs.astral.sh/ruff/rules/#pyupgrade-up - "UP004", # useless-object-inheritance Class {name} inherits from object - "UP012", # unnecessary-encode-utf8 Unnecessary call to encode as UTF-8 - "UP015", # redundant-open-modes Unnecessary mode argument - "UP032", # f-string Use f-string instead of format call ] builtins = ["gdb"] extend-include = ["*.configure"] diff --git a/python/gdbpp/gdbpp/__init__.py b/python/gdbpp/gdbpp/__init__.py index 9edc626eb6f9..da36fb77b98a 100644 --- a/python/gdbpp/gdbpp/__init__.py +++ b/python/gdbpp/gdbpp/__init__.py @@ -8,7 +8,7 @@ import gdb import gdb.printing -class GeckoPrettyPrinter(object): +class GeckoPrettyPrinter: pp = gdb.printing.RegexpCollectionPrettyPrinter("GeckoPrettyPrinters") def __init__(self, name, regexp): diff --git a/python/gdbpp/gdbpp/enumset.py b/python/gdbpp/gdbpp/enumset.py index 71315389c1b7..bf8cd858f67e 100644 --- a/python/gdbpp/gdbpp/enumset.py +++ b/python/gdbpp/gdbpp/enumset.py @@ -10,7 +10,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter("mozilla::EnumSet", "^mozilla::EnumSet<.*>$") -class enumset_printer(object): +class enumset_printer: def __init__(self, value): self.value = value self.enum_type = value.type.template_argument(0) diff --git a/python/gdbpp/gdbpp/linkedlist.py b/python/gdbpp/gdbpp/linkedlist.py index 1ba25a1cf0a1..05d89070f26e 100644 --- a/python/gdbpp/gdbpp/linkedlist.py +++ b/python/gdbpp/gdbpp/linkedlist.py @@ -15,7 +15,7 @@ from gdbpp import GeckoPrettyPrinter # itself. We do not want to start printing every item in the list whenever # we run into a LinkedListElement. @GeckoPrettyPrinter("mozilla::LinkedList", "^mozilla::LinkedList<.*>$") -class linkedlist_printer(object): +class linkedlist_printer: def __init__(self, value): self.value = value # mfbt's LinkedList has the elements of the linked list subclass from diff --git a/python/gdbpp/gdbpp/owningthread.py b/python/gdbpp/gdbpp/owningthread.py index 52055b3c99ff..cbd39f131900 100644 --- a/python/gdbpp/gdbpp/owningthread.py +++ b/python/gdbpp/gdbpp/owningthread.py @@ -10,7 +10,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter("nsAutoOwningThread", "^nsAutoOwningThread$") -class owning_thread_printer(object): +class owning_thread_printer: def __init__(self, value): self.value = value diff --git a/python/gdbpp/gdbpp/smartptr.py b/python/gdbpp/gdbpp/smartptr.py index 1a9f5034127c..2566164f49fc 100644 --- a/python/gdbpp/gdbpp/smartptr.py +++ b/python/gdbpp/gdbpp/smartptr.py @@ -8,7 +8,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter("nsWeakPtr", "^nsCOMPtr$") -class weak_ptr_printer(object): +class weak_ptr_printer: def __init__(self, value): self.value = value @@ -30,7 +30,7 @@ class weak_ptr_printer(object): @GeckoPrettyPrinter("nsAutoPtr", "^nsAutoPtr<.*>$") @GeckoPrettyPrinter("nsCOMPtr", "^nsCOMPtr<.*>$") @GeckoPrettyPrinter("RefPtr", "^RefPtr<.*>$") -class smartptr_printer(object): +class smartptr_printer: def __init__(self, value): self.value = value["mRawPtr"] @@ -47,7 +47,7 @@ class smartptr_printer(object): @GeckoPrettyPrinter("UniquePtr", "^mozilla::UniquePtr<.*>$") -class uniqueptr_printer(object): +class uniqueptr_printer: def __init__(self, value): self.value = value["mTuple"]["mFirstA"] diff --git a/python/gdbpp/gdbpp/string.py b/python/gdbpp/gdbpp/string.py index b5722f2c62da..0a3c7da7c9ac 100644 --- a/python/gdbpp/gdbpp/string.py +++ b/python/gdbpp/gdbpp/string.py @@ -10,7 +10,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter("nsTSubstring", "^nsTSubstring<.*>$") @GeckoPrettyPrinter("nsTAutoStringN", "^nsTAutoStringN<.*>$") @GeckoPrettyPrinter("nsString", "^nsTString<.*>$") -class string_printer(object): +class string_printer: def __init__(self, value): self.value = value diff --git a/python/gdbpp/gdbpp/syncedcontext.py b/python/gdbpp/gdbpp/syncedcontext.py index c9c80a556240..5c203aacf5ff 100644 --- a/python/gdbpp/gdbpp/syncedcontext.py +++ b/python/gdbpp/gdbpp/syncedcontext.py @@ -14,7 +14,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter( "syncedcontext::FieldValues", "^mozilla::dom::syncedcontext::FieldValues<.*>$" ) -class synced_context_field_printer(object): +class synced_context_field_printer: def __init__(self, value): self.type = gdb.types.get_basic_type(value.type).template_argument(0) self.value = value.cast(self.type) diff --git a/python/gdbpp/gdbpp/tarray.py b/python/gdbpp/gdbpp/tarray.py index a5c82253b9cb..d2ed29618001 100644 --- a/python/gdbpp/gdbpp/tarray.py +++ b/python/gdbpp/gdbpp/tarray.py @@ -11,7 +11,7 @@ from gdbpp import GeckoPrettyPrinter @GeckoPrettyPrinter("FallibleTArray", "^FallibleTArray<.*>$") @GeckoPrettyPrinter("AutoTArray", "^AutoTArray<.*>$") @GeckoPrettyPrinter("nsTArray", "^nsTArray<.*>$") -class tarray_printer(object): +class tarray_printer: def __init__(self, value): self.value = value self.elem_type = value.type.template_argument(0) diff --git a/python/gdbpp/gdbpp/thashtable.py b/python/gdbpp/gdbpp/thashtable.py index 8b0294acf60d..3d1524e6c5f1 100644 --- a/python/gdbpp/gdbpp/thashtable.py +++ b/python/gdbpp/gdbpp/thashtable.py @@ -50,7 +50,7 @@ def walk_template_to_given_base(value, desired_tag_prefix): @GeckoPrettyPrinter("nsRefPtrHashtable", "^nsRefPtrHashtable<.*>$") @GeckoPrettyPrinter("nsBaseHashtable", "^nsBaseHashtable<.*>$") @GeckoPrettyPrinter("nsTHashtable", "^nsTHashtable<.*>$") -class thashtable_printer(object): +class thashtable_printer: def __init__(self, outer_value): self.outermost_type = outer_value.type diff --git a/python/l10n/test_fluent_migrations/fmt.py b/python/l10n/test_fluent_migrations/fmt.py index 213968b34c2f..a082de473eba 100644 --- a/python/l10n/test_fluent_migrations/fmt.py +++ b/python/l10n/test_fluent_migrations/fmt.py @@ -175,7 +175,7 @@ def test_migration( {"file": to_test}, "Missing or wrong bug number for {file}", ) - if any("part {}".format(n + 1) not in msg for n, msg in enumerate(messages)): + if any(f"part {n + 1}" not in msg for n, msg in enumerate(messages)): rv = 1 cmd.log( logging.ERROR, diff --git a/python/mach/mach/commands/commandinfo.py b/python/mach/mach/commands/commandinfo.py index f31c36a8472b..a3d6701db241 100644 --- a/python/mach/mach/commands/commandinfo.py +++ b/python/mach/mach/commands/commandinfo.py @@ -27,7 +27,7 @@ class CommandInfo: def render_template(shell, context): - filename = "{}.template".format(shell) + filename = f"{shell}.template" with open(COMPLETION_TEMPLATES_DIR / filename) as fh: template = fh.read() return template % context @@ -210,7 +210,7 @@ def _zsh_describe(value, description=None): if description.endswith('"') and not description.endswith(r"\""): description = description[:-1] - value += ":{}".format(description) + value += f":{description}" value += '"' @@ -249,7 +249,7 @@ def completion_bash(command_context, outfile): case_options.append( "\n".join( [ - " ({})".format(cmd.name), + f" ({cmd.name})", ' opts="${{opts}} {}"'.format(" ".join(options)), " ;;", "", @@ -268,7 +268,7 @@ def completion_bash(command_context, outfile): case_options.append( "\n".join( [ - ' ("{} {}")'.format(sub.name, sub.subcommand), + f' ("{sub.name} {sub.subcommand}")', ' opts="${{opts}} {}"'.format(" ".join(options)), " ;;", "", @@ -283,8 +283,8 @@ def completion_bash(command_context, outfile): case_commands_subcommands.append( "\n".join( [ - " ({})".format(cmd.name), - ' comsubs=" {} "'.format(comsubs), + f" ({cmd.name})", + f' comsubs=" {comsubs} "', " ;;", "", ] @@ -294,7 +294,7 @@ def completion_bash(command_context, outfile): case_subcommands.append( "\n".join( [ - " ({})".format(cmd.name), + f" ({cmd.name})", ' subs="${{subs}} {}"'.format(" ".join(subcommands)), " ;;", "", @@ -347,7 +347,7 @@ def completion_zsh(command_context, outfile): case_options.append( "\n".join( [ - " ({})".format(cmd.name), + f" ({cmd.name})", " opts+=({})".format(" ".join(options)), " ;;", "", @@ -366,7 +366,7 @@ def completion_zsh(command_context, outfile): case_options.append( "\n".join( [ - " ({} {})".format(sub.name, sub.subcommand), + f" ({sub.name} {sub.subcommand})", " opts+=({})".format(" ".join(options)), " ;;", "", @@ -388,7 +388,7 @@ def completion_zsh(command_context, outfile): case_subcommands.append( "\n".join( [ - " ({})".format(cmd.name), + f" ({cmd.name})", " subs+=({})".format(" ".join(subcommands)), " ;;", "", @@ -429,9 +429,9 @@ def completion_fish(command_context, outfile): def _append_opt_strs(comp, opt_strs): for opt in opt_strs: if opt.startswith("--"): - comp += " -l {}".format(opt[2:]) + comp += f" -l {opt[2:]}" elif opt.startswith("-"): - comp += " -s {}".format(opt[1:]) + comp += f" -s {opt[1:]}" return comp globalopts = [] @@ -451,7 +451,7 @@ def completion_fish(command_context, outfile): "-a {} -d '{}'".format(cmd.name, cmd.description.replace("'", "\\'")) ) - cmds_opts += ["# {}".format(cmd.name)] + cmds_opts += [f"# {cmd.name}"] subcommands = " ".join([s.subcommand for s in cmd.subcommands]) for opt_strs, description in cmd.options.items(): @@ -476,10 +476,8 @@ def completion_fish(command_context, outfile): description = sub.description or "" description = description.replace("'", "\\'") comp = ( - "complete -c mach -A -n '__fish_mach_complete_command {} {}' " - "-d '{}' -a {}".format( - cmd.name, subcommands, description, sub.subcommand - ) + f"complete -c mach -A -n '__fish_mach_complete_command {cmd.name} {subcommands}' " + f"-d '{description}' -a {sub.subcommand}" ) cmds_opts.append(comp) diff --git a/python/mach/mach/commands/settings.py b/python/mach/mach/commands/settings.py index 83e342904ce3..b1a136a01a31 100644 --- a/python/mach/mach/commands/settings.py +++ b/python/mach/mach/commands/settings.py @@ -35,7 +35,7 @@ def run_settings(command_context, short=None): desc = meta["description"] if short: - print("{}.{} -- {}".format(section, option, desc.splitlines()[0])) + print(f"{section}.{option} -- {desc.splitlines()[0]}") continue if option == "*": @@ -47,4 +47,4 @@ def run_settings(command_context, short=None): value = "<%s>" % types[meta["type_cls"]] print(wrapper.fill(desc)) - print(";{}={}".format(option, value)) + print(f";{option}={value}") diff --git a/python/mach/mach/config.py b/python/mach/mach/config.py index 0335cc1e36e8..0d8c938c664c 100644 --- a/python/mach/mach/config.py +++ b/python/mach/mach/config.py @@ -360,7 +360,7 @@ class ConfigSettings(collections.abc.Mapping): if option in config_settings[section]: raise ConfigException( - "Setting has already been registered: {}.{}".format(section, option) + f"Setting has already been registered: {section}.{option}" ) meta = self._format_metadata(*setting[1:]) @@ -372,7 +372,7 @@ class ConfigSettings(collections.abc.Mapping): for k, v in settings.items(): if k in section: raise ConfigException( - "Setting already registered: {}.{}".format(section_name, k) + f"Setting already registered: {section_name}.{k}" ) section[k] = v diff --git a/python/mach/mach/main.py b/python/mach/mach/main.py index 8aa22df8d2fc..60f650de5491 100644 --- a/python/mach/mach/main.py +++ b/python/mach/mach/main.py @@ -488,7 +488,7 @@ To see more help for a specific command, run: if not sentry_event_id: return - fh.write("\nSentry event ID: {}\n".format(sentry_event_id)) + fh.write(f"\nSentry event ID: {sentry_event_id}\n") def load_settings(self): if not self.settings_loaded: diff --git a/python/mach/mach/registrar.py b/python/mach/mach/registrar.py index 2efcbcdbf2e9..20f9f4dd1d42 100644 --- a/python/mach/mach/registrar.py +++ b/python/mach/mach/registrar.py @@ -196,10 +196,10 @@ class MachRegistrar: if unknown: if subcommand: - name = "{} {}".format(name, subcommand) + name = f"{name} {subcommand}" parser.error( "unrecognized arguments for {}: {}".format( - name, ", ".join(["'{}'".format(arg) for arg in unknown]) + name, ", ".join([f"'{arg}'" for arg in unknown]) ) ) diff --git a/python/mach/mach/requirements.py b/python/mach/mach/requirements.py index 8d85db27abe9..018ecaa9bdbd 100644 --- a/python/mach/mach/requirements.py +++ b/python/mach/mach/requirements.py @@ -180,7 +180,7 @@ def _parse_mach_env_requirements( raise Exception( "Expected pypi-optional package to have a repercussion " 'description in the format "package:fallback explanation", ' - 'found "{}"'.format(params) + f'found "{params}"' ) raw_requirement, repercussion = params.split(":") requirements_output.pypi_optional_requirements.append( diff --git a/python/mach/mach/sentry.py b/python/mach/mach/sentry.py index 0a0aeeb7505a..1185138e7ebc 100644 --- a/python/mach/mach/sentry.py +++ b/python/mach/mach/sentry.py @@ -90,7 +90,7 @@ def _process_event(sentry_event, topsrcdir: Path): for map_fn in (_settle_mach_module_id, _patch_absolute_paths, _delete_server_name): sentry_event = map_fn(sentry_event, topsrcdir) - sentry_event["release"] = "hg-rev-{}".format(base_ref) + sentry_event["release"] = f"hg-rev-{base_ref}" return sentry_event diff --git a/python/mach/mach/site.py b/python/mach/mach/site.py index 05956a32b3c8..bbcbc447bc02 100644 --- a/python/mach/mach/site.py +++ b/python/mach/mach/site.py @@ -1013,7 +1013,7 @@ class PythonVirtualenv: # thereby causing a build failure. To avoid this, we explicitly influence the # build to only target a single architecture - our current architecture. kwargs.setdefault("env", os.environ.copy()).setdefault( - "ARCHFLAGS", "-arch {}".format(platform.machine()) + "ARCHFLAGS", f"-arch {platform.machine()}" ) kwargs.setdefault("check", True) kwargs.setdefault("stdout", None if show_pip_output() else subprocess.PIPE) diff --git a/python/mach_commands.py b/python/mach_commands.py index 508a11bc0aff..82733d3949c1 100644 --- a/python/mach_commands.py +++ b/python/mach_commands.py @@ -182,10 +182,10 @@ def run_python_tests( tests = mp.active_tests(filters=filters, disabled=False, python=3, **mozinfo.info) if not tests: - submsg = "for subsuite '{}' ".format(subsuite) if subsuite else "" + submsg = f"for subsuite '{subsuite}' " if subsuite else "" message = ( "TEST-UNEXPECTED-FAIL | No tests collected " - + "{}(Not in PYTHON_UNITTEST_MANIFESTS?)".format(submsg) + + f"{submsg}(Not in PYTHON_UNITTEST_MANIFESTS?)" ) command_context.log(logging.WARN, "python-test", {}, message) return 1 diff --git a/python/mozboot/mozboot/android.py b/python/mozboot/mozboot/android.py index 07f1a9a71608..ec444d17621a 100644 --- a/python/mozboot/mozboot/android.py +++ b/python/mozboot/mozboot/android.py @@ -216,7 +216,7 @@ def get_ndk_version(ndk_path: Union[str, Path]): minor, human). """ ndk_path = Path(ndk_path) - with open(ndk_path / "source.properties", "r") as f: + with open(ndk_path / "source.properties") as f: revision = [line for line in f if line.startswith("Pkg.Revision")] if not revision: raise GetNdkVersionError( @@ -331,13 +331,9 @@ def ensure_android( else: os_tag = os_name - sdk_url = "https://dl.google.com/android/repository/commandlinetools-{0}-{1}_latest.zip".format( # NOQA: E501 - os_tag, CMDLINE_TOOLS_VERSION - ) + sdk_url = f"https://dl.google.com/android/repository/commandlinetools-{os_tag}-{CMDLINE_TOOLS_VERSION}_latest.zip" ndk_url = android_ndk_url(os_name) - bundletool_url = "https://github.com/google/bundletool/releases/download/{v}/bundletool-all-{v}.jar".format( # NOQA: E501 - v=BUNDLETOOL_VERSION - ) + bundletool_url = f"https://github.com/google/bundletool/releases/download/{BUNDLETOOL_VERSION}/bundletool-all-{BUNDLETOOL_VERSION}.jar" ensure_android_sdk_and_ndk( mozbuild_path, @@ -505,7 +501,7 @@ def ensure_android_avd( env = os.environ.copy() env["ANDROID_AVD_HOME"] = str(avd_home_path) proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env) - proc.communicate("no\n".encode("UTF-8")) + proc.communicate(b"no\n") retcode = proc.poll() if retcode: @@ -760,7 +756,7 @@ def main(argv): else: raise NotImplementedError( "We don't support bootstrapping the Android SDK (or Android " - "NDK) on {0} yet!".format(platform.system()) + f"NDK) on {platform.system()} yet!" ) os_arch = platform.machine() @@ -822,16 +818,9 @@ def ensure_java(os_name: str, os_arch: str): # e.g. https://github.com/adoptium/temurin17-binaries/releases/ # download/jdk-17.0.14%2B7/OpenJDK17U-jdk_x64_linux_hotspot_17.0.14_7.tar.gz java_url = ( - "https://github.com/adoptium/temurin{major}-binaries/releases/" - "download/jdk-{major}.{minor}%2B{patch}/" - "OpenJDK{major}U-jdk_{arch}_{os}_hotspot_{major}.{minor}_{patch}.{ext}" - ).format( - major=JAVA_VERSION_MAJOR, - minor=JAVA_VERSION_MINOR, - patch=JAVA_VERSION_PATCH, - os=os_tag, - arch=arch, - ext=ext, + f"https://github.com/adoptium/temurin{JAVA_VERSION_MAJOR}-binaries/releases/" + f"download/jdk-{JAVA_VERSION_MAJOR}.{JAVA_VERSION_MINOR}%2B{JAVA_VERSION_PATCH}/" + f"OpenJDK{JAVA_VERSION_MAJOR}U-jdk_{arch}_{os_tag}_hotspot_{JAVA_VERSION_MAJOR}.{JAVA_VERSION_MINOR}_{JAVA_VERSION_PATCH}.{ext}" ) install_mobile_android_sdk_or_ndk(java_url, mozbuild_path / "jdk") return java_path @@ -839,9 +828,7 @@ def ensure_java(os_name: str, os_arch: str): def java_bin_path(os_name, toolchain_path: Path): # Like jdk-17.0.14+7 - jdk_folder = "jdk-{major}.{minor}+{patch}".format( - major=JAVA_VERSION_MAJOR, minor=JAVA_VERSION_MINOR, patch=JAVA_VERSION_PATCH - ) + jdk_folder = f"jdk-{JAVA_VERSION_MAJOR}.{JAVA_VERSION_MINOR}+{JAVA_VERSION_PATCH}" java_path = toolchain_path / "jdk" / jdk_folder diff --git a/python/mozboot/mozboot/base.py b/python/mozboot/mozboot/base.py index 3c685ebdf65b..f40c9ec4359d 100644 --- a/python/mozboot/mozboot/base.py +++ b/python/mozboot/mozboot/base.py @@ -152,7 +152,7 @@ MODERN_MERCURIAL_VERSION = Version("4.9") MODERN_RUST_VERSION = Version(MINIMUM_RUST_VERSION) -class BaseBootstrapper(object): +class BaseBootstrapper: """Base class for system bootstrappers.""" def __init__(self, no_interactive=False, no_system_changes=False): @@ -372,7 +372,7 @@ class BaseBootstrapper(object): if self.no_interactive: print(prompt) - print('Selecting "{}" because context is not interactive.'.format(default)) + print(f'Selecting "{default}" because context is not interactive.') return default while True: diff --git a/python/mozboot/mozboot/bootstrap.py b/python/mozboot/mozboot/bootstrap.py index 08377a724812..86ae1e0b1979 100644 --- a/python/mozboot/mozboot/bootstrap.py +++ b/python/mozboot/mozboot/bootstrap.py @@ -251,7 +251,7 @@ def check_for_hgrc_state_dir_mismatch(state_dir): raise Exception(hgrc_state_dir_mismatch_error_message) -class Bootstrapper(object): +class Bootstrapper: """Main class that performs system bootstrap.""" def __init__( @@ -388,8 +388,8 @@ class Bootstrapper(object): labels = [ "%s. %s" % (i, name) for i, name in enumerate(applications.keys(), 1) ] - choices = [" {} [default]".format(labels[0])] - choices += [" {}".format(label) for label in labels[1:]] + choices = [f" {labels[0]} [default]"] + choices += [f" {label}" for label in labels[1:]] prompt = APPLICATION_CHOICE % "\n".join(choices) prompt_choice = self.instance.prompt_int( prompt=prompt, low=1, high=len(applications) @@ -577,7 +577,7 @@ class Bootstrapper(object): def _read_default_mozconfig(self): path = self._default_mozconfig_path() - with open(path, "r") as mozconfig_file: + with open(path) as mozconfig_file: return mozconfig_file.read() def _write_default_mozconfig(self, raw_mozconfig): diff --git a/python/mozboot/mozboot/linux_common.py b/python/mozboot/mozboot/linux_common.py index bd61640eac9b..4c85a6e91865 100644 --- a/python/mozboot/mozboot/linux_common.py +++ b/python/mozboot/mozboot/linux_common.py @@ -13,7 +13,7 @@ def is_non_x86_64(): return platform.machine() != "x86_64" -class MobileAndroidBootstrapper(object): +class MobileAndroidBootstrapper: def __init__(self, **kwargs): pass diff --git a/python/mozboot/mozboot/mach_commands.py b/python/mozboot/mozboot/mach_commands.py index 538747687228..d5f582cbf92b 100644 --- a/python/mozboot/mozboot/mach_commands.py +++ b/python/mozboot/mozboot/mach_commands.py @@ -95,7 +95,7 @@ def vcs_setup(command_context, update_only=False): vcs = to_optional_path(which(tool)) if not vcs: - raise OSError(errno.ENOENT, "Could not find {} on $PATH".format(tool)) + raise OSError(errno.ENOENT, f"Could not find {tool} on $PATH") if update_only: if repo.name == "git": diff --git a/python/mozboot/mozboot/mozconfig.py b/python/mozboot/mozboot/mozconfig.py index a1ae4c8523cd..e27c189d3413 100644 --- a/python/mozboot/mozboot/mozconfig.py +++ b/python/mozboot/mozboot/mozconfig.py @@ -28,7 +28,7 @@ class MozconfigFindException(Exception): """Raised when a mozconfig location is not defined properly.""" -class MozconfigBuilder(object): +class MozconfigBuilder: def __init__(self): self._lines = [] diff --git a/python/mozboot/mozboot/osx.py b/python/mozboot/mozboot/osx.py index 712ee7aba139..b1be9a921cb5 100644 --- a/python/mozboot/mozboot/osx.py +++ b/python/mozboot/mozboot/osx.py @@ -35,7 +35,7 @@ output as packages are built. NO_BREW_INSTALLED = "It seems you don't have Homebrew installed." -class OSXAndroidBootstrapper(object): +class OSXAndroidBootstrapper: def install_mobile_android_packages(self, mozconfig_builder, artifact_mode=False): os_arch = platform.machine() if os_arch != "x86_64" and os_arch != "arm64": diff --git a/python/mozboot/mozboot/test/test_msrv.py b/python/mozboot/mozboot/test/test_msrv.py index 530946c290d2..44d468c01bf8 100644 --- a/python/mozboot/mozboot/test/test_msrv.py +++ b/python/mozboot/mozboot/test/test_msrv.py @@ -17,7 +17,7 @@ class TestMSRV(unittest.TestCase): """Ensure MSRV in mozboot and top-level Config.toml match.""" cargo_toml = os.path.join(topsrcdir, "Cargo.toml") - with open(cargo_toml, "r") as f: + with open(cargo_toml) as f: content = toml.load(f) workspace = content.get("workspace", {}) rust_version = workspace.get("package", {}).get("rust-version") diff --git a/python/mozbuild/mozbuild/action/check_binary.py b/python/mozbuild/mozbuild/action/check_binary.py index 4f66b0bb2f22..d96ff1247f41 100644 --- a/python/mozbuild/mozbuild/action/check_binary.py +++ b/python/mozbuild/mozbuild/action/check_binary.py @@ -135,9 +135,7 @@ def check_binary_compat(binary): error = [] for lib, prefix, _ in checks: if prefix in unwanted: - error.append( - "We do not want these {} symbol versions to be used:".format(lib) - ) + error.append(f"We do not want these {lib} symbol versions to be used:") error.extend( " {} ({})".format(s["name"], s["version"]) for s in unwanted[prefix] ) @@ -263,7 +261,7 @@ def check_networking(binary): ) retcode = 1 elif buildconfig.substs.get("MOZ_AUTOMATION"): - print("TEST-PASS | check_networking | {}".format(basename)) + print(f"TEST-PASS | check_networking | {basename}") return retcode @@ -289,12 +287,12 @@ def checks(binary): name = c.__name__ c(binary) if buildconfig.substs.get("MOZ_AUTOMATION"): - print("TEST-PASS | {} | {}".format(name, basename)) + print(f"TEST-PASS | {name} | {basename}") except Skip: pass except RuntimeError as e: print( - "TEST-UNEXPECTED-FAIL | {} | {} | {}".format(name, basename, str(e)), + f"TEST-UNEXPECTED-FAIL | {name} | {basename} | {str(e)}", file=sys.stderr, ) retcode = 1 diff --git a/python/mozbuild/mozbuild/action/dumpsymbols.py b/python/mozbuild/mozbuild/action/dumpsymbols.py index 0af2c1c4e576..529f0016bbff 100644 --- a/python/mozbuild/mozbuild/action/dumpsymbols.py +++ b/python/mozbuild/mozbuild/action/dumpsymbols.py @@ -16,7 +16,7 @@ def dump_symbols(target, tracking_file, count_ctors=False): # symbols. Remove them in this case so we don't simply accumulate old symbols # during incremental builds. if os.path.isfile(os.path.normpath(tracking_file)): - with open(tracking_file, "r") as fh: + with open(tracking_file) as fh: files = fh.read().splitlines() dirs = set(os.path.dirname(f) for f in files) for d in dirs: diff --git a/python/mozbuild/mozbuild/action/fat_aar.py b/python/mozbuild/mozbuild/action/fat_aar.py index d17d4696a0b2..d3819f5d233f 100644 --- a/python/mozbuild/mozbuild/action/fat_aar.py +++ b/python/mozbuild/mozbuild/action/fat_aar.py @@ -36,10 +36,8 @@ def fat_aar(distdir, aars_paths, no_process=False, no_compatibility_check=False) for arch, aar_path in aars_paths.items(): # Map old non-architecture-specific path to new architecture-specific path. old_rewrite_map = { - "greprefs.js": "{}/greprefs.js".format(arch), - "defaults/pref/geckoview-prefs.js": "defaults/pref/{}/geckoview-prefs.js".format( - arch - ), + "greprefs.js": f"{arch}/greprefs.js", + "defaults/pref/geckoview-prefs.js": f"defaults/pref/{arch}/geckoview-prefs.js", } # Architecture-specific preferences files. @@ -64,7 +62,7 @@ def fat_aar(distdir, aars_paths, no_process=False, no_compatibility_check=False) z = ZipFile(BytesIO(fileobj.open().read())) for r in z.namelist(): fingerprint = sha1(z.open(r).read()).hexdigest() - diffs["{}!/{}".format(path, r)][fingerprint].append(arch) + diffs[f"{path}!/{r}"][fingerprint].append(arch) else: fingerprint = sha1(six.ensure_binary(fileobj.open().read())).hexdigest() @@ -109,9 +107,7 @@ def fat_aar(distdir, aars_paths, no_process=False, no_compatibility_check=False) if any(mozpath.match(p, pat) for pat in allow_pattern_list): print( - 'Allowed: Path "{path}" has architecture-specific versions:\n{ds_repr}'.format( - path=p, ds_repr=format_diffs(ds) - ) + f'Allowed: Path "{p}" has architecture-specific versions:\n{format_diffs(ds)}' ) continue @@ -119,16 +115,12 @@ def fat_aar(distdir, aars_paths, no_process=False, no_compatibility_check=False) for p, ds in not_allowed.items(): print( - 'Disallowed: Path "{path}" has architecture-specific versions:\n{ds_repr}'.format( - path=p, ds_repr=format_diffs(ds) - ) + f'Disallowed: Path "{p}" has architecture-specific versions:\n{format_diffs(ds)}' ) for missing in sorted(missing_arch_prefs): print( - "Disallowed: Inputs missing expected architecture-specific input: {missing}".format( - missing=missing - ) + f"Disallowed: Inputs missing expected architecture-specific input: {missing}" ) if not no_compatibility_check and (missing_arch_prefs or not_allowed): @@ -160,7 +152,7 @@ compatibility, and ready inputs to an Android multi-architecture fat AAR build." for arch in _ALL_ARCHS: command_line_flag = arch.replace("_", "-") - parser.add_argument("--{}".format(command_line_flag), dest=arch) + parser.add_argument(f"--{command_line_flag}", dest=arch) args = parser.parse_args(argv) diff --git a/python/mozbuild/mozbuild/action/file_generate.py b/python/mozbuild/mozbuild/action/file_generate.py index 070c24a682ca..077e19f4b81c 100644 --- a/python/mozbuild/mozbuild/action/file_generate.py +++ b/python/mozbuild/mozbuild/action/file_generate.py @@ -86,7 +86,7 @@ def main(argv): method = args.method_name if not hasattr(module, method): print( - 'Error: script "{0}" is missing a {1} method'.format(script, method), + f'Error: script "{script}" is missing a {method} method', file=sys.stderr, ) return 1 @@ -144,7 +144,7 @@ def main(argv): output.avoid_writing_to_file() except OSError as e: - print('Error opening file "{0}"'.format(e.filename), file=sys.stderr) + print(f'Error opening file "{e.filename}"', file=sys.stderr) traceback.print_exc() return 1 return ret diff --git a/python/mozbuild/mozbuild/action/langpack_manifest.py b/python/mozbuild/mozbuild/action/langpack_manifest.py index edadebb16105..08f7af0e7647 100644 --- a/python/mozbuild/mozbuild/action/langpack_manifest.py +++ b/python/mozbuild/mozbuild/action/langpack_manifest.py @@ -80,7 +80,7 @@ def get_dt_from_hg(path): response = session.get(url) response.raise_for_status() except Exception as e: - msg = "Failed to retrieve push timestamp using {}\nError: {}".format(url, e) + msg = f"Failed to retrieve push timestamp using {url}\nError: {e}" raise Exception(msg) return response.json() @@ -89,9 +89,7 @@ def get_dt_from_hg(path): try: date = data["pushdate"][0] except KeyError as exc: - msg = "{}\ndata is: {}".format( - str(exc), json.dumps(data, indent=2, sort_keys=True) - ) + msg = f"{str(exc)}\ndata is: {json.dumps(data, indent=2, sort_keys=True)}" raise KeyError(msg) return datetime.datetime.utcfromtimestamp(date) @@ -305,7 +303,7 @@ def convert_entry_flags_to_platform_codes(flags): elif value[1] == "WINNT": ret.append("win") else: - raise Exception("Unknown flag value {0}".format(value[1])) + raise Exception(f"Unknown flag value {value[1]}") return ret @@ -366,7 +364,7 @@ def parse_chrome_manifest(path, base_path, chrome_entries): } ) else: - raise Exception("Unknown type {0}".format(entry.name)) + raise Exception(f"Unknown type {entry.name}") ### @@ -578,10 +576,10 @@ def main(args): if args.app_name == "SeaMonkey": # SeaMonkey is odd in that hasn't changed for many years. # So min is ..0 - min_app_version = "{}.{}.0".format(v.major, v.minor) + min_app_version = f"{v.major}.{v.minor}.0" else: # Language packs should be minversion of {major}.0 - min_app_version = "{}.0".format(v.major) + min_app_version = f"{v.major}.0" res = create_webmanifest( args.locales, diff --git a/python/mozbuild/mozbuild/action/node.py b/python/mozbuild/mozbuild/action/node.py index b9b81e3dee4d..86b8e2b45c74 100644 --- a/python/mozbuild/mozbuild/action/node.py +++ b/python/mozbuild/mozbuild/action/node.py @@ -50,7 +50,7 @@ def execute_node_cmd(node_cmd_list): try: if os.environ.get("BUILD_VERBOSE_LOG"): - print('Executing "{}"'.format(shell_quote(*node_cmd_list)), file=sys.stderr) + print(f'Executing "{shell_quote(*node_cmd_list)}"', file=sys.stderr) sys.stderr.flush() # We need to redirect stderr to a pipe because diff --git a/python/mozbuild/mozbuild/action/process_define_files.py b/python/mozbuild/mozbuild/action/process_define_files.py index 83c1985449ea..e8dc5775b67d 100644 --- a/python/mozbuild/mozbuild/action/process_define_files.py +++ b/python/mozbuild/mozbuild/action/process_define_files.py @@ -37,7 +37,7 @@ def process_define_file(output, input): ) and not config.substs.get("JS_STANDALONE"): config = PartialConfigEnvironment(mozpath.join(topobjdir, "js", "src")) - with open(path, "r") as input: + with open(path) as input: r = re.compile( r"^\s*#\s*(?P[a-z]+)(?:\s+(?P\S+)(?:\s+(?P\S+))?)?", re.U ) @@ -60,11 +60,9 @@ def process_define_file(output, input): via the command line, which raises a mass of macro redefinition warnings. Just handle those macros specially here.""" - define = "#define {name} {val}".format(name=name, val=val) + define = f"#define {name} {val}" if name in ("_WIN32_IE", "_WIN32_WINNT", "WIN32", "WINVER"): - return "#if !defined({name})\n{define}\n#endif".format( - name=name, define=define - ) + return f"#if !defined({name})\n{define}\n#endif" return define defines = "\n".join( diff --git a/python/mozbuild/mozbuild/action/symbols_archive.py b/python/mozbuild/mozbuild/action/symbols_archive.py index 75ecb71d1726..9eb421a8207b 100644 --- a/python/mozbuild/mozbuild/action/symbols_archive.py +++ b/python/mozbuild/mozbuild/action/symbols_archive.py @@ -57,9 +57,7 @@ def make_archive(archive_name, base, exclude, include): fill_archive(add_file) else: - raise Exception( - "Unsupported archive format for {}".format(archive_basename) - ) + raise Exception(f"Unsupported archive format for {archive_basename}") def main(argv): diff --git a/python/mozbuild/mozbuild/action/test_archive.py b/python/mozbuild/mozbuild/action/test_archive.py index 508c7800fd2c..271ab2e8c022 100644 --- a/python/mozbuild/mozbuild/action/test_archive.py +++ b/python/mozbuild/mozbuild/action/test_archive.py @@ -800,7 +800,7 @@ def find_files(archive): manifests.append(manifest) if manifests: dirs = find_manifest_dirs(os.path.join(source, base), manifests) - patterns.extend({"{}/**".format(d) for d in dirs}) + patterns.extend({f"{d}/**" for d in dirs}) ignore = list(entry.get("ignore", [])) ignore.extend(["**/.flake8", "**/.mkdir.done", "**/*.pyc"]) @@ -844,9 +844,7 @@ def find_manifest_dirs(topsrcdir, manifests): else: raise Exception( - '"{}" is not a supported manifest format.'.format( - os.path.splitext(p)[1] - ) + f'"{os.path.splitext(p)[1]}" is not a supported manifest format.' ) dirs = {mozpath.normpath(d[len(topsrcdir) :]).lstrip("/") for d in dirs} diff --git a/python/mozbuild/mozbuild/action/tooltool.py b/python/mozbuild/mozbuild/action/tooltool.py index eef45c70ac67..75da8699b9be 100755 --- a/python/mozbuild/mozbuild/action/tooltool.py +++ b/python/mozbuild/mozbuild/action/tooltool.py @@ -82,9 +82,7 @@ def retrier(attempts=5, sleeptime=10, max_sleeptime=300, sleepscale=1.5, jitter= jitter = jitter or 0 # py35 barfs on the next line if jitter is None if jitter > sleeptime: # To prevent negative sleep times - raise Exception( - "jitter ({}) must be less than sleep time ({})".format(jitter, sleeptime) - ) + raise Exception(f"jitter ({jitter}) must be less than sleep time ({sleeptime})") sleeptime_real = sleeptime for _ in range(attempts): @@ -271,9 +269,7 @@ def prepare_header_val(val): if not REQUEST_HEADER_ATTRIBUTE_CHARS.match(val): raise BadHeaderValue( # pragma: no cover - "header value value={val} contained an illegal character".format( - val=repr(val) - ) + f"header value value={repr(val)} contained an illegal character" ) return val @@ -301,9 +297,7 @@ def calculate_payload_hash(algorithm, payload, content_type): # pragma: no cove for p in parts: p_hash.update(p) - log.debug( - "calculating payload hash from:\n{parts}".format(parts=pprint.pformat(parts)) - ) + log.debug(f"calculating payload hash from:\n{pprint.pformat(parts)}") return base64.b64encode(p_hash.digest()) @@ -318,7 +312,7 @@ def validate_taskcluster_credentials(credentials): credentials["accessToken"] except KeyError: # pragma: no cover etype, val, tb = sys.exc_info() - raise InvalidCredentials("{etype}: {val}".format(etype=etype, val=val)) + raise InvalidCredentials(f"{etype}: {val}") def normalize_header_attr(val): @@ -372,7 +366,7 @@ def calculate_mac( normalized = normalize_string( mac_type, timestamp, nonce, method, name, host, port, content_hash ) - log.debug("normalized resource for mac calc: {norm}".format(norm=normalized)) + log.debug(f"normalized resource for mac calc: {normalized}") digestmod = getattr(hashlib, algorithm) if not isinstance(normalized, bytes): @@ -418,10 +412,10 @@ def make_taskcluster_header(credentials, req): content_hash, ) - header = 'Hawk mac="{}"'.format(prepare_header_val(mac)) + header = f'Hawk mac="{prepare_header_val(mac)}"' if content_hash: # pragma: no cover - header = '{}, hash="{}"'.format(header, prepare_header_val(content_hash)) + header = f'{header}, hash="{prepare_header_val(content_hash)}"' header = '{header}, id="{id}", ts="{ts}", nonce="{nonce}"'.format( header=header, @@ -430,12 +424,12 @@ def make_taskcluster_header(credentials, req): nonce=prepare_header_val(nonce), ) - log.debug("Hawk header for URL={} method={}: {}".format(url, method, header)) + log.debug(f"Hawk header for URL={url} method={method}: {header}") return header -class FileRecord(object): +class FileRecord: def __init__( self, filename, @@ -628,7 +622,7 @@ class FileRecordJSONDecoder(json.JSONDecoder): return rv -class Manifest(object): +class Manifest: valid_formats = ("json",) def __init__(self, file_records=None): @@ -741,7 +735,7 @@ def open_manifest(manifest_file): """I know how to take a filename and load it into a Manifest object""" if os.path.exists(manifest_file): manifest = Manifest() - with builtins.open(manifest_file, "r") as f: + with builtins.open(manifest_file) as f: manifest.load(f) log.debug("loaded manifest from file '%s'" % manifest_file) return manifest @@ -1704,9 +1698,9 @@ Supported commands are: tooltool_host = os.environ.get("TOOLTOOL_HOST", "tooltool.mozilla-releng.net") taskcluster_proxy_url = os.environ.get("TASKCLUSTER_PROXY_URL") if taskcluster_proxy_url: - tooltool_url = "{}/{}".format(taskcluster_proxy_url, tooltool_host) + tooltool_url = f"{taskcluster_proxy_url}/{tooltool_host}" else: - tooltool_url = "https://{}".format(tooltool_host) + tooltool_url = f"https://{tooltool_host}" options_obj.base_url = [tooltool_url] diff --git a/python/mozbuild/mozbuild/action/unify_symbols.py b/python/mozbuild/mozbuild/action/unify_symbols.py index 4e96a010b298..da9832839b33 100644 --- a/python/mozbuild/mozbuild/action/unify_symbols.py +++ b/python/mozbuild/mozbuild/action/unify_symbols.py @@ -17,11 +17,7 @@ class UnifiedSymbolsFinder(UnifiedFinder): return file1 if not file1: return file2 - errors.error( - "{} is in both {} and {}".format( - path, self._finder1.base, self._finder2.base - ) - ) + errors.error(f"{path} is in both {self._finder1.base} and {self._finder2.base}") def main(): diff --git a/python/mozbuild/mozbuild/analyze/hg.py b/python/mozbuild/mozbuild/analyze/hg.py index 605ff6838eed..1fc7237d7c31 100644 --- a/python/mozbuild/mozbuild/analyze/hg.py +++ b/python/mozbuild/mozbuild/analyze/hg.py @@ -33,10 +33,8 @@ def get_pushlog_chunk(session, start, end): # returns pushes sorted by date res = session.get( URL - + "version=1&startID={0}&\ - endID={1}&full=1".format( - start, end - ) + + f"version=1&startID={start}&\ + endID={end}&full=1" ).json() return sorted(res.items(), key=lambda x: x[1]["date"]) @@ -68,7 +66,7 @@ def get_data(epoch): return {k: v for sublist in data for (k, v) in sublist} -class Pushlog(object): +class Pushlog: def __init__(self, days): info = get_data(unix_from_date(days, datetime.today())) self.pushlog = info @@ -89,14 +87,14 @@ class Pushlog(object): return keys -class Push(object): +class Push: def __init__(self, pid, p_dict): self.id = pid self.date = p_dict["date"] self.files = [f for x in p_dict["changesets"] for f in x["files"]] -class Report(object): +class Report: def __init__(self, days, path=None, cost_dict=None): obj = Pushlog(days) self.file_set = obj.file_set diff --git a/python/mozbuild/mozbuild/artifact_cache.py b/python/mozbuild/mozbuild/artifact_cache.py index a2d960ec6be2..998ccc5bb4b6 100644 --- a/python/mozbuild/mozbuild/artifact_cache.py +++ b/python/mozbuild/mozbuild/artifact_cache.py @@ -148,7 +148,7 @@ class ArtifactPersistLimit(dlmanager.PersistLimit): self.files = [] -class ArtifactCache(object): +class ArtifactCache: """Fetch artifacts from URLS and purge least recently used artifacts from disk.""" def __init__(self, cache_dir, log=None, skip_cache=False): diff --git a/python/mozbuild/mozbuild/artifact_commands.py b/python/mozbuild/mozbuild/artifact_commands.py index 8050a9b0ecc2..83da36b3940b 100644 --- a/python/mozbuild/mozbuild/artifact_commands.py +++ b/python/mozbuild/mozbuild/artifact_commands.py @@ -303,9 +303,9 @@ def artifact_toolchain( tooltool_host = os.environ.get("TOOLTOOL_HOST", "tooltool.mozilla-releng.net") taskcluster_proxy_url = os.environ.get("TASKCLUSTER_PROXY_URL") if taskcluster_proxy_url: - tooltool_url = "{}/{}".format(taskcluster_proxy_url, tooltool_host) + tooltool_url = f"{taskcluster_proxy_url}/{tooltool_host}" else: - tooltool_url = "https://{}".format(tooltool_host) + tooltool_url = f"https://{tooltool_host}" cache = ArtifactCache( cache_dir=cache_dir, log=command_context.log, skip_cache=skip_cache @@ -362,7 +362,7 @@ def artifact_toolchain( if tooltool_manifest: manifest = open_manifest(tooltool_manifest) for record in manifest.file_records: - url = "{}/{}/{}".format(tooltool_url, record.algorithm, record.digest) + url = f"{tooltool_url}/{record.algorithm}/{record.digest}" records[record.filename] = DownloadRecord( url, record.filename, @@ -394,7 +394,7 @@ def artifact_toolchain( user_value = b if not b.startswith("toolchain-"): - b = "toolchain-{}".format(b) + b = f"toolchain-{b}" task = tasks.get(b) if not task: diff --git a/python/mozbuild/mozbuild/artifacts.py b/python/mozbuild/mozbuild/artifacts.py index 0c744f478e36..c2961140b437 100644 --- a/python/mozbuild/mozbuild/artifacts.py +++ b/python/mozbuild/mozbuild/artifacts.py @@ -86,7 +86,7 @@ MAX_CACHED_TASKS = 400 # Number of pushheads to cache Task Cluster task data fo PROCESSED_SUFFIX = ".processed.jar" -class ArtifactJob(object): +class ArtifactJob: trust_domain = "gecko" default_candidate_trees = [ "releases/mozilla-release", @@ -230,13 +230,13 @@ class ArtifactJob(object): ) if self._tests_re and not tests_artifact: raise ValueError( - 'Expected tests archive matching "{re}", but ' - "found none!".format(re=self._tests_re) + f'Expected tests archive matching "{self._tests_re}", but ' + "found none!" ) if self._maven_zip_re and not maven_zip_artifact: raise ValueError( - 'Expected Maven zip archive matching "{re}", but ' - "found none!".format(re=self._maven_zip_re) + f'Expected Maven zip archive matching "{self._maven_zip_re}", but ' + "found none!" ) @contextmanager @@ -315,10 +315,8 @@ class ArtifactJob(object): if not added_entry: raise ValueError( - 'Archive format changed! No pattern from "{patterns}"' - "matched an archive path.".format( - patterns=LinuxArtifactJob.test_artifact_patterns - ) + f'Archive format changed! No pattern from "{LinuxArtifactJob.test_artifact_patterns}"' + "matched an archive path." ) def process_tests_tar_artifact(self, filename, processed_filename): @@ -378,10 +376,8 @@ class ArtifactJob(object): if not added_entry: raise ValueError( - 'Archive format changed! No pattern from "{patterns}"' - "matched an archive path.".format( - patterns=LinuxArtifactJob.test_artifact_patterns - ) + f'Archive format changed! No pattern from "{LinuxArtifactJob.test_artifact_patterns}"' + "matched an archive path." ) def process_symbols_archive( @@ -417,7 +413,7 @@ class ArtifactJob(object): ) break else: - raise ValueError('"{}" is not a recognized extra archive!'.format(filename)) + raise ValueError(f'"{filename}" is not a recognized extra archive!') src_prefix = extra_archive["src_prefix"] dest_prefix = extra_archive["dest_prefix"] @@ -599,10 +595,8 @@ class LinuxArtifactJob(ArtifactJob): if not added_entry: raise ValueError( - 'Archive format changed! No pattern from "{patterns}" ' - "matched an archive path.".format( - patterns=LinuxArtifactJob.package_artifact_patterns - ) + f'Archive format changed! No pattern from "{LinuxArtifactJob.package_artifact_patterns}" ' + "matched an archive path." ) @@ -726,9 +720,7 @@ class MacArtifactJob(ArtifactJob): bundle_dirs = glob.glob(mozpath.join(tempdir, "*.app")) if len(bundle_dirs) != 1: - raise ValueError( - "Expected one source bundle, found: {}".format(bundle_dirs) - ) + raise ValueError(f"Expected one source bundle, found: {bundle_dirs}") [source] = bundle_dirs # These get copied into dist/bin with the path, so "root/a/b/c" -> "dist/bin/a/b/c". @@ -848,12 +840,12 @@ class WinArtifactJob(ArtifactJob): if not added_entry: raise ValueError( - 'Archive format changed! No pattern from "{patterns}"' - "matched an archive path.".format(patterns=self.artifact_patterns) + f'Archive format changed! No pattern from "{self.artifact_patterns}"' + "matched an archive path." ) -class ThunderbirdMixin(object): +class ThunderbirdMixin: trust_domain = "comm" product = "thunderbird" try_tree = "try-comm-central" @@ -936,7 +928,7 @@ def cachedmethod(cachefunc): return decorator -class CacheManager(object): +class CacheManager: """Maintain an LRU cache. Provide simple persistence, including support for loading and saving the state using a "with" block. Allow clearing the cache and printing the cache for debugging. @@ -1085,13 +1077,7 @@ class TaskCache(CacheManager): if job.endswith("-opt"): tree += ".shippable" - namespace = "{trust_domain}.v2.{tree}.revision.{rev}.{product}.{job}".format( - trust_domain=artifact_job_class.trust_domain, - rev=rev, - tree=tree, - product=artifact_job_class.product, - job=job, - ) + namespace = f"{artifact_job_class.trust_domain}.v2.{tree}.revision.{rev}.{artifact_job_class.product}.{job}" self.log( logging.DEBUG, "artifact", @@ -1103,14 +1089,12 @@ class TaskCache(CacheManager): except KeyError: # Not all revisions correspond to pushes that produce the job we # care about; and even those that do may not have completed yet. - raise ValueError( - "Task for {namespace} does not exist (yet)!".format(namespace=namespace) - ) + raise ValueError(f"Task for {namespace} does not exist (yet)!") return taskId, list_artifacts(taskId) -class Artifacts(object): +class Artifacts: """Maintain state to efficiently fetch build artifacts from a Firefox tree.""" def __init__( @@ -1277,7 +1261,7 @@ class Artifacts(object): self._git, "rev-list", "--topo-order", - "--max-count={num}".format(num=NUM_REVISIONS_TO_QUERY), + f"--max-count={NUM_REVISIONS_TO_QUERY}", "HEAD", ], universal_newlines=True, @@ -1345,7 +1329,7 @@ class Artifacts(object): "--template", "{rev}:{node}\n", "-r", - "last(public() and ::., {num})".format(num=NUM_REVISIONS_TO_QUERY), + f"last(public() and ::., {NUM_REVISIONS_TO_QUERY})", cwd=self._topsrcdir, ).splitlines() @@ -1417,11 +1401,9 @@ https://firefox-source-docs.mozilla.org/contributing/vcs/mercurial_bundles.html if not count: raise Exception( - "Could not find any candidate pushheads in the last {num} revisions.\n" - "Search started with {rev}, which must be known to Mozilla automation.\n\n" - "see https://firefox-source-docs.mozilla.org/contributing/build/artifact_builds.html".format( # noqa E501 - rev=last_revs[0], num=NUM_PUSHHEADS_TO_QUERY_PER_PARENT - ) + f"Could not find any candidate pushheads in the last {NUM_PUSHHEADS_TO_QUERY_PER_PARENT} revisions.\n" + f"Search started with {last_revs[0]}, which must be known to Mozilla automation.\n\n" + f"see https://firefox-source-docs.mozilla.org/contributing/build/artifact_builds.html" ) def find_pushhead_artifacts(self, task_cache, job, tree, pushhead): @@ -1656,9 +1638,7 @@ https://firefox-source-docs.mozilla.org/contributing/vcs/mercurial_bundles.html url = get_artifact_url(taskId, artifact_name) urls.append(url) if not urls: - raise ValueError( - "Task {taskId} existed, but no artifacts found!".format(taskId=taskId) - ) + raise ValueError(f"Task {taskId} existed, but no artifacts found!") for url in urls: if self.install_from_url(url, distdir): return 1 diff --git a/python/mozbuild/mozbuild/backend/base.py b/python/mozbuild/mozbuild/backend/base.py index 48ab289a66e9..037c17970577 100644 --- a/python/mozbuild/mozbuild/backend/base.py +++ b/python/mozbuild/mozbuild/backend/base.py @@ -139,7 +139,7 @@ class BuildBackend(LoggingMixin): for path in delete_files: full_path = mozpath.join(self.environment.topobjdir, path) try: - with open(full_path, mode="r", encoding="utf-8") as existing: + with open(full_path, encoding="utf-8") as existing: old_content = existing.read() if old_content: self.file_diffs[full_path] = simple_diff( @@ -236,7 +236,7 @@ class BuildBackend(LoggingMixin): purgecaches_dirs.append(bundledir) for dir in purgecaches_dirs: - with open(mozpath.join(dir, ".purgecaches"), "wt") as f: + with open(mozpath.join(dir, ".purgecaches"), "w") as f: f.write("\n") def post_build(self, config, output, jobs, verbose, status): diff --git a/python/mozbuild/mozbuild/backend/common.py b/python/mozbuild/mozbuild/backend/common.py index abbf71547262..71b09b41fa08 100644 --- a/python/mozbuild/mozbuild/backend/common.py +++ b/python/mozbuild/mozbuild/backend/common.py @@ -46,10 +46,10 @@ from mozbuild.jar import DeprecatedJarManifest, JarManifestParser from mozbuild.preprocessor import Preprocessor -class XPIDLManager(object): +class XPIDLManager: """Helps manage XPCOM IDLs in the context of the build system.""" - class Module(object): + class Module: def __init__(self): self.idl_files = set() self.directories = set() @@ -92,7 +92,7 @@ class XPIDLManager(object): return itertools.chain(*[m.stems() for m in self.modules.values()]) -class BinariesCollection(object): +class BinariesCollection: """Tracks state of binaries produced by the build.""" def __init__(self): diff --git a/python/mozbuild/mozbuild/backend/configenvironment.py b/python/mozbuild/mozbuild/backend/configenvironment.py index 9f8cfb3f8f6c..c5754b5fd3cc 100644 --- a/python/mozbuild/mozbuild/backend/configenvironment.py +++ b/python/mozbuild/mozbuild/backend/configenvironment.py @@ -25,7 +25,7 @@ class ConfigStatusFailure(Exception): """Error loading config.status""" -class BuildConfig(object): +class BuildConfig: """Represents the output of configure.""" _CODE_CACHE = {} @@ -53,7 +53,7 @@ class BuildConfig(object): mod.__file__ = path sys.modules["config.status"] = mod - with open(path, "rt") as fh: + with open(path) as fh: source = fh.read() code_cache[path] = ( mtime, @@ -75,7 +75,7 @@ class BuildConfig(object): return config -class ConfigEnvironment(object): +class ConfigEnvironment: """Perform actions associated with a configured but bare objdir. The purpose of this class is to preprocess files from the source directory @@ -197,7 +197,7 @@ class ConfigEnvironment(object): ) -class PartialConfigDict(object): +class PartialConfigDict: """Facilitates mapping the config.statusd defines & substs with dict-like access. This allows a buildconfig client to use buildconfig.defines['FOO'] (and @@ -296,7 +296,7 @@ class PartialConfigDict(object): yield var, self[var] -class PartialConfigEnvironment(object): +class PartialConfigEnvironment: """Allows access to individual config.status items via config.statusd/* files. This class is similar to the full ConfigEnvironment, which uses diff --git a/python/mozbuild/mozbuild/backend/mach_commands.py b/python/mozbuild/mozbuild/backend/mach_commands.py index 112f6c0e2e84..8225f7560f51 100644 --- a/python/mozbuild/mozbuild/backend/mach_commands.py +++ b/python/mozbuild/mozbuild/backend/mach_commands.py @@ -172,11 +172,7 @@ def setup_vscode(command_context, interactive): with open(vscode_settings) as fh: old_settings_str = fh.read() except FileNotFoundError: - print( - "Configuration for {} will be created.{}".format( - vscode_settings, artifact_prefix - ) - ) + print(f"Configuration for {vscode_settings} will be created.{artifact_prefix}") old_settings_str = None if old_settings_str is None: @@ -230,9 +226,7 @@ def setup_vscode(command_context, interactive): ) ) choice = prompt_bool( - "{}{}\nProceed with modifications to {}?".format( - artifact_prefix, prompt_prefix, vscode_settings - ) + f"{artifact_prefix}{prompt_prefix}\nProceed with modifications to {vscode_settings}?" ) if not choice: return 1 @@ -247,9 +241,7 @@ def setup_vscode(command_context, interactive): # binary was not found. if vscode_cmd is None: print( - "Please open VS Code manually and load directory: {}".format( - command_context.topsrcdir - ) + f"Please open VS Code manually and load directory: {command_context.topsrcdir}" ) return 0 @@ -261,7 +253,7 @@ def setup_vscode(command_context, interactive): "ide", {}, "Unable to open VS Code. Please open VS Code manually and load " - "directory: {}".format(command_context.topsrcdir), + f"directory: {command_context.topsrcdir}", ) return rc @@ -287,7 +279,7 @@ def setup_clangd_rust_in_vscode(command_context): logging.ERROR, "ide", {}, - "Unable to locate clangd in {}.".format(clang_tidy_bin), + f"Unable to locate clangd in {clang_tidy_bin}.", ) rc = get_clang_tools(command_context, clang_tools_path) diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py index 6c0cb7951a1b..a22d6569f941 100644 --- a/python/mozbuild/mozbuild/backend/recursivemake.py +++ b/python/mozbuild/mozbuild/backend/recursivemake.py @@ -122,7 +122,7 @@ def make_quote(s): return s.replace("#", r"\#").replace("$", "$$") -class BackendMakeFile(object): +class BackendMakeFile: """Represents a generated backend.mk file. This is both a wrapper around a file handle as well as a container that @@ -193,7 +193,7 @@ class BackendMakeFile(object): return self.fh.diff -class RecursiveMakeTraversal(object): +class RecursiveMakeTraversal: """ Helper class to keep track of how the "traditional" recursive make backend recurses subdirectories. This is useful until all adhoc rules are removed @@ -1751,7 +1751,7 @@ class RecursiveMakeBackend(MakeBackend): for manifest in sorted(manifests): master.write('["include:%s"]\n' % manifest) - class Substitution(object): + class Substitution: """BaseConfigSubstitution-like class for use with _create_makefile.""" __slots__ = ("input_path", "output_path", "topsrcdir", "topobjdir", "config") @@ -1831,7 +1831,7 @@ class RecursiveMakeBackend(MakeBackend): ) ipdl_srcs_path = mozpath.join(ipdl_dir, "ipdlsrcs.txt") - mk.add_statement("ALL_IPDLSRCS_FILE := {}".format(ipdl_srcs_path)) + mk.add_statement(f"ALL_IPDLSRCS_FILE := {ipdl_srcs_path}") # Preprocessed ipdl files are generated in ipdl_dir. mk.add_statement( @@ -1849,10 +1849,10 @@ class RecursiveMakeBackend(MakeBackend): # Windows (32768 bytes) if the checkout path is sufficiently long. with self._write_file(ipdl_srcs_path) as srcs: for filename in sorted_nonstatic_ipdl_basenames: - srcs.write("{}\n".format(filename)) + srcs.write(f"{filename}\n") for filename in sorted_static_ipdl_sources: - srcs.write("{}\n".format(filename)) + srcs.write(f"{filename}\n") with self._write_file(mozpath.join(ipdl_dir, "ipdlsrcs.mk")) as ipdls: mk.dump(ipdls, removal_guard=False) diff --git a/python/mozbuild/mozbuild/base.py b/python/mozbuild/mozbuild/base.py index 9e80a1029b66..a70f3e1348c3 100644 --- a/python/mozbuild/mozbuild/base.py +++ b/python/mozbuild/mozbuild/base.py @@ -64,7 +64,7 @@ class BinaryNotFoundException(Exception): self.path = path def __str__(self): - return "Binary expected at {} does not exist.".format(self.path) + return f"Binary expected at {self.path} does not exist." def help(self): return "It looks like your program isn't built. You can run |./mach build| to build it." @@ -141,7 +141,7 @@ class MozbuildObject(ProcessExecutionMixin): mozconfig = MozconfigLoader.AUTODETECT def load_mozinfo(path): - info = json.load(open(path, "rt", encoding="utf-8")) + info = json.load(open(path, encoding="utf-8")) topsrcdir = info.get("topsrcdir") topobjdir = os.path.dirname(path) mozconfig = info.get("mozconfig") @@ -207,7 +207,7 @@ class MozbuildObject(ProcessExecutionMixin): return True deps = [] - with open(dep_file, "r", encoding="utf-8", newline="\n") as fh: + with open(dep_file, encoding="utf-8", newline="\n") as fh: deps = fh.read().splitlines() mtime = os.path.getmtime(output) @@ -232,7 +232,7 @@ class MozbuildObject(ProcessExecutionMixin): # we last built the backend, re-generate the backend if # so. outputs = [] - with open(backend_file, "r", encoding="utf-8", newline="\n") as fh: + with open(backend_file, encoding="utf-8", newline="\n") as fh: outputs = fh.read().splitlines() for output in outputs: if not os.path.isfile(mozpath.join(self.topobjdir, output)): @@ -936,7 +936,7 @@ class MachCommandBase(MozbuildObject): self._ensure_state_subdir_exists(".") logfile = self._get_state_filename("last_log.json") try: - fd = open(logfile, "wt") + fd = open(logfile, "w") self.log_manager.add_json_handler(fd) except Exception as e: self.log( @@ -952,7 +952,7 @@ class MachCommandBase(MozbuildObject): ) -class MachCommandConditions(object): +class MachCommandConditions: """A series of commonly used condition functions which can be applied to mach commands with providers deriving from MachCommandBase. """ @@ -1061,13 +1061,13 @@ class MachCommandConditions(object): def is_buildapp_in(cls, apps): """Must have a build for one of the given app""" for app in apps: - attr = getattr(MachCommandConditions, "is_{}".format(app), None) + attr = getattr(MachCommandConditions, f"is_{app}", None) if attr and attr(cls): return True return False -class PathArgument(object): +class PathArgument: """Parse a filesystem path argument and transform it in various ways.""" def __init__(self, arg, topsrcdir, topobjdir, cwd=None): diff --git a/python/mozbuild/mozbuild/code_analysis/mach_commands.py b/python/mozbuild/mozbuild/code_analysis/mach_commands.py index 65d6d4f97636..9f480ccb6a4d 100644 --- a/python/mozbuild/mozbuild/code_analysis/mach_commands.py +++ b/python/mozbuild/mozbuild/code_analysis/mach_commands.py @@ -74,7 +74,7 @@ class StaticAnalysisSubCommand(SubCommand): return after -class StaticAnalysisMonitor(object): +class StaticAnalysisMonitor: def __init__(self, srcdir, objdir, checks, total): self._total = total self._processed = 0 @@ -337,7 +337,7 @@ def check( source = get_abspath_files(command_context, files) # Split in several chunks to avoid hitting Python's limit of 100 groups in re - compile_db = json.loads(open(_compile_db, "r").read()) + compile_db = json.loads(open(_compile_db).read()) total = 0 import re @@ -425,7 +425,7 @@ def get_files_with_commands(command_context, compile_db, source): Returns an array of dictionaries having file_path with build command """ - compile_db = json.load(open(compile_db, "r")) + compile_db = json.load(open(compile_db)) commands_list = [] @@ -434,9 +434,7 @@ def get_files_with_commands(command_context, compile_db, source): _, ext = os.path.splitext(f) if ext.lower() not in _format_include_extensions: - command_context.log( - logging.INFO, "static-analysis", {}, "Skipping {}".format(f) - ) + command_context.log(logging.INFO, "static-analysis", {}, f"Skipping {f}") continue file_with_abspath = os.path.join(command_context.topsrcdir, f) for f in compile_db: @@ -486,7 +484,7 @@ def _get_current_version(command_context, clang_paths): logging.INFO, "static-analysis", {}, - "{} Version = {} ".format(clang_paths._clang_format_path, version_info), + f"{clang_paths._clang_format_path} Version = {version_info} ", ) except subprocess.CalledProcessError as e: @@ -495,7 +493,7 @@ def _get_current_version(command_context, clang_paths): "static-analysis", {}, "Error determining the version clang-tidy/format binary, please see the " - "attached exception: \n{}".format(e.output), + f"attached exception: \n{e.output}", ) return version_info @@ -517,12 +515,9 @@ def _is_version_eligible(command_context, clang_paths, log_error=True): logging.ERROR, "static-analysis", {}, - "ERROR: You're using an old or incorrect version ({}) of clang-format binary. " - "Please update to a more recent one (at least > {}) " - "by running: './mach bootstrap' ".format( - _get_current_version(command_context, clang_paths), - _get_required_version(command_context), - ), + f"ERROR: You're using an old or incorrect version ({_get_current_version(command_context, clang_paths)}) of clang-format binary. " + f"Please update to a more recent one (at least > {_get_required_version(command_context)}) " + "by running: './mach bootstrap' ", ) return False @@ -704,9 +699,7 @@ def autotest( logging.ERROR, "static-analysis", {}, - "ERROR: RUNNING: clang-tidy autotest for platform {} not supported.".format( - platform - ), + f"ERROR: RUNNING: clang-tidy autotest for platform {platform} not supported.", ) return TOOLS_UNSUPORTED_PLATFORM @@ -716,9 +709,7 @@ def autotest( logging.INFO, "static-analysis", {}, - "RUNNING: clang-tidy autotest for platform {0} with {1} workers.".format( - platform, max_workers - ), + f"RUNNING: clang-tidy autotest for platform {platform} with {max_workers} workers.", ) # List all available checkers @@ -800,31 +791,27 @@ def autotest( if checker_error == TOOLS_CHECKER_NOT_FOUND: message_to_log = ( "\tChecker " - "{} not present in this clang-tidy version.".format( - checker_name - ) + f"{checker_name} not present in this clang-tidy version." ) elif checker_error == TOOLS_CHECKER_NO_TEST_FILE: message_to_log = ( "\tChecker " - "{0} does not have a test file - {0}.cpp".format(checker_name) + f"{checker_name} does not have a test file - {checker_name}.cpp" ) elif checker_error == TOOLS_CHECKER_RETURNED_NO_ISSUES: message_to_log = ( - "\tChecker {0} did not find any issues in its test file, " - "clang-tidy output for the run is:\n{1}" - ).format(checker_name, info1) + f"\tChecker {checker_name} did not find any issues in its test file, " + f"clang-tidy output for the run is:\n{info1}" + ) elif checker_error == TOOLS_CHECKER_RESULT_FILE_NOT_FOUND: - message_to_log = ( - "\tChecker {0} does not have a result file - {0}.json" - ).format(checker_name) + message_to_log = f"\tChecker {checker_name} does not have a result file - {checker_name}.json" elif checker_error == TOOLS_CHECKER_DIFF_FAILED: message_to_log = ( - "\tChecker {0}\nExpected: {1}\n" - "Got: {2}\n" + f"\tChecker {checker_name}\nExpected: {info1}\n" + f"Got: {info2}\n" "clang-tidy output for the run is:\n" - "{3}" - ).format(checker_name, info1, info2, info3) + f"{info3}" + ) print("\n" + message_to_log) @@ -946,15 +933,11 @@ def _run_analysis_batch(command_context, clang_paths, compilation_commands_path, for failed_check, baseline_issue in zip(failed_checks, failed_checks_baseline): print( - "\tChecker {0} expect following results: \n\t\t{1}".format( - failed_check, baseline_issue - ) + f"\tChecker {failed_check} expect following results: \n\t\t{baseline_issue}" ) print( - "This is the output generated by clang-tidy for the bulk build:\n{}".format( - clang_output - ) + f"This is the output generated by clang-tidy for the bulk build:\n{clang_output}" ) return TOOLS_CHECKER_DIFF_FAILED @@ -1224,7 +1207,7 @@ def _verify_checker( logging.INFO, "static-analysis", {}, - "RUNNING: clang-tidy checker {}.".format(check), + f"RUNNING: clang-tidy checker {check}.", ) # Structured information in case a checker fails @@ -1583,17 +1566,15 @@ def _get_clang_format_diff_command(command_context, commit): else: args += ["-r", ".^"] for dot_extension in _format_include_extensions: - args += ["--include", "glob:**{0}".format(dot_extension)] - args += ["--exclude", "listfile:{0}".format(_format_ignore_file)] + args += ["--include", f"glob:**{dot_extension}"] + args += ["--exclude", f"listfile:{_format_ignore_file}"] else: commit_range = "HEAD" # All uncommitted changes. if commit: - commit_range = ( - commit if ".." in commit else "{}~..{}".format(commit, commit) - ) + commit_range = commit if ".." in commit else f"{commit}~..{commit}" args = ["git", "diff", "--no-color", "-U0", commit_range, "--"] for dot_extension in _format_include_extensions: - args += ["*{0}".format(dot_extension)] + args += [f"*{dot_extension}"] # git-diff doesn't support an 'exclude-from-files' param, but # allow to add individual exclude pattern since v1.9, see # https://git-scm.com/docs/gitglossary#gitglossary-aiddefpathspecapathspec @@ -1650,7 +1631,7 @@ def _is_ignored_path(command_context, ignored_dir_re, f): def _generate_path_list(command_context, paths, verbose=True): path_to_third_party = os.path.join(command_context.topsrcdir, _format_ignore_file) ignored_dir = [] - with open(path_to_third_party, "r") as fh: + with open(path_to_third_party) as fh: for line in fh: # Remove comments and empty lines if line.startswith("#") or len(line.strip()) == 0: @@ -1667,7 +1648,7 @@ def _generate_path_list(command_context, paths, verbose=True): if _is_ignored_path(command_context, ignored_dir_re, f): # Early exit if we have provided an ignored directory if verbose: - print("static-analysis: Ignored third party code '{0}'".format(f)) + print(f"static-analysis: Ignored third party code '{f}'") continue if os.path.isdir(f): @@ -1698,10 +1679,10 @@ def _run_clang_format_in_console(command_context, clang_format, paths, assume_fi # We use -assume-filename in order to better determine the path for # the .clang-format when it is ran outside of the repo, for example # by the extension hg-formatsource - args = [clang_format, "-assume-filename={}".format(assume_filename[0])] + args = [clang_format, f"-assume-filename={assume_filename[0]}"] process = subprocess.Popen(args, stdin=subprocess.PIPE) - with open(paths[0], "r") as fin: + with open(paths[0]) as fin: process.stdin.write(fin.read()) process.stdin.close() process.wait() @@ -1831,11 +1812,11 @@ def _run_clang_format_path( target_path_diff = os.path.join("b", relative_path) e.output = e.output.decode("utf-8") patch = e.output.replace( - "+++ {}".format(target_file), - "+++ {}".format(target_path_diff), + f"+++ {target_file}", + f"+++ {target_path_diff}", ).replace( - "-- {}".format(original_path), - "-- {}".format(original_path_diff), + f"-- {original_path}", + f"-- {original_path_diff}", ) patches[original_path] = patch @@ -1897,7 +1878,7 @@ def _parse_xml_output(path, clang_output): list of patches, and calculates line level informations from the character level provided changes. """ - content = six.ensure_str(open(path, "r").read()) + content = six.ensure_str(open(path).read()) def _nb_of_lines(start, end): return len(content[start:end].splitlines()) diff --git a/python/mozbuild/mozbuild/code_analysis/utils.py b/python/mozbuild/mozbuild/code_analysis/utils.py index e3931aa7e4eb..365f5158bee1 100644 --- a/python/mozbuild/mozbuild/code_analysis/utils.py +++ b/python/mozbuild/mozbuild/code_analysis/utils.py @@ -10,7 +10,7 @@ import yaml from mozbuild.util import memoized_property -class ClangTidyConfig(object): +class ClangTidyConfig: def __init__(self, mozilla_src): self._clang_tidy_config = self._get_clang_tidy_config(mozilla_src) diff --git a/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py b/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py index 7935cd6905ad..b8d5d0b2050f 100644 --- a/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py +++ b/python/mozbuild/mozbuild/codecoverage/lcov_rewriter.py @@ -18,7 +18,7 @@ from mozpack.chrome.manifest import parse_manifest from .manifest_handler import ChromeManifestHandler -class LcovRecord(object): +class LcovRecord: __slots__ = ( "test_name", "source_file", @@ -83,7 +83,7 @@ class LcovRecord(object): self.covered_branch_count = len([c for c in self.branches.values() if c]) -class RecordRewriter(object): +class RecordRewriter: # Helper class for rewriting/spliting individual lcov records according # to what the preprocessor did. def __init__(self): @@ -194,7 +194,7 @@ class RecordRewriter(object): return generated_records -class LcovFile(object): +class LcovFile: # Simple parser/pretty-printer for lcov format. # lcov parsing based on http://ltp.sourceforge.net/coverage/lcov/geninfo.1.php @@ -234,7 +234,7 @@ class LcovFile(object): current_pp_info = None current_lines = [] for lcov_path in self.lcov_paths: - with open(lcov_path, "r", encoding="utf-8") as lcov_fh: + with open(lcov_path, encoding="utf-8") as lcov_fh: for line in lcov_fh: line = line.rstrip() if not line: @@ -423,7 +423,7 @@ class UrlFinderError(Exception): pass -class UrlFinder(object): +class UrlFinder: # Given a "chrome://" or "resource://" url, uses data from the UrlMapBackend # and install manifests to find a path to the source file and the corresponding # (potentially pre-processed) file in the objdir. @@ -432,7 +432,7 @@ class UrlFinder(object): self._final_mapping = {} try: - with open(chrome_map_path, "r", encoding="utf-8") as fh: + with open(chrome_map_path, encoding="utf-8") as fh: url_prefixes, overrides, install_info, buildconfig = json.load(fh) except OSError: print( @@ -643,7 +643,7 @@ class UrlFinder(object): return result -class LcovFileRewriter(object): +class LcovFileRewriter: # Class for partial parses of LCOV format and rewriting to resolve urls # and preprocessed file lines. def __init__( diff --git a/python/mozbuild/mozbuild/codecoverage/manifest_handler.py b/python/mozbuild/mozbuild/codecoverage/manifest_handler.py index 1f67b4089c4d..ffc01a74ccdb 100644 --- a/python/mozbuild/mozbuild/codecoverage/manifest_handler.py +++ b/python/mozbuild/mozbuild/codecoverage/manifest_handler.py @@ -19,7 +19,7 @@ from mozpack.chrome.manifest import ( ) -class ChromeManifestHandler(object): +class ChromeManifestHandler: def __init__(self): self.overrides = {} self.chrome_mapping = defaultdict(set) diff --git a/python/mozbuild/mozbuild/compilation/warnings.py b/python/mozbuild/mozbuild/compilation/warnings.py index 3928538de59e..6e73e7eb46fc 100644 --- a/python/mozbuild/mozbuild/compilation/warnings.py +++ b/python/mozbuild/mozbuild/compilation/warnings.py @@ -103,7 +103,7 @@ class CompilerWarning(dict): return hash(tuple(sorted(self.items()))) -class WarningsDatabase(object): +class WarningsDatabase: """Holds a collection of warnings. The warnings database is a semi-intelligent container that holds warnings @@ -275,7 +275,7 @@ class WarningsDatabase(object): def load_from_file(self, filename): """Load the database from a file.""" - with open(filename, "r", encoding="utf-8") as fh: + with open(filename, encoding="utf-8") as fh: self.deserialize(fh) def save_to_file(self, filename): @@ -286,7 +286,7 @@ class WarningsDatabase(object): self.serialize(fh) -class WarningsCollector(object): +class WarningsCollector: """Collects warnings from text data. Instances of this class receive data (usually the output of compiler diff --git a/python/mozbuild/mozbuild/config_status.py b/python/mozbuild/mozbuild/config_status.py index bd62d5ee6528..07bc0f8d4941 100644 --- a/python/mozbuild/mozbuild/config_status.py +++ b/python/mozbuild/mozbuild/config_status.py @@ -222,8 +222,8 @@ def config_status( untracked = wall_time - execution_time print( - "Total wall time: {:.2f}s; CPU time: {:.2f}s; Efficiency: " - "{:.0%}; Untracked: {:.2f}s".format(wall_time, cpu_time, efficiency, untracked), + f"Total wall time: {wall_time:.2f}s; CPU time: {cpu_time:.2f}s; Efficiency: " + f"{efficiency:.0%}; Untracked: {untracked:.2f}s", file=sys.stderr, ) diff --git a/python/mozbuild/mozbuild/configure/__init__.py b/python/mozbuild/mozbuild/configure/__init__.py index ba9ce6752351..c2b92577d0ab 100644 --- a/python/mozbuild/mozbuild/configure/__init__.py +++ b/python/mozbuild/mozbuild/configure/__init__.py @@ -43,7 +43,7 @@ class ConfigureError(Exception): pass -class SandboxDependsFunction(object): +class SandboxDependsFunction: """Sandbox-visible representation of @depends functions.""" def __init__(self, unsandboxed): @@ -105,7 +105,7 @@ class SandboxDependsFunction(object): raise ConfigureError("Cannot do boolean operations on @depends functions.") -class DependsFunction(object): +class DependsFunction: __slots__ = ( "_func", "_name", diff --git a/python/mozbuild/mozbuild/configure/help.py b/python/mozbuild/mozbuild/configure/help.py index 972fa01bf324..588b5ed1e01d 100644 --- a/python/mozbuild/mozbuild/configure/help.py +++ b/python/mozbuild/mozbuild/configure/help.py @@ -9,7 +9,7 @@ from collections import defaultdict from mozbuild.configure.options import Option -class HelpFormatter(object): +class HelpFormatter: def __init__(self, argv0): self.intro = ["Usage: %s [options]" % os.path.basename(argv0)] self.options = [] diff --git a/python/mozbuild/mozbuild/configure/lint.py b/python/mozbuild/mozbuild/configure/lint.py index 285e16d277f1..df54a394a5a8 100644 --- a/python/mozbuild/mozbuild/configure/lint.py +++ b/python/mozbuild/mozbuild/configure/lint.py @@ -232,14 +232,12 @@ class LintSandbox(ConfigureSandbox): }, } for prefix, replacement in table[default].items(): - if name.startswith("--{}-".format(prefix)): + if name.startswith(f"--{prefix}-"): frame = self._pretty_current_frame() e = ConfigureError( "{} should be used instead of " "{} with default={}".format( - name.replace( - "--{}-".format(prefix), "--{}-".format(replacement) - ), + name.replace(f"--{prefix}-", f"--{replacement}-"), name, default, ) @@ -280,7 +278,7 @@ class LintSandbox(ConfigureSandbox): rule = "{With|Without}" frame = self._pretty_current_frame() - e = ConfigureError('`help` should contain "{}" because {}'.format(rule, check)) + e = ConfigureError(f'`help` should contain "{rule}" because {check}') self._raise_from(e, frame.f_back if frame else None) def _check_help_message(self, option, *args, **kwargs): @@ -340,9 +338,7 @@ class LintSandbox(ConfigureSandbox): what = _import.split(".")[0] imports.add(what) if _from == "__builtin__" and _import in glob["__builtins__"]: - e = NameError( - "builtin '{}' doesn't need to be imported".format(_import) - ) + e = NameError(f"builtin '{_import}' doesn't need to be imported") self._raise_from(e, func) for instr in Bytecode(func): code = func.__code__ @@ -355,7 +351,7 @@ class LintSandbox(ConfigureSandbox): ): # Raise the same kind of error as what would happen during # execution. - e = NameError("global name '{}' is not defined".format(instr.argval)) + e = NameError(f"global name '{instr.argval}' is not defined") if instr.starts_line is None: self._raise_from(e, func) else: diff --git a/python/mozbuild/mozbuild/configure/options.py b/python/mozbuild/mozbuild/configure/options.py index 6ba4d59380b4..db2f42e31250 100644 --- a/python/mozbuild/mozbuild/configure/options.py +++ b/python/mozbuild/mozbuild/configure/options.py @@ -161,7 +161,7 @@ class ConflictingOptionError(InvalidOptionError): setattr(self, k, v) -class Option(object): +class Option: """Represents a configure option A configure option can be a command line flag or an environment variable @@ -509,7 +509,7 @@ class Option(object): return "<%s [%s]>" % (self.__class__.__name__, self.option) -class CommandLineHelper(object): +class CommandLineHelper: """Helper class to handle the various ways options can be given either on the command line of through the environment. diff --git a/python/mozbuild/mozbuild/configure/util.py b/python/mozbuild/mozbuild/configure/util.py index 3f8d2873af83..c411fe618cdd 100644 --- a/python/mozbuild/mozbuild/configure/util.py +++ b/python/mozbuild/mozbuild/configure/util.py @@ -198,7 +198,7 @@ class ConfigureOutputHandler(logging.Handler): self._keep_if_debug = self.KEEP -class LineIO(object): +class LineIO: """File-like class that sends each line of the written data to a callback (without carriage returns). """ diff --git a/python/mozbuild/mozbuild/controller/building.py b/python/mozbuild/mozbuild/controller/building.py index ef9aabc14445..8fea62c70f8d 100644 --- a/python/mozbuild/mozbuild/controller/building.py +++ b/python/mozbuild/mozbuild/controller/building.py @@ -92,7 +92,7 @@ BuildOutputResult = namedtuple( ) -class TierStatus(object): +class TierStatus: """Represents the state and progress of tier traversal. The build system is organized into linear phases called tiers. Each tier @@ -766,9 +766,10 @@ class StaticAnalysisOutputManager(OutputManager): self._handler.release() def write(self, path, output_format): - assert output_format in ("text", "json"), "Invalid output format {}".format( - output_format - ) + assert output_format in ( + "text", + "json", + ), f"Invalid output format {output_format}" path = mozpath.realpath(path) if output_format == "json": @@ -786,7 +787,7 @@ class StaticAnalysisOutputManager(OutputManager): ) -class CCacheStats(object): +class CCacheStats: """Holds statistics from ccache. Instances can be subtracted from each other to obtain differences. @@ -1787,7 +1788,7 @@ class BuildDriver(MozbuildObject): # Copy the original mozconfig to the objdir. mozconfig_objdir = mozpath.join(self.topobjdir, ".mozconfig") if mozconfig["path"]: - with open(mozconfig["path"], "r") as ifh: + with open(mozconfig["path"]) as ifh: with FileAvoidWrite(mozconfig_objdir) as ofh: ofh.write(ifh.read()) else: diff --git a/python/mozbuild/mozbuild/controller/clobber.py b/python/mozbuild/mozbuild/controller/clobber.py index a944b93d3b1e..faa218be6cb5 100644 --- a/python/mozbuild/mozbuild/controller/clobber.py +++ b/python/mozbuild/mozbuild/controller/clobber.py @@ -42,7 +42,7 @@ Well, are ya? -- you can ignore this clobber requirement by running: ) -class Clobberer(object): +class Clobberer: def __init__(self, topsrcdir, topobjdir, substs=None): """Create a new object to manage clobbering the tree. @@ -87,7 +87,7 @@ class Clobberer(object): This returns a list of lines describing why the clobber was required. Each line is stripped of leading and trailing whitespace. """ - with open(self.src_clobber, "rt") as fh: + with open(self.src_clobber) as fh: lines = [l.strip() for l in fh.readlines()] return [l for l in lines if l and not l.startswith("#")] diff --git a/python/mozbuild/mozbuild/doctor.py b/python/mozbuild/mozbuild/doctor.py index 4ea61cce5bc8..399245b0e95f 100644 --- a/python/mozbuild/mozbuild/doctor.py +++ b/python/mozbuild/mozbuild/doctor.py @@ -164,7 +164,7 @@ def ssh(**kwargs) -> DoctorCheck: name="ssh", status=CheckStatus.FATAL, display_text=[ - "SSH username `{}` is not an email address.".format(username), + f"SSH username `{username}` is not an email address.", "hg.mozilla.org logins should be in the form `user@domain.com`.", ], ) @@ -173,8 +173,8 @@ def ssh(**kwargs) -> DoctorCheck: name="ssh", status=CheckStatus.WARNING, display_text=[ - "SSH username `{}` does not have permission to push to " - "hg.mozilla.org.".format(username) + f"SSH username `{username}` does not have permission to push to " + "hg.mozilla.org." ], ) @@ -429,7 +429,7 @@ def mozillabuild(**kwargs) -> DoctorCheck: ) try: - with open(mozpath.join(MOZILLABUILD, "VERSION"), "r") as fh: + with open(mozpath.join(MOZILLABUILD, "VERSION")) as fh: local_version = fh.readline() if not local_version: diff --git a/python/mozbuild/mozbuild/faster_daemon.py b/python/mozbuild/mozbuild/faster_daemon.py index 13fb07a79c3d..0be69af1d9d4 100644 --- a/python/mozbuild/mozbuild/faster_daemon.py +++ b/python/mozbuild/mozbuild/faster_daemon.py @@ -54,14 +54,14 @@ class FasterBuildException(Exception): self.cause = cause -class FasterBuildChange(object): +class FasterBuildChange: def __init__(self): self.unrecognized = set() self.input_to_outputs = {} self.output_to_inputs = {} -class Daemon(object): +class Daemon: def __init__(self, config_environment): self.config_environment = config_environment self._client = None @@ -218,19 +218,17 @@ class Daemon(object): if verbose: print_line( "watch", - "Subscribing to {}".format(self.config_environment.topsrcdir), + f"Subscribing to {self.config_environment.topsrcdir}", ) self.subscribe_to_topsrcdir() if verbose: - print_line( - "watch", "Watching {}".format(self.config_environment.topsrcdir) - ) + print_line("watch", f"Watching {self.config_environment.topsrcdir}") input_to_outputs = self.file_copier.input_to_outputs_tree() for input, outputs in input_to_outputs.items(): if not outputs: raise Exception( - "Refusing to watch input ({}) with no outputs".format(input) + f"Refusing to watch input ({input}) with no outputs" ) while True: @@ -267,18 +265,14 @@ class Daemon(object): # Abstract away pywatchman errors. raise FasterBuildException( e, - "Command error using pywatchman to watch {}".format( - self.config_environment.topsrcdir - ), + f"Command error using pywatchman to watch {self.config_environment.topsrcdir}", ) except pywatchman.SocketTimeout as e: # Abstract away pywatchman errors. raise FasterBuildException( e, - "Socket timeout using pywatchman to watch {}".format( - self.config_environment.topsrcdir - ), + f"Socket timeout using pywatchman to watch {self.config_environment.topsrcdir}", ) finally: @@ -293,15 +287,15 @@ class Daemon(object): now = datetime.datetime.utcnow() for unrecognized in sorted(change.unrecognized): - print_line("watch", "! {}".format(unrecognized), now=now) + print_line("watch", f"! {unrecognized}", now=now) all_outputs = set() for input in sorted(change.input_to_outputs): outputs = change.input_to_outputs[input] - print_line("watch", "< {}".format(input), now=now) + print_line("watch", f"< {input}", now=now) for output in sorted(outputs): - print_line("watch", "> {}".format(output), now=now) + print_line("watch", f"> {output}", now=now) all_outputs |= outputs if all_outputs: diff --git a/python/mozbuild/mozbuild/frontend/context.py b/python/mozbuild/mozbuild/frontend/context.py index b92bef4d7b51..9133d3fe5f21 100644 --- a/python/mozbuild/mozbuild/frontend/context.py +++ b/python/mozbuild/mozbuild/frontend/context.py @@ -42,7 +42,7 @@ from .. import schedules from ..testing import read_manifestparser_manifest, read_reftest_manifest -class ContextDerivedValue(object): +class ContextDerivedValue: """Classes deriving from this one receive a special treatment in a Context. See Context documentation. """ @@ -781,7 +781,7 @@ def Enum(*values): assert len(values) default = values[0] - class EnumClass(object): + class EnumClass: def __new__(cls, value=None): if value is None: return default @@ -1037,7 +1037,7 @@ def ContextDerivedTypedRecord(*fields): return _TypedRecord -class Schedules(object): +class Schedules: """Similar to a ContextDerivedTypedRecord, but with different behavior for the properties: diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py index ee2cffed026d..dbbd871b0ce5 100644 --- a/python/mozbuild/mozbuild/frontend/data.py +++ b/python/mozbuild/mozbuild/frontend/data.py @@ -27,7 +27,7 @@ from ..util import group_unified_files from .context import FinalTargetValue -class TreeMetadata(object): +class TreeMetadata: """Base class for all data being captured.""" __slots__ = () @@ -92,7 +92,7 @@ class ContextDerived(TreeMetadata): return mozpath.relpath(self.objdir, self.topobjdir) -class HostMixin(object): +class HostMixin: @property def defines(self): defines = self._context["HOST_DEFINES"] @@ -690,7 +690,7 @@ class SandboxedWasmLibrary(Library): return self.config.substs.get("WASM_OBJ_SUFFIX", "") -class BaseRustLibrary(object): +class BaseRustLibrary: slots = ( "cargo_file", "crate_type", @@ -909,7 +909,7 @@ class HostSharedLibrary(HostMixin, Library): ) -class ExternalLibrary(object): +class ExternalLibrary: """Empty mixin for libraries built by an external build system.""" diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py index b92180c827fa..2ffde7c978f6 100644 --- a/python/mozbuild/mozbuild/frontend/emitter.py +++ b/python/mozbuild/mozbuild/frontend/emitter.py @@ -517,7 +517,7 @@ class TreeMetadataEmitter(LoggingMixin): raise SandboxValidationError( "No Cargo.toml file found in %s" % cargo_file, context ) - with open(cargo_file, "r") as f: + with open(cargo_file) as f: content = toml.load(f) crate_name = content.get("package", {}).get("name") diff --git a/python/mozbuild/mozbuild/frontend/gyp_reader.py b/python/mozbuild/mozbuild/frontend/gyp_reader.py index 884b32d05edd..399e48d6f719 100644 --- a/python/mozbuild/mozbuild/frontend/gyp_reader.py +++ b/python/mozbuild/mozbuild/frontend/gyp_reader.py @@ -398,7 +398,7 @@ def load_gyp(*args): return flat_list, targets, data -class GypProcessor(object): +class GypProcessor: """Reads a gyp configuration in the background using the given executor and emits GypContexts for the backend to process. diff --git a/python/mozbuild/mozbuild/frontend/reader.py b/python/mozbuild/mozbuild/frontend/reader.py index 2d934b424470..9f6292cb909d 100644 --- a/python/mozbuild/mozbuild/frontend/reader.py +++ b/python/mozbuild/mozbuild/frontend/reader.py @@ -70,7 +70,7 @@ def log(logger, level, action, params, formatter): logger.log(level, formatter, extra={"action": action, "params": params}) -class EmptyConfig(object): +class EmptyConfig: """A config object that is empty. This config object is suitable for using with a BuildReader on a vanilla @@ -379,7 +379,7 @@ class MozbuildSandbox(Sandbox): return template_wrapper -class TemplateFunction(object): +class TemplateFunction: def __init__(self, func, sandbox): self.path = func.__code__.co_filename self.name = func.__name__ @@ -817,7 +817,7 @@ class BuildReaderError(Exception): s.write(" %s\n" % traceback.format_exception_only(type(e), e)) -class BuildReader(object): +class BuildReader: """Read a tree of mozbuild files into data structures. This is where the build system starts. You give it a tree configuration @@ -1161,7 +1161,7 @@ class BuildReader(object): logging.DEBUG, "read_mozbuild", {"path": path}, - "Reading file: {path}".format(path=path), + f"Reading file: {path}", ) time_start = time.monotonic() @@ -1179,7 +1179,7 @@ class BuildReader(object): logging.WARNING, "read_already", {"path": path}, - "File already read. Skipping: {path}".format(path=path), + f"File already read. Skipping: {path}", ) return diff --git a/python/mozbuild/mozbuild/generated_sources.py b/python/mozbuild/mozbuild/generated_sources.py index 81b6f4d6d832..135f3a32ff76 100644 --- a/python/mozbuild/mozbuild/generated_sources.py +++ b/python/mozbuild/mozbuild/generated_sources.py @@ -39,7 +39,7 @@ def get_generated_sources(): # First, get the list of generated sources produced by the build backend. gen_sources = os.path.join(buildconfig.topobjdir, "generated-sources.json") - with open(gen_sources, "r") as f: + with open(gen_sources) as f: data = json.load(f) for f in data["sources"]: # Exclute symverscript diff --git a/python/mozbuild/mozbuild/html_build_viewer.py b/python/mozbuild/mozbuild/html_build_viewer.py index 7a99ff774474..0a85e3a20523 100644 --- a/python/mozbuild/mozbuild/html_build_viewer.py +++ b/python/mozbuild/mozbuild/html_build_viewer.py @@ -84,7 +84,7 @@ class HTTPHandler(http.server.BaseHTTPRequestHandler): self.wfile.write(fh.read()) -class BuildViewerServer(object): +class BuildViewerServer: def __init__(self, address="localhost", port=0): # TODO use pkg_resources to obtain HTML resources. pkg_dir = os.path.dirname(os.path.abspath(__file__)) diff --git a/python/mozbuild/mozbuild/jar.py b/python/mozbuild/mozbuild/jar.py index 2d0e26d73c91..365e08067e8e 100644 --- a/python/mozbuild/mozbuild/jar.py +++ b/python/mozbuild/mozbuild/jar.py @@ -30,7 +30,7 @@ if sys.platform == "win32": __all__ = ["JarMaker"] -class ZipEntry(object): +class ZipEntry: """Helper class for jar output. This class defines a simple file-like object for a zipfile.ZipEntry @@ -62,7 +62,7 @@ def getModTime(aPath): return localtime(mtime) -class JarManifestEntry(object): +class JarManifestEntry: def __init__(self, output, source, is_locale=False, preprocess=False): self.output = output self.source = source @@ -70,7 +70,7 @@ class JarManifestEntry(object): self.preprocess = preprocess -class JarInfo(object): +class JarInfo: def __init__(self, base_or_jarinfo, name=None): if name is None: assert isinstance(base_or_jarinfo, JarInfo) @@ -93,7 +93,7 @@ class DeprecatedJarManifest(Exception): pass -class JarManifestParser(object): +class JarManifestParser: ignore = re.compile(r"\s*(#.*)?$") jarline = re.compile( r""" @@ -197,7 +197,7 @@ class JarManifestParser(object): return iter(self._jars) -class JarMaker(object): +class JarMaker: """JarMaker reads jar.mn files and process those into jar files or flat directories, along with chrome.manifest files. """ @@ -295,9 +295,7 @@ class JarMaker(object): register, ) if jarname != "chrome": - addEntriesToListFile( - chromeManifest, ["manifest {0}.manifest".format(jarname)] - ) + addEntriesToListFile(chromeManifest, [f"manifest {jarname}.manifest"]) if self.useChromeManifest: chromebase = os.path.dirname(jarname) + "/" self.updateManifest( @@ -529,7 +527,7 @@ class JarMaker(object): outf.close() inf.close() - class OutputHelper_jar(object): + class OutputHelper_jar: """Provide getDestModTime and getOutput for a given jarfile.""" def __init__(self, jarfile): @@ -545,7 +543,7 @@ class JarMaker(object): def getOutput(self, name, mode="wb"): return ZipEntry(name, self.jarfile) - class OutputHelper_flat(object): + class OutputHelper_flat: """Provide getDestModTime and getOutput for a given flat output directory. The helper method ensureDirFor is used by the symlink subclass. diff --git a/python/mozbuild/mozbuild/mach_commands.py b/python/mozbuild/mozbuild/mach_commands.py index 3b56fcbb2fa7..9ca2e25f01ad 100644 --- a/python/mozbuild/mozbuild/mach_commands.py +++ b/python/mozbuild/mozbuild/mach_commands.py @@ -339,9 +339,7 @@ def cargo( append_env["CARGO_NO_AUTO_ARG"] = "1" else: append_env["ADD_RUST_LTOABLE"] = ( - "force-cargo-library-{s:s} force-cargo-program-{s:s}".format( - s=cargo_command - ) + f"force-cargo-library-{cargo_command:s} force-cargo-program-{cargo_command:s}" ) ret = command_context._run_make( @@ -1244,16 +1242,14 @@ def _print_package_name(command_context): if not os.path.exists(package_name_path): return - with open(package_name_path, "r") as f: + with open(package_name_path) as f: package_name = f.read().strip() package_path = mozpath.join(dist_path, package_name) if not os.path.exists(package_path): return - command_context.log( - logging.INFO, "package", {}, "Created package: {}".format(package_path) - ) + command_context.log(logging.INFO, "package", {}, f"Created package: {package_path}") def _get_android_install_parser(): @@ -1689,7 +1685,7 @@ def _run_android( metadata = metadata_for_app(app) if not metadata.activity_name: - raise RuntimeError("Application not recognized: {}".format(app)) + raise RuntimeError(f"Application not recognized: {app}") # If we want to debug an existing process, we implicitly do not want # to kill it and pave over its installation with a new one. @@ -1735,9 +1731,7 @@ def _run_android( # Always /data/local/tmp, rather than `device.test_root`, because # GeckoView only takes its configuration file from /data/local/tmp, # and we want to follow suit. - target_profile = "/data/local/tmp/{}-profile".format( - metadata.package_name - ) + target_profile = f"/data/local/tmp/{metadata.package_name}-profile" device.rm(target_profile, recursive=True, force=True) device.push(host_profile, target_profile) command_context.log( @@ -1768,7 +1762,7 @@ def _run_android( extras = {} for i, e in enumerate(env): - extras["env{}".format(i)] = e + extras[f"env{i}"] = e if args: extras["args"] = " ".join(args) @@ -3293,7 +3287,7 @@ def repackage_snap_install(command_context, snap_file, snap_name, sudo=None): logging.INFO, "repackage-snap-install-howto-run", {}, - "Example usage: snap run {}".format(snap_name), + f"Example usage: snap run {snap_name}", ) return 0 @@ -3431,7 +3425,7 @@ def package_l10n(command_context, verbose=False, locales=[]): ) command_context._run_make( directory=command_context.topobjdir, - target=["chrome-{}".format(locale) for locale in locales], + target=[f"chrome-{locale}" for locale in locales], append_env=append_env, pass_thru=False, print_directory=False, diff --git a/python/mozbuild/mozbuild/makeutil.py b/python/mozbuild/mozbuild/makeutil.py index 0f693c3f1920..32d2cf635632 100644 --- a/python/mozbuild/mozbuild/makeutil.py +++ b/python/mozbuild/mozbuild/makeutil.py @@ -7,7 +7,7 @@ import re from collections.abc import Iterable -class Makefile(object): +class Makefile: """Provides an interface for writing simple makefiles Instances of this class are created, populated with rules, then @@ -57,7 +57,7 @@ class Makefile(object): guard.dump(fh) -class _SimpleOrderedSet(object): +class _SimpleOrderedSet: """ Simple ordered set, specialized for used in Rule below only. It doesn't expose a complete API, and normalizes path separators @@ -94,7 +94,7 @@ class _SimpleOrderedSet(object): self._list.extend(added) -class Rule(object): +class Rule: """Class handling simple rules in the form: target1 target2 ... : dep1 dep2 ... command1 command2 ... diff --git a/python/mozbuild/mozbuild/mozconfig.py b/python/mozbuild/mozbuild/mozconfig.py index bc3a849fd784..3c9d1dd884a0 100644 --- a/python/mozbuild/mozbuild/mozconfig.py +++ b/python/mozbuild/mozbuild/mozconfig.py @@ -61,7 +61,7 @@ class MozconfigLoadException(Exception): Exception.__init__(self, message) -class MozconfigLoader(object): +class MozconfigLoader: """Handles loading and parsing of mozconfig files.""" RE_MAKE_VARIABLE = re.compile( diff --git a/python/mozbuild/mozbuild/mozinfo.py b/python/mozbuild/mozbuild/mozinfo.py index 5cf76af1946f..c5d4f831d4ba 100644 --- a/python/mozbuild/mozbuild/mozinfo.py +++ b/python/mozbuild/mozbuild/mozinfo.py @@ -109,12 +109,12 @@ def build_dict(config, env=os.environ): if p == "mac": p = "macosx64" elif d["bits"] == 64: - p = "{}64".format(p) + p = f"{p}64" elif p in ("win",): - p = "{}32".format(p) + p = f"{p}32" if d["asan"]: - p = "{}-asan".format(p) + p = f"{p}-asan" return p @@ -165,6 +165,6 @@ def write_mozinfo(file, config, env=os.environ): """ build_conf = build_dict(config, env) if isinstance(file, str): - file = open(file, "wt") + file = open(file, "w") json.dump(build_conf, file, sort_keys=True, indent=4) diff --git a/python/mozbuild/mozbuild/preprocessor.py b/python/mozbuild/mozbuild/preprocessor.py index f9aa6bb3c263..382189e0ee93 100644 --- a/python/mozbuild/mozbuild/preprocessor.py +++ b/python/mozbuild/mozbuild/preprocessor.py @@ -267,9 +267,7 @@ class Expression: self.content = expression.content[:3] def __str__(self): - return 'Unexpected content at offset {0}, "{1}"'.format( - self.offset, self.content - ) + return f'Unexpected content at offset {self.offset}, "{self.content}"' class Context(dict): @@ -366,7 +364,7 @@ class Preprocessor: msg = "no useful preprocessor directives found" if msg: - class Fake(object): + class Fake: pass fake = Fake() @@ -394,7 +392,7 @@ class Preprocessor: self.ambiguous_comment = re.compile(ambiguous_fmt.format(aMarker)) else: - class NoMatch(object): + class NoMatch: def match(self, *args): return False @@ -482,9 +480,7 @@ class Preprocessor: or expected_file and expected_file != next_file ): - self.out.write( - '//@line {line} "{file}"\n'.format(line=next_line, file=next_file) - ) + self.out.write(f'//@line {next_line} "{next_file}"\n') self.noteLineInfo() filteredLine = self.applyFilters(aLine) @@ -532,7 +528,7 @@ class Preprocessor: if args: for f in args: if not isinstance(f, io.TextIOBase): - f = open(f, "r", encoding="utf-8") + f = open(f, encoding="utf-8") with f as input_: self.processFile(input=input_, output=out) if depfile: @@ -868,7 +864,7 @@ class Preprocessor: args = self.applyFilters(args) if not os.path.isabs(args): args = os.path.join(self.curdir, args) - args = open(args, "r", encoding="utf-8") + args = open(args, encoding="utf-8") except Preprocessor.Error: raise except Exception: @@ -922,7 +918,7 @@ class Preprocessor: def preprocess(includes=[sys.stdin], defines={}, output=sys.stdout, marker="#"): pp = Preprocessor(defines=defines, marker=marker) for f in includes: - with open(f, "r", encoding="utf-8") as input: + with open(f, encoding="utf-8") as input: pp.processFile(input=input, output=output) return pp.includes diff --git a/python/mozbuild/mozbuild/repackaging/mar.py b/python/mozbuild/mozbuild/repackaging/mar.py index 46972398e80a..caa9fd21dbd5 100644 --- a/python/mozbuild/mozbuild/repackaging/mar.py +++ b/python/mozbuild/mozbuild/repackaging/mar.py @@ -31,9 +31,7 @@ def repackage_mar(topsrcdir, package, mar, output, arch=None, mar_channel_id=Non raise Exception("Package file %s is not a valid .zip or .tar file." % package) if arch and arch not in _BCJ_OPTIONS: raise Exception( - "Unknown architecture {}, available architectures: {}".format( - arch, list(_BCJ_OPTIONS.keys()) - ) + f"Unknown architecture {arch}, available architectures: {list(_BCJ_OPTIONS.keys())}" ) ensureParentDir(output) diff --git a/python/mozbuild/mozbuild/repackaging/msi.py b/python/mozbuild/mozbuild/repackaging/msi.py index 3773ba14ae50..ff046009f0cf 100644 --- a/python/mozbuild/mozbuild/repackaging/msi.py +++ b/python/mozbuild/mozbuild/repackaging/msi.py @@ -50,9 +50,7 @@ def repackage_msi( if locale is None: raise Exception("locale name must be provided.") if arch is None or arch not in _MSI_ARCH.keys(): - raise Exception( - "arch name must be provided and one of {}.".format(_MSI_ARCH.keys()) - ) + raise Exception(f"arch name must be provided and one of {_MSI_ARCH.keys()}.") if not os.path.isfile(setupexe): raise Exception("%s does not exist." % setupexe) if candle is not None and not os.path.isfile(candle): diff --git a/python/mozbuild/mozbuild/repackaging/msix.py b/python/mozbuild/mozbuild/repackaging/msix.py index 37060201437e..61ca9e215d67 100644 --- a/python/mozbuild/mozbuild/repackaging/msix.py +++ b/python/mozbuild/mozbuild/repackaging/msix.py @@ -358,17 +358,15 @@ def repackage_msix( "nightly", "unofficial", ): - raise Exception("channel is unrecognized: {}".format(channel)) + raise Exception(f"channel is unrecognized: {channel}") # TODO: maybe we can fish this from the package directly? Maybe from a DLL, # maybe from application.ini? if arch is None or arch not in _MSIX_ARCH.keys(): - raise Exception( - "arch name must be provided and one of {}.".format(_MSIX_ARCH.keys()) - ) + raise Exception(f"arch name must be provided and one of {_MSIX_ARCH.keys()}.") if not os.path.exists(dir_or_package): - raise Exception("{} does not exist".format(dir_or_package)) + raise Exception(f"{dir_or_package} does not exist") if ( os.path.isfile(dir_or_package) @@ -412,7 +410,7 @@ def repackage_msix( first = next(values) if not displayname: - displayname = "Mozilla {}".format(first) + displayname = f"Mozilla {first}" if channel == "beta": # Release (official) and Beta share branding. Differentiate Beta a little bit. @@ -482,7 +480,7 @@ def repackage_msix( use_official_branding, topsrcdir, build_app, unpack_finder, log ) if not os.path.isdir(branding): - raise Exception("branding dir {} does not exist".format(branding)) + raise Exception(f"branding dir {branding} does not exist") template = os.path.join(topsrcdir, build_app, "installer", "windows", "msix") @@ -495,31 +493,27 @@ def repackage_msix( # The convention is $MOZBUILD_STATE_PATH/cache/$FEATURE. output_dir = mozpath.normsep( - mozpath.join( - get_state_dir(), "cache", "mach-msix", "msix-temp-{}".format(channel) - ) + mozpath.join(get_state_dir(), "cache", "mach-msix", f"msix-temp-{channel}") ) # Like 'Firefox Package Root', 'Firefox Nightly Package Root', 'Firefox Beta # Package Root'. This is `BrandFullName` in the installer, and we want to # be close but to not match. By not matching, we hope to prevent confusion # and/or errors between regularly installed builds and App Package builds. - instdir = "{} Package Root".format(displayname) + instdir = f"{displayname} Package Root" # The standard package name is like "CompanyNoSpaces.ProductNoSpaces". - identity = identity or "{}.{}".format(vendor, displayname).replace(" ", "") + identity = identity or f"{vendor}.{displayname}".replace(" ", "") # We might want to include the publisher ID hash here. I.e., # "__{publisherID}". My locally produced MSIX was named like # `Mozilla.MozillaFirefoxNightly_89.0.0.0_x64__4gf61r4q480j0`, suggesting also a # missing field, but it's not necessary, since this is just an output file name. - package_output_name = "{identity}_{version}_{arch}".format( - identity=identity, version=version, arch=_MSIX_ARCH[arch] - ) + package_output_name = f"{identity}_{version}_{_MSIX_ARCH[arch]}" # The convention is $MOZBUILD_STATE_PATH/cache/$FEATURE. default_output = mozpath.normsep( mozpath.join( - get_state_dir(), "cache", "mach-msix", "{}.msix".format(package_output_name) + get_state_dir(), "cache", "mach-msix", f"{package_output_name}.msix" ) ) output = output or default_output @@ -796,7 +790,7 @@ def _sign_msix_win(output, force, log, verbose): get_state_dir(), "cache", "mach-msix", - "{}.crt".format(friendly_name).replace(" ", "_").lower(), + f"{friendly_name}.crt".replace(" ", "_").lower(), ) crt_path = mozpath.abspath(crt_path) ensureParentDir(crt_path) @@ -812,25 +806,21 @@ def _sign_msix_win(output, force, log, verbose): logging.INFO, "msix", {"crt_path": crt_path}, - "Creating new self signed certificate at: {}".format(crt_path), + f"Creating new self signed certificate at: {crt_path}", ) thumbprints = [ thumbprint.strip() for thumbprint in powershell( - ( - r"Get-ChildItem -Path Cert:\CurrentUser\My" - '| Where-Object {{$_.Subject -Match "{}"}}' - '| Where-Object {{$_.FriendlyName -Match "{}"}}' - "| Select-Object -ExpandProperty Thumbprint" - ).format(vendor, friendly_name) + r"Get-ChildItem -Path Cert:\CurrentUser\My" + f'| Where-Object {{$_.Subject -Match "{vendor}"}}' + f'| Where-Object {{$_.FriendlyName -Match "{friendly_name}"}}' + "| Select-Object -ExpandProperty Thumbprint" ).splitlines() ] if len(thumbprints) > 1: raise Exception( - "Multiple certificates with friendly name found: {}".format( - friendly_name - ) + f"Multiple certificates with friendly name found: {friendly_name}" ) if len(thumbprints) == 1: @@ -841,14 +831,12 @@ def _sign_msix_win(output, force, log, verbose): if force or not thumbprint: thumbprint = ( powershell( - ( - 'New-SelfSignedCertificate -Type Custom -Subject "{}" ' - '-KeyUsage DigitalSignature -FriendlyName "{}"' - r" -CertStoreLocation Cert:\CurrentUser\My" - ' -TextExtension @("2.5.29.37={{text}}1.3.6.1.5.5.7.3.3", ' - '"2.5.29.19={{text}}")' - "| Select-Object -ExpandProperty Thumbprint" - ).format(publisher, friendly_name) + f'New-SelfSignedCertificate -Type Custom -Subject "{publisher}" ' + f'-KeyUsage DigitalSignature -FriendlyName "{friendly_name}"' + r" -CertStoreLocation Cert:\CurrentUser\My" + ' -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", ' + '"2.5.29.19={text}")' + "| Select-Object -ExpandProperty Thumbprint" ) .strip() .upper() @@ -856,15 +844,11 @@ def _sign_msix_win(output, force, log, verbose): if not thumbprint: raise Exception( - "Failed to find or create certificate with friendly name: {}".format( - friendly_name - ) + f"Failed to find or create certificate with friendly name: {friendly_name}" ) powershell( - r'Export-Certificate -Cert Cert:\CurrentUser\My\{} -FilePath "{}"'.format( - thumbprint, crt_path - ) + rf'Export-Certificate -Cert Cert:\CurrentUser\My\{thumbprint} -FilePath "{crt_path}"' ) log( logging.INFO, @@ -874,10 +858,8 @@ def _sign_msix_win(output, force, log, verbose): ) powershell( - ( - r'Export-PfxCertificate -Cert Cert:\CurrentUser\My\{} -FilePath "{}"' - ' -Password (ConvertTo-SecureString -String "{}" -Force -AsPlainText)' - ).format(thumbprint, pfx_path, password) + rf'Export-PfxCertificate -Cert Cert:\CurrentUser\My\{thumbprint} -FilePath "{pfx_path}"' + f' -Password (ConvertTo-SecureString -String "{password}" -Force -AsPlainText)' ) log( logging.INFO, @@ -899,15 +881,13 @@ def _sign_msix_win(output, force, log, verbose): thumbprints = [ thumbprint.strip() for thumbprint in powershell( - 'Get-PfxCertificate -FilePath "{}" | Select-Object -ExpandProperty Thumbprint'.format( - crt_path - ) + f'Get-PfxCertificate -FilePath "{crt_path}" | Select-Object -ExpandProperty Thumbprint' ).splitlines() ] if len(thumbprints) > 1: - raise Exception("Multiple thumbprints found for PFX: {}".format(pfx_path)) + raise Exception(f"Multiple thumbprints found for PFX: {pfx_path}") if len(thumbprints) == 0: - raise Exception("No thumbprints found for PFX: {}".format(pfx_path)) + raise Exception(f"No thumbprints found for PFX: {pfx_path}") thumbprint = thumbprints[0] log( logging.INFO, @@ -946,8 +926,8 @@ def _sign_msix_win(output, force, log, verbose): root_thumbprints = [ root_thumbprint.strip() for root_thumbprint in powershell( - r"Get-ChildItem -Path Cert:\LocalMachine\Root\{} " - "| Select-Object -ExpandProperty Thumbprint".format(thumbprint), + rf"Get-ChildItem -Path Cert:\LocalMachine\Root\{thumbprint} " + "| Select-Object -ExpandProperty Thumbprint", check=False, ).splitlines() ] @@ -1032,7 +1012,7 @@ def _sign_msix_posix(output, force, log, verbose): key_path = mozpath.join(cache_dir, "MozillaMSIX.key") pfx_path = mozpath.join( cache_dir, - "{}.pfx".format(friendly_name).replace(" ", "_").lower(), + f"{friendly_name}.pfx".replace(" ", "_").lower(), ) pfx_path = mozpath.abspath(pfx_path) ensureParentDir(pfx_path) @@ -1042,7 +1022,7 @@ def _sign_msix_posix(output, force, log, verbose): logging.INFO, "msix", {"pfx_path": pfx_path}, - "Creating new self signed certificate at: {}".format(pfx_path), + f"Creating new self signed certificate at: {pfx_path}", ) # Ultimately, we only end up using the CA certificate diff --git a/python/mozbuild/mozbuild/repackaging/snapcraft_transform.py b/python/mozbuild/mozbuild/repackaging/snapcraft_transform.py index 038c1394f268..110e76e92b6c 100644 --- a/python/mozbuild/mozbuild/repackaging/snapcraft_transform.py +++ b/python/mozbuild/mozbuild/repackaging/snapcraft_transform.py @@ -131,7 +131,7 @@ class SnapcraftTransform: del self.snap["apps"]["firefox"] def change_version(self, version, build): - self.snap["version"] = "{version}-{build}".format(version=version, build=build) + self.snap["version"] = f"{version}-{build}" def change_name(self, name): self.snap["name"] = str(name) @@ -146,7 +146,7 @@ class SnapcraftTransform: class SnapDesktopFile: def __init__(self, log, appname, branchname, wmclass=None): if wmclass is None: - wmclass = "{}-{}".format(appname, branchname) + wmclass = f"{appname}-{branchname}" build_variables = { "DEB_PKG_NAME": appname, diff --git a/python/mozbuild/mozbuild/shellutil.py b/python/mozbuild/mozbuild/shellutil.py index 94cb66b2617c..c3a83f9cecab 100644 --- a/python/mozbuild/mozbuild/shellutil.py +++ b/python/mozbuild/mozbuild/shellutil.py @@ -51,7 +51,7 @@ class MetaCharacterException(Exception): self.char = char -class _ClineSplitter(object): +class _ClineSplitter: """ Parses a given command line string and creates a list of command and arguments, with wildcard expansion. diff --git a/python/mozbuild/mozbuild/telemetry.py b/python/mozbuild/mozbuild/telemetry.py index 3b164b7a0f48..22eadd43f8c4 100644 --- a/python/mozbuild/mozbuild/telemetry.py +++ b/python/mozbuild/mozbuild/telemetry.py @@ -18,7 +18,7 @@ def cpu_brand_linux(): """ Read the CPU brand string out of /proc/cpuinfo on Linux. """ - with open("/proc/cpuinfo", "r") as f: + with open("/proc/cpuinfo") as f: for line in f: if line.startswith("model name"): _, brand = line.split(": ", 1) diff --git a/python/mozbuild/mozbuild/test/action/test_buildlist.py b/python/mozbuild/mozbuild/test/action/test_buildlist.py index 9a1d2738edbf..1a59d9d7d5c1 100644 --- a/python/mozbuild/mozbuild/test/action/test_buildlist.py +++ b/python/mozbuild/mozbuild/test/action/test_buildlist.py @@ -36,20 +36,18 @@ class TestBuildList(unittest.TestCase): """Assert that the lines in the file |filename| are equal to the contents of the list |l|, in order.""" l = l[:] - f = open(filename, "r") + f = open(filename) lines = [line.rstrip() for line in f.readlines()] f.close() for line in lines: self.assertTrue( len(l) > 0, - "ran out of expected lines! (expected '{0}', got '{1}')".format( - l, lines - ), + f"ran out of expected lines! (expected '{l}', got '{lines}')", ) self.assertEqual(line, l.pop(0)) self.assertTrue( len(l) == 0, - "not enough lines in file! (expected '{0}'," " got '{1}'".format(l, lines), + f"not enough lines in file! (expected '{l}'," f" got '{lines}'", ) def test_basic(self): diff --git a/python/mozbuild/mozbuild/test/action/test_html_fragment_preprocessor.py b/python/mozbuild/mozbuild/test/action/test_html_fragment_preprocessor.py index 3cce1c5f9443..02cd445bd151 100644 --- a/python/mozbuild/mozbuild/test/action/test_html_fragment_preprocessor.py +++ b/python/mozbuild/mozbuild/test/action/test_html_fragment_preprocessor.py @@ -165,7 +165,7 @@ class TestNode(unittest.TestCase): EXAMPLE_TEMPLATES, EXAMPLE_XUL, ) - with open(DUMMY_FILE, "r") as file: + with open(DUMMY_FILE) as file: contents = file.read() self.assertIn( "= {0} required (install Rust {0} or newer)".format( - minimum_rust_version - ), + f"Cargo >= {minimum_rust_version} required (install Rust {minimum_rust_version} or newer)", ) return False self.log(logging.DEBUG, "cargo_version", {}, "cargo is new enough") @@ -398,9 +396,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- def _check_licenses(self, vendor_dir: str) -> bool: def verify_acceptable_license(package: str, license: str) -> bool: - self.log( - logging.DEBUG, "package_license", {}, "has license {}".format(license) - ) + self.log(logging.DEBUG, "package_license", {}, f"has license {license}") if not self.runtime_license(package, license): if license not in self.BUILDTIME_LICENSE_WHITELIST: @@ -408,13 +404,11 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_license_error", {}, - """Package {} has a non-approved license: {}. + f"""Package {package} has a non-approved license: {license}. Please request license review on the package's license. If the package's license is approved, please add it to the whitelist of suitable licenses. - """.format( - package, license - ), + """, ) return False elif package not in self.BUILDTIME_LICENSE_WHITELIST[license]: @@ -422,16 +416,14 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_license_error", {}, - """Package {} has a license that is approved for build-time dependencies: - {} + f"""Package {package} has a license that is approved for build-time dependencies: + {license} but the package itself is not whitelisted as being a build-time only package. If your package is build-time only, please add it to the whitelist of build-time only packages. Otherwise, you need to request license review on the package's license. If the package's license is approved, please add it to the whitelist of suitable licenses. - """.format( - package, license - ), + """, ) return False return True @@ -441,7 +433,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.DEBUG, "package_check", {}, - "Checking license for {}".format(package_name), + f"Checking license for {package_name}", ) toml_file = os.path.join(vendor_dir, package_name, "Cargo.toml") @@ -457,9 +449,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_invalid_license_format", {}, - "package {} has an invalid `license` field (expected a string)".format( - package_name - ), + f"package {package_name} has an invalid `license` field (expected a string)", ) return False @@ -468,9 +458,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_invalid_license_format", {}, - "package {} has an invalid `license-file` field (expected a string)".format( - package_name - ), + f"package {package_name} has an invalid `license-file` field (expected a string)", ) return False @@ -481,7 +469,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_no_license", {}, - "package {} does not provide a license".format(package_name), + f"package {package_name} does not provide a license", ) return False @@ -493,7 +481,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_many_licenses", {}, - "package {} provides too many licenses".format(package_name), + f"package {package_name} provides too many licenses", ) return False @@ -506,7 +494,7 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.DEBUG, "package_license_file", {}, - "package has license-file {}".format(license_file), + f"package has license-file {license_file}", ) if package_name not in self.RUNTIME_LICENSE_FILE_PACKAGE_WHITELIST: @@ -514,13 +502,11 @@ Please commit or stash these changes before vendoring, or re-run with `--ignore- logging.ERROR, "package_license_file_unknown", {}, - """Package {} has an unreviewed license file: {}. + f"""Package {package_name} has an unreviewed license file: {license_file}. Please request review on the provided license; if approved, the package can be added to the whitelist of packages whose licenses are suitable. -""".format( - package_name, license_file - ), +""", ) return False @@ -536,13 +522,11 @@ to the whitelist of packages whose licenses are suitable. logging.ERROR, "package_license_file_mismatch", {}, - """Package {} has changed its license file: {} (hash {}). + f"""Package {package_name} has changed its license file: {license_file} (hash {current_hash}). Please request review on the provided license; if approved, please update the license file's hash. -""".format( - package_name, license_file, current_hash - ), +""", ) return False return True @@ -903,11 +887,9 @@ license file's hash. logging.ERROR, "license_check_failed", {}, - """The changes from `mach vendor rust` will NOT be added to version control. + f"""The changes from `mach vendor rust` will NOT be added to version control. -{notice}""".format( - notice=CARGO_LOCK_NOTICE - ), +{CARGO_LOCK_NOTICE}""", ) self.repository.clean_directory(vendor_dir) return False @@ -961,14 +943,12 @@ The changes from `mach vendor rust` will NOT be added to version control. logging.WARN, "filesize_check", {}, - """Your changes add {size} bytes of added files. + f"""Your changes add {cumulative_added_size} bytes of added files. Please consider finding ways to reduce the size of the vendored packages. For instance, check the vendored packages for unusually large test or benchmark files that don't need to be published to crates.io and submit -a pull request upstream to ignore those files when publishing.""".format( - size=cumulative_added_size - ), +a pull request upstream to ignore those files when publishing.""", ) if "MOZ_AUTOMATION" in os.environ: changed = self.repository.get_changed_files(mode="staged") diff --git a/python/mozbuild/mozpack/archive.py b/python/mozbuild/mozpack/archive.py index 89bf14b1795c..9d08de388bfb 100644 --- a/python/mozbuild/mozpack/archive.py +++ b/python/mozbuild/mozpack/archive.py @@ -118,7 +118,7 @@ def create_tar_gz_from_files(fp, files, filename=None, compresslevel=9): create_tar_from_files(gf, files) -class _BZ2Proxy(object): +class _BZ2Proxy: """File object that proxies writes to a bz2 compressor.""" def __init__(self, fp, compresslevel=9): diff --git a/python/mozbuild/mozpack/chrome/flags.py b/python/mozbuild/mozpack/chrome/flags.py index bd419b7875a7..671b055d8947 100644 --- a/python/mozbuild/mozpack/chrome/flags.py +++ b/python/mozbuild/mozpack/chrome/flags.py @@ -10,7 +10,7 @@ from packaging.version import Version from mozpack.errors import errors -class Flag(object): +class Flag: """ Class for flags in manifest entries in the form: "flag" (same as "flag=true") @@ -67,7 +67,7 @@ class Flag(object): return str(self) == other -class StringFlag(object): +class StringFlag: """ Class for string flags in manifest entries in the form: "flag=string" @@ -135,7 +135,7 @@ class StringFlag(object): return str(self) == other -class VersionFlag(object): +class VersionFlag: """ Class for version flags in manifest entries in the form: "flag=version" diff --git a/python/mozbuild/mozpack/chrome/manifest.py b/python/mozbuild/mozpack/chrome/manifest.py index db86d4c8aef0..322eae6930f5 100644 --- a/python/mozbuild/mozpack/chrome/manifest.py +++ b/python/mozbuild/mozpack/chrome/manifest.py @@ -13,7 +13,7 @@ from mozpack.chrome.flags import Flags from mozpack.errors import errors -class ManifestEntry(object): +class ManifestEntry: """ Base class for all manifest entry types. Subclasses may define the following class or member variables: diff --git a/python/mozbuild/mozpack/copier.py b/python/mozbuild/mozpack/copier.py index 2bf35afe5fc2..eeabf7f539b3 100644 --- a/python/mozbuild/mozpack/copier.py +++ b/python/mozbuild/mozpack/copier.py @@ -14,7 +14,7 @@ from mozpack.errors import errors from mozpack.files import BaseFile, Dest -class FileRegistry(object): +class FileRegistry: """ Generic container to keep track of a set of BaseFile instances. It preserves the order under which the files are added, but doesn't keep @@ -173,7 +173,7 @@ class FileRegistry(object): return dict(tree) -class FileRegistrySubtree(object): +class FileRegistrySubtree: """A proxy class to give access to a subtree of an existing FileRegistry. Note this doesn't implement the whole FileRegistry interface.""" @@ -222,7 +222,7 @@ class FileRegistrySubtree(object): yield mozpath.relpath(p, self._base), f -class FileCopyResult(object): +class FileCopyResult: """Represents results of a FileCopier.copy operation.""" def __init__(self): diff --git a/python/mozbuild/mozpack/dmg.py b/python/mozbuild/mozpack/dmg.py index c2728d1e0eb2..f1dfe893528d 100644 --- a/python/mozbuild/mozpack/dmg.py +++ b/python/mozbuild/mozpack/dmg.py @@ -57,9 +57,9 @@ def generate_hfs_file( [ "dd", "if=/dev/zero", - "of={}".format(hfs), + f"of={hfs}", "bs=1M", - "count={}".format(size), + f"count={size}", ] ) subprocess.check_call([mkfshfs_tool, "-v", volume_name, hfs]) diff --git a/python/mozbuild/mozpack/errors.py b/python/mozbuild/mozpack/errors.py index 25c0e8549ca0..2872ce2529fd 100644 --- a/python/mozbuild/mozpack/errors.py +++ b/python/mozbuild/mozpack/errors.py @@ -14,7 +14,7 @@ class AccumulatedErrors(Exception): """Exception type raised from errors.accumulate()""" -class ErrorCollector(object): +class ErrorCollector: """ Error handling/logging class. A global instance, errors, is provided for convenience. diff --git a/python/mozbuild/mozpack/files.py b/python/mozbuild/mozpack/files.py index eda3c0fa1e07..98ceabd4b5b3 100644 --- a/python/mozbuild/mozpack/files.py +++ b/python/mozbuild/mozpack/files.py @@ -65,7 +65,7 @@ def _open(path, mode="r"): return open(path, mode) -class Dest(object): +class Dest: """ Helper interface for BaseFile.copy. The interface works as follows: - read() and write() can be used to sequentially read/write from the underlying file. @@ -105,7 +105,7 @@ class Dest(object): self.file = None -class BaseFile(object): +class BaseFile: """ Base interface and helper for file copying. Derived class may implement their own copy function, or rely on BaseFile.copy using the open() member @@ -805,7 +805,7 @@ class MinifiedJavaScript(BaseFile): return output -class BaseFinder(object): +class BaseFinder: def __init__( self, base, minify=False, minify_js=False, minify_js_verify_command=None ): diff --git a/python/mozbuild/mozpack/macpkg.py b/python/mozbuild/mozpack/macpkg.py index 197f91d4814d..f4cd5062eda9 100644 --- a/python/mozbuild/mozpack/macpkg.py +++ b/python/mozbuild/mozpack/macpkg.py @@ -17,7 +17,7 @@ from collections import deque, namedtuple from xml.etree.ElementTree import XML -class ZlibFile(object): +class ZlibFile: def __init__(self, fileobj): self.fileobj = fileobj self.decompressor = zlib.decompressobj() @@ -97,7 +97,7 @@ def unxar(fileobj): yield filename, content -class Pbzx(object): +class Pbzx: def __init__(self, fileobj): magic = fileobj.read(4) if magic != b"pbzx": @@ -155,7 +155,7 @@ class Pbzx(object): return result -class Take(object): +class Take: """ File object wrapper that allows to read at most a certain length. """ diff --git a/python/mozbuild/mozpack/manifests.py b/python/mozbuild/mozpack/manifests.py index 2df6c729eaf0..62b5d6f6c721 100644 --- a/python/mozbuild/mozpack/manifests.py +++ b/python/mozbuild/mozpack/manifests.py @@ -43,7 +43,7 @@ class UnreadableInstallManifest(Exception): """Raised when an invalid install manifest is parsed.""" -class InstallManifest(object): +class InstallManifest: """Describes actions to be used with a copier.FileCopier instance. This class facilitates serialization and deserialization of data used to diff --git a/python/mozbuild/mozpack/mozjar.py b/python/mozbuild/mozpack/mozjar.py index 0d05b1f0423e..c323aab1777e 100644 --- a/python/mozbuild/mozpack/mozjar.py +++ b/python/mozbuild/mozpack/mozjar.py @@ -27,7 +27,7 @@ class JarWriterError(Exception): """Error type for Jar writer errors.""" -class JarStruct(object): +class JarStruct: """ Helper used to define ZIP archive raw data structures. Data structures handled by this helper all start with a magic number, defined in @@ -270,7 +270,7 @@ class JarLocalFileHeader(JarStruct): ) -class JarFileReader(object): +class JarFileReader: """ File-like class for use by JarReader to give access to individual files within a Jar archive. @@ -364,7 +364,7 @@ class JarFileReader(object): return self._uncompressed_data -class JarReader(object): +class JarReader: """ Class with methods to read Jar files. Can open standard jar files as well as Mozilla jar files (see further details in the JarWriter documentation). @@ -496,7 +496,7 @@ class JarReader(object): return name in self.entries -class JarWriter(object): +class JarWriter: """ Class with methods to write Jar files. Can write more-or-less standard jar archives as well as jar archives optimized for Gecko. See the documentation @@ -711,7 +711,7 @@ class JarWriter(object): self._contents = new_contents -class Deflater(object): +class Deflater: """ File-like interface to zlib compression. The data is actually not compressed unless the compressed form is smaller than the uncompressed @@ -832,7 +832,7 @@ class JarLog(dict): def __init__(self, file=None, fileobj=None): if not fileobj: - fileobj = open(file, "r") + fileobj = open(file) for line in fileobj: jar, path = line.strip().split(None, 1) if not jar or not path: diff --git a/python/mozbuild/mozpack/packager/__init__.py b/python/mozbuild/mozpack/packager/__init__.py index 96750d34ade1..a5326b09a7b5 100644 --- a/python/mozbuild/mozpack/packager/__init__.py +++ b/python/mozbuild/mozpack/packager/__init__.py @@ -23,7 +23,7 @@ from mozpack.chrome.manifest import ( from mozpack.errors import errors -class Component(object): +class Component: """ Class that represents a component in a package manifest. """ @@ -129,7 +129,7 @@ class Component(object): return Component(name, destdir=destdir) -class PackageManifestParser(object): +class PackageManifestParser: """ Class for parsing of a package manifest, after preprocessing. @@ -174,7 +174,7 @@ class PackageManifestParser(object): self._sink.add(self._component, str) -class PreprocessorOutputWrapper(object): +class PreprocessorOutputWrapper: """ File-like helper to handle the preprocessor output and send it to a parser. The parser's handle_line method is called in the relevant errors.context. @@ -231,7 +231,7 @@ class CallDeque(deque): function(*args) -class SimplePackager(object): +class SimplePackager: """ Helper used to translate and buffer instructions from the SimpleManifestSink to a formatter. Formatters expect some information to be @@ -378,7 +378,7 @@ class SimplePackager(object): self._file_queue.execute() -class SimpleManifestSink(object): +class SimpleManifestSink: """ Parser sink for "simple" package manifests. Simple package manifests use the format described in the PackageManifestParser documentation, but don't diff --git a/python/mozbuild/mozpack/packager/formats.py b/python/mozbuild/mozpack/packager/formats.py index 2926f98ce09c..94882d7b34cf 100644 --- a/python/mozbuild/mozpack/packager/formats.py +++ b/python/mozbuild/mozpack/packager/formats.py @@ -58,7 +58,7 @@ data. """ -class PiecemealFormatter(object): +class PiecemealFormatter: """ Generic formatter that dispatches across different sub-formatters according to paths. @@ -121,7 +121,7 @@ class FlatFormatter(PiecemealFormatter): ) -class FlatSubFormatter(object): +class FlatSubFormatter: """ Sub-formatter for the flat package format. """ diff --git a/python/mozbuild/mozpack/packager/l10n.py b/python/mozbuild/mozpack/packager/l10n.py index c62b37e1789a..3a029f2f83e9 100644 --- a/python/mozbuild/mozpack/packager/l10n.py +++ b/python/mozbuild/mozpack/packager/l10n.py @@ -30,12 +30,12 @@ from mozpack.packager.formats import FlatFormatter, JarFormatter, OmniJarFormatt from mozpack.packager.unpack import UnpackFinder -class LocaleManifestFinder(object): +class LocaleManifestFinder: def __init__(self, finder): entries = self.entries = [] bases = self.bases = [] - class MockFormatter(object): + class MockFormatter: def add_interfaces(self, path, content): pass @@ -54,7 +54,7 @@ class LocaleManifestFinder(object): # Those type of entries are used by language packs to work as addons, # but are not necessary for the purpose of l10n repacking. So we wrap # the finder in order to remove those entries. - class WrapFinder(object): + class WrapFinder: def __init__(self, finder): self._finder = finder @@ -80,7 +80,7 @@ class LocaleManifestFinder(object): ) -class L10NRepackFormatterMixin(object): +class L10NRepackFormatterMixin: def __init__(self, *args, **kwargs): super(L10NRepackFormatterMixin, self).__init__(*args, **kwargs) self._dictionaries = {} diff --git a/python/mozbuild/mozpack/path.py b/python/mozbuild/mozpack/path.py index 3e5af0a06b27..bc17acb748ec 100644 --- a/python/mozbuild/mozpack/path.py +++ b/python/mozbuild/mozpack/path.py @@ -216,7 +216,7 @@ def readlink(path): FILE_FLAG_BACKUP_SEMANTICS, 0, ) - assert handle != 1, "Failed getting a handle to: {}".format(path) + assert handle != 1, f"Failed getting a handle to: {path}" MAX_PATH = 260 @@ -233,7 +233,7 @@ def readlink(path): FILE_NAME_NORMALIZED = 0x0 rv = GetFinalPathNameByHandleW(handle, buf, MAX_PATH, FILE_NAME_NORMALIZED) - assert rv != 0 and rv <= MAX_PATH, "Failed getting final path for: {}".format(path) + assert rv != 0 and rv <= MAX_PATH, f"Failed getting final path for: {path}" CloseHandle = ctypes.windll.kernel32.CloseHandle CloseHandle.argtypes = [ctypes.wintypes.HANDLE] diff --git a/python/mozbuild/mozpack/test/test_errors.py b/python/mozbuild/mozpack/test/test_errors.py index 411b1b54c3b1..5cc4bed81877 100644 --- a/python/mozbuild/mozpack/test/test_errors.py +++ b/python/mozbuild/mozpack/test/test_errors.py @@ -11,7 +11,7 @@ import six from mozpack.errors import AccumulatedErrors, ErrorMessage, errors -class TestErrors(object): +class TestErrors: def setUp(self): errors.out = six.moves.cStringIO() errors.ignore_errors(False) diff --git a/python/mozbuild/mozpack/test/test_files.py b/python/mozbuild/mozpack/test/test_files.py index 41ed1d7ea5df..0975a6f0383a 100644 --- a/python/mozbuild/mozpack/test/test_files.py +++ b/python/mozbuild/mozpack/test/test_files.py @@ -281,7 +281,7 @@ class TestAbsoluteSymlinkFile(TestWithTmpDir): def test_symlink_file(self): source = self.tmppath("test_path") - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("Hello world") s = AbsoluteSymlinkFile(source) @@ -301,7 +301,7 @@ class TestAbsoluteSymlinkFile(TestWithTmpDir): # If symlinks are supported, an existing file should be replaced by a # symlink. source = self.tmppath("test_path") - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("source") dest = self.tmppath("dest") @@ -368,7 +368,7 @@ class TestHardlinkFile(TestWithTmpDir): def test_hardlink_file(self): source = self.tmppath("test_path") - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("Hello world") s = HardlinkFile(source) @@ -390,7 +390,7 @@ class TestHardlinkFile(TestWithTmpDir): # If hardlink are supported, an existing file should be replaced by a # symlink. source = self.tmppath("test_path") - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("source") dest = self.tmppath("dest") @@ -932,7 +932,7 @@ class TestMinifiedJavaScript(TestWithTmpDir): self.assertEqual(mini_lines, orig_f.open().readlines()) -class MatchTestTemplate(object): +class MatchTestTemplate: def prepare_match_test(self, with_dotfiles=False): self.add("bar") self.add("foo/bar") diff --git a/python/mozbuild/mozpack/test/test_manifests.py b/python/mozbuild/mozpack/test/test_manifests.py index a5db53b58ce4..3ec041e40871 100644 --- a/python/mozbuild/mozpack/test/test_manifests.py +++ b/python/mozbuild/mozpack/test/test_manifests.py @@ -18,7 +18,7 @@ class TestInstallManifest(TestWithTmpDir): def test_malformed(self): f = self.tmppath("manifest") - open(f, "wt").write("junk\n") + open(f, "w").write("junk\n") with self.assertRaises(UnreadableInstallManifest): InstallManifest(f) @@ -91,7 +91,7 @@ class TestInstallManifest(TestWithTmpDir): m.write(path=p) self.assertTrue(os.path.isfile(p)) - with open(p, "r") as fh: + with open(p) as fh: c = fh.read() self.assertEqual(c.count("\n"), 9) @@ -106,7 +106,7 @@ class TestInstallManifest(TestWithTmpDir): p2 = self.tmppath("m2") m2.write(path=p2) - with open(p2, "r") as fh: + with open(p2) as fh: c2 = fh.read() self.assertEqual(c, c2) @@ -186,13 +186,13 @@ class TestInstallManifest(TestWithTmpDir): with open(to_delete, "a"): pass - with open(self.tmppath("s_source"), "wt") as fh: + with open(self.tmppath("s_source"), "w") as fh: fh.write("symlink!") - with open(self.tmppath("c_source"), "wt") as fh: + with open(self.tmppath("c_source"), "w") as fh: fh.write("copy!") - with open(self.tmppath("p_source"), "wt") as fh: + with open(self.tmppath("p_source"), "w") as fh: fh.write("#define FOO 1\npreprocess!") with open(self.tmppath("dest/e_dest"), "a"): @@ -214,13 +214,13 @@ class TestInstallManifest(TestWithTmpDir): self.assertTrue(os.path.exists(self.tmppath("dest/content"))) self.assertFalse(os.path.exists(to_delete)) - with open(self.tmppath("dest/s_dest"), "rt") as fh: + with open(self.tmppath("dest/s_dest")) as fh: self.assertEqual(fh.read(), "symlink!") - with open(self.tmppath("dest/c_dest"), "rt") as fh: + with open(self.tmppath("dest/c_dest")) as fh: self.assertEqual(fh.read(), "copy!") - with open(self.tmppath("dest/p_dest"), "rt") as fh: + with open(self.tmppath("dest/p_dest")) as fh: self.assertEqual(fh.read(), "preprocess!") self.assertEqual( @@ -243,12 +243,12 @@ class TestInstallManifest(TestWithTmpDir): dest = self.tmppath("dest") include = self.tmppath("p_incl") - with open(include, "wt") as fh: + with open(include, "w") as fh: fh.write("#define INCL\n") time = os.path.getmtime(include) - 3 os.utime(include, (time, time)) - with open(self.tmppath("p_source"), "wt") as fh: + with open(self.tmppath("p_source"), "w") as fh: fh.write("#ifdef FOO\n#if BAZ == QUX\nPASS1\n#endif\n#endif\n") fh.write("#ifdef DEPTEST\nPASS2\n#endif\n") fh.write("#include p_incl\n#ifdef INCLTEST\nPASS3\n#endif\n") @@ -270,7 +270,7 @@ class TestInstallManifest(TestWithTmpDir): self.assertTrue(os.path.exists(self.tmppath("dest/p_dest"))) - with open(self.tmppath("dest/p_dest"), "rt") as fh: + with open(self.tmppath("dest/p_dest")) as fh: self.assertEqual(fh.read(), "PASS1\n") # Create a second manifest with the preprocessed file, then apply it. @@ -300,7 +300,7 @@ class TestInstallManifest(TestWithTmpDir): m2.populate_registry(c) self.assertTrue(c.copy(dest)) - with open(self.tmppath("dest/p_dest"), "rt") as fh: + with open(self.tmppath("dest/p_dest")) as fh: self.assertEqual(fh.read(), "PASS2\n") # Set the time on the manifest back, so it won't be picked up as @@ -310,7 +310,7 @@ class TestInstallManifest(TestWithTmpDir): # Update the contents of a file included by the source file. This should # cause the destination to be regenerated. - with open(include, "wt") as fh: + with open(include, "w") as fh: fh.write("#define INCLTEST\n") time = os.path.getmtime(include) - 1 @@ -319,7 +319,7 @@ class TestInstallManifest(TestWithTmpDir): m2.populate_registry(c) self.assertTrue(c.copy(dest)) - with open(self.tmppath("dest/p_dest"), "rt") as fh: + with open(self.tmppath("dest/p_dest")) as fh: self.assertEqual(fh.read(), "PASS2\nPASS3\n") def test_preprocessor_dependencies(self): @@ -331,12 +331,12 @@ class TestInstallManifest(TestWithTmpDir): include = self.tmppath("p_incl") os.mkdir(dest) - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("#define SRC\nSOURCE\n") time = os.path.getmtime(source) - 3 os.utime(source, (time, time)) - with open(include, "wt") as fh: + with open(include, "w") as fh: fh.write("INCLUDE\n") time = os.path.getmtime(source) - 3 os.utime(include, (time, time)) @@ -356,11 +356,11 @@ class TestInstallManifest(TestWithTmpDir): m.populate_registry(c) self.assertTrue(c.copy(dest)) - with open(destfile, "rt") as fh: + with open(destfile) as fh: self.assertEqual(fh.read(), "SOURCE\n") # Next, modify the source to #INCLUDE another file. - with open(source, "wt") as fh: + with open(source, "w") as fh: fh.write("SOURCE\n#include p_incl\n") time = os.path.getmtime(source) - 1 os.utime(destfile, (time, time)) @@ -372,7 +372,7 @@ class TestInstallManifest(TestWithTmpDir): m.populate_registry(c) c.copy(dest) - with open(destfile, "rt") as fh: + with open(destfile) as fh: self.assertEqual(fh.read(), "SOURCE\nINCLUDE\n") # Set the time on the source file back, so it won't be picked up as @@ -381,7 +381,7 @@ class TestInstallManifest(TestWithTmpDir): os.utime(source, (time, time)) # Now, modify the include file (but not the original source). - with open(include, "wt") as fh: + with open(include, "w") as fh: fh.write("INCLUDE MODIFIED\n") time = os.path.getmtime(include) - 1 os.utime(destfile, (time, time)) @@ -393,7 +393,7 @@ class TestInstallManifest(TestWithTmpDir): m.populate_registry(c) c.copy(dest) - with open(destfile, "rt") as fh: + with open(destfile) as fh: self.assertEqual(fh.read(), "SOURCE\nINCLUDE MODIFIED\n") # ORing an InstallManifest should copy file dependencies diff --git a/python/mozbuild/mozpack/test/test_packager.py b/python/mozbuild/mozpack/test/test_packager.py index 266902ebb250..3b4c3d2d6e88 100644 --- a/python/mozbuild/mozpack/test/test_packager.py +++ b/python/mozbuild/mozpack/test/test_packager.py @@ -54,7 +54,7 @@ class TestPreprocessManifest(unittest.TestCase): ] def setUp(self): - class MockSink(object): + class MockSink: def __init__(self): self.log = [] @@ -98,7 +98,7 @@ class TestPreprocessManifest(unittest.TestCase): ) -class MockFinder(object): +class MockFinder: def __init__(self, files): self.files = files self.log = [] @@ -113,7 +113,7 @@ class MockFinder(object): return self.find("") -class MockFormatter(object): +class MockFormatter: def __init__(self): self.log = [] @@ -540,7 +540,7 @@ class TestSimpleManifestSink(unittest.TestCase): class TestCallDeque(unittest.TestCase): def test_call_deque(self): - class Logger(object): + class Logger: def __init__(self): self._log = [] diff --git a/python/mozbuild/mozpack/test/test_unify.py b/python/mozbuild/mozpack/test/test_unify.py index b2c3073f0382..a3c79ec47c5c 100644 --- a/python/mozbuild/mozpack/test/test_unify.py +++ b/python/mozbuild/mozpack/test/test_unify.py @@ -230,7 +230,7 @@ class TestUnifiedBuildFinder(TestUnified): # Now create the files from the above table and compare results = [] for emid, (rdf_a, rdf_b, result) in enumerate(testcases): - filename = "ext/id{0}/install.rdf".format(emid) + filename = f"ext/id{emid}/install.rdf" self.create_one("a", filename, rdf_a) self.create_one("b", filename, rdf_b) results.append((filename, result)) diff --git a/python/mozlint/mozlint/cli.py b/python/mozlint/mozlint/cli.py index 21d6d878a4af..ceaa1e866496 100644 --- a/python/mozlint/mozlint/cli.py +++ b/python/mozlint/mozlint/cli.py @@ -279,15 +279,11 @@ class MozlintParser(ArgumentParser): fmt_dir = os.path.dirname(path) if not os.access(fmt_dir, os.W_OK | os.X_OK): self.error( - "the following directory is not writable: {}".format( - fmt_dir - ) + f"the following directory is not writable: {fmt_dir}" ) if fmt not in all_formatters.keys(): - self.error( - "the following formatter is not available: {}".format(fmt) - ) + self.error(f"the following formatter is not available: {fmt}") formats.append((fmt, path)) args.formats = formats diff --git a/python/mozlint/mozlint/errors.py b/python/mozlint/mozlint/errors.py index 4b36f00f69ab..cb4ed587140a 100644 --- a/python/mozlint/mozlint/errors.py +++ b/python/mozlint/mozlint/errors.py @@ -9,7 +9,7 @@ class LintException(Exception): class LinterNotFound(LintException): def __init__(self, path): - LintException.__init__(self, "Could not find lint file '{}'".format(path)) + LintException.__init__(self, f"Could not find lint file '{path}'") class NoValidLinter(LintException): @@ -22,7 +22,7 @@ class NoValidLinter(LintException): class LinterParseError(LintException): def __init__(self, path, message): - LintException.__init__(self, "{}: {}".format(path, message)) + LintException.__init__(self, f"{path}: {message}") class LintersNotConfigured(LintException): diff --git a/python/mozlint/mozlint/formatters/__init__.py b/python/mozlint/mozlint/formatters/__init__.py index e50616216fc2..3f652b748942 100644 --- a/python/mozlint/mozlint/formatters/__init__.py +++ b/python/mozlint/mozlint/formatters/__init__.py @@ -12,7 +12,7 @@ from .treeherder import TreeherderFormatter from .unix import UnixFormatter -class JSONFormatter(object): +class JSONFormatter: def __call__(self, result): return json.dumps(result.issues, cls=IssueEncoder) diff --git a/python/mozlint/mozlint/formatters/compact.py b/python/mozlint/mozlint/formatters/compact.py index 54ee1942151d..388441e54c99 100644 --- a/python/mozlint/mozlint/formatters/compact.py +++ b/python/mozlint/mozlint/formatters/compact.py @@ -7,7 +7,7 @@ import attr from ..result import Issue -class CompactFormatter(object): +class CompactFormatter: """Formatter for compact output. This formatter prints one error per line, mimicking the diff --git a/python/mozlint/mozlint/formatters/stylish.py b/python/mozlint/mozlint/formatters/stylish.py index 1988d07c1dc7..7a4b12de282d 100644 --- a/python/mozlint/mozlint/formatters/stylish.py +++ b/python/mozlint/mozlint/formatters/stylish.py @@ -8,7 +8,7 @@ from ..result import Issue from ..util.string import pluralize -class StylishFormatter(object): +class StylishFormatter: """Formatter based on the eslint default.""" _indent_ = " " @@ -112,7 +112,7 @@ class StylishFormatter(object): "lineno": str(err.lineno).rjust(self.max_lineno), "column": col, "level": err.level.ljust(self.max_level), - "rule": "{} ".format(err.rule) if err.rule else "", + "rule": f"{err.rule} " if err.rule else "", "linter": err.linter.lower(), "message": err.message.ljust(self.max_message), "diff": self._get_colored_diff(err.diff).ljust(self.max_message), @@ -146,7 +146,7 @@ class StylishFormatter(object): failure=( ", {}".format(pluralize("failure", len(failed))) if failed else "" ), - fixed="{} fixed".format(num_fixed), + fixed=f"{num_fixed} fixed", ) ) diff --git a/python/mozlint/mozlint/formatters/summary.py b/python/mozlint/mozlint/formatters/summary.py index e6ecf375080b..a74727eb0e19 100644 --- a/python/mozlint/mozlint/formatters/summary.py +++ b/python/mozlint/mozlint/formatters/summary.py @@ -10,7 +10,7 @@ import mozpack.path as mozpath from ..util.string import pluralize -class SummaryFormatter(object): +class SummaryFormatter: def __init__(self, depth=None): self.depth = depth or int(os.environ.get("MOZLINT_SUMMARY_DEPTH", 1)) diff --git a/python/mozlint/mozlint/formatters/treeherder.py b/python/mozlint/mozlint/formatters/treeherder.py index 66c7c59eee09..372e1add4002 100644 --- a/python/mozlint/mozlint/formatters/treeherder.py +++ b/python/mozlint/mozlint/formatters/treeherder.py @@ -7,7 +7,7 @@ import attr from ..result import Issue -class TreeherderFormatter(object): +class TreeherderFormatter: """Formatter for treeherder friendly output. This formatter looks ugly, but prints output such that diff --git a/python/mozlint/mozlint/formatters/unix.py b/python/mozlint/mozlint/formatters/unix.py index ae096f3e2ebc..972b46fa0e98 100644 --- a/python/mozlint/mozlint/formatters/unix.py +++ b/python/mozlint/mozlint/formatters/unix.py @@ -7,7 +7,7 @@ import attr from ..result import Issue -class UnixFormatter(object): +class UnixFormatter: """Formatter that respects Unix output conventions frequently employed by preprocessors and compilers. The format is `:[:]: : `. diff --git a/python/mozlint/mozlint/parser.py b/python/mozlint/mozlint/parser.py index 213af88b4bba..b215440374d5 100644 --- a/python/mozlint/mozlint/parser.py +++ b/python/mozlint/mozlint/parser.py @@ -12,7 +12,7 @@ from .types import supported_types GLOBAL_SUPPORT_FILES = [] -class Parser(object): +class Parser: """Reads and validates lint configuration files.""" required_attributes = ( @@ -54,7 +54,7 @@ class Parser(object): ): raise LinterParseError( relpath, - "The {} directive must be a " "list of strings!".format(attr), + f"The {attr} directive must be a " "list of strings!", ) invalid_paths = set() for path in linter[attr]: @@ -63,7 +63,7 @@ class Parser(object): raise LinterParseError( relpath, "Paths in the include directive cannot " - "contain globs:\n {}".format(path), + f"contain globs:\n {path}", ) continue diff --git a/python/mozlint/mozlint/pathutils.py b/python/mozlint/mozlint/pathutils.py index 2d41fe9945e7..066d1b4fea85 100644 --- a/python/mozlint/mozlint/pathutils.py +++ b/python/mozlint/mozlint/pathutils.py @@ -11,7 +11,7 @@ from mozpack.files import FileFinder _is_windows = sys.platform == "cygwin" or (sys.platform == "win32" and os.sep == "\\") -class FilterPath(object): +class FilterPath: """Helper class to make comparing and matching file paths easier.""" def __init__(self, path): @@ -248,9 +248,7 @@ def findobject(path): return mod. """ if path.count(":") != 1: - raise ValueError( - 'python path {!r} does not have the form "module:object"'.format(path) - ) + raise ValueError(f'python path {path!r} does not have the form "module:object"') modulepath, objectpath = path.split(":") obj = __import__(modulepath) @@ -317,7 +315,7 @@ def expand_exclusions(paths, config, root): # return files that are passed explicitly and whose extensions are in the # exclusion set. If we don't put it in the ignore set, the FileFinder # would return files in (sub)directories passed to us. - base_ignore = ["**/*.{}".format(ext) for ext in exclude_extensions] + base_ignore = [f"**/*.{ext}" for ext in exclude_extensions] exclude += base_ignore for path in paths: path = mozpath.normsep(path) @@ -350,7 +348,7 @@ def expand_exclusions(paths, config, root): finder = FileFinder(path, ignore=ignore, find_dotfiles=find_dotfiles) if extensions: for ext in extensions: - for p, f in finder.find("**/*.{}".format(ext)): + for p, f in finder.find(f"**/*.{ext}"): yield os.path.join(path, p) else: for p, f in finder.find("**/*.*"): diff --git a/python/mozlint/mozlint/result.py b/python/mozlint/mozlint/result.py index 1137aafe2228..0a6d9301dce3 100644 --- a/python/mozlint/mozlint/result.py +++ b/python/mozlint/mozlint/result.py @@ -11,7 +11,7 @@ import attr import mozpack.path as mozpath -class ResultSummary(object): +class ResultSummary: """Represents overall result state from an entire lint run.""" root = None @@ -79,7 +79,7 @@ class ResultSummary(object): @attr.s(slots=True, kw_only=True) -class Issue(object): +class Issue: """Represents a single lint issue and its related metadata. :param linter: name of the linter that flagged this error diff --git a/python/mozlint/mozlint/roller.py b/python/mozlint/mozlint/roller.py index cad8225fc464..478d3f61b43d 100644 --- a/python/mozlint/mozlint/roller.py +++ b/python/mozlint/mozlint/roller.py @@ -89,7 +89,7 @@ def _run_worker(config, paths, **lintargs): return result finally: end_time = time.monotonic() - log.debug("Finished in {:.2f} seconds".format(end_time - start_time)) + log.debug(f"Finished in {end_time - start_time:.2f} seconds") sys.stdout.flush() if not isinstance(res, (list, tuple)): @@ -154,7 +154,7 @@ atexit.unregister(futures_atexit) atexit.register(wrap_futures_atexit) -class LintRoller(object): +class LintRoller: """Registers and runs linters. :param root: Path to which relative paths will be joined. If diff --git a/python/mozlint/mozlint/types.py b/python/mozlint/mozlint/types.py index 1b24abc3a659..944b30167316 100644 --- a/python/mozlint/mozlint/types.py +++ b/python/mozlint/mozlint/types.py @@ -15,7 +15,7 @@ from . import result from .pathutils import expand_exclusions, filterpaths, findobject -class BaseType(object): +class BaseType: """Abstract base class for all types of linters.""" __metaclass__ = ABCMeta @@ -86,7 +86,7 @@ class BaseType(object): if not config.get("extensions"): patterns = ["**"] else: - patterns = ["**/*.{}".format(e) for e in config["extensions"]] + patterns = [f"**/*.{e}" for e in config["extensions"]] exclude = [os.path.relpath(e, path) for e in config.get("exclude", [])] finder = FileFinder(path, ignore=exclude) @@ -120,7 +120,7 @@ class LineType(BaseType): return self._lint_dir(path, config, **lintargs) payload = config["payload"] - with open(path, "r", errors="replace") as fh: + with open(path, errors="replace") as fh: lines = fh.readlines() errors = [] diff --git a/python/mozlint/test/linters/external.py b/python/mozlint/test/linters/external.py index 9c2e58909dc5..0d66591462f1 100644 --- a/python/mozlint/test/linters/external.py +++ b/python/mozlint/test/linters/external.py @@ -23,7 +23,7 @@ def external(files, config, **lintargs): if os.path.isdir(path): continue - with open(path, "r") as fh: + with open(path) as fh: for i, line in enumerate(fh.readlines()): if "foobar" in line: results.append( @@ -48,7 +48,7 @@ def structured(files, config, logger, **kwargs): if os.path.isdir(path): continue - with open(path, "r") as fh: + with open(path) as fh: for i, line in enumerate(fh.readlines()): if "foobar" in line: logger.lint_error( diff --git a/python/mozlint/test/test_pathutils.py b/python/mozlint/test/test_pathutils.py index c61dd7047af5..2a7ec0b9bd3b 100644 --- a/python/mozlint/test/test_pathutils.py +++ b/python/mozlint/test/test_pathutils.py @@ -224,7 +224,7 @@ def test_collapse(paths, expected): else: inputs.append(path) - print("inputs: {}".format(inputs)) + print(f"inputs: {inputs}") assert_paths(pathutils.collapse(inputs), expected) diff --git a/python/mozperftest/mozperftest/metrics/common.py b/python/mozperftest/mozperftest/metrics/common.py index 3598cd378a9c..6845ba1a03ef 100644 --- a/python/mozperftest/mozperftest/metrics/common.py +++ b/python/mozperftest/mozperftest/metrics/common.py @@ -50,7 +50,7 @@ COMMON_ARGS = { } -class MetricsStorage(object): +class MetricsStorage: """Holds data that is commonly used across all metrics layers. An instance of this class represents data for a given and output @@ -77,7 +77,7 @@ class MetricsStorage(object): # Expecting a single path or a directory p = Path(results) if not p.exists(): - self.logger.warning("Given path does not exist: {}".format(results)) + self.logger.warning(f"Given path does not exist: {results}") elif p.is_dir(): files = [f for f in p.glob("**/*.json") if not f.is_dir()] res.extend(self._parse_results(files)) @@ -166,7 +166,7 @@ class MetricsStorage(object): tfm = transformer if transformer is not None else data_info["transformer"] prefix = data_type if self.prefix: - prefix = "{}-{}".format(self.prefix, data_type) + prefix = f"{self.prefix}-{data_type}" # Primarily used to store the transformer used on the data # so that it can also be used for generating things diff --git a/python/mozperftest/mozperftest/metrics/notebook/constant.py b/python/mozperftest/mozperftest/metrics/notebook/constant.py index ca40d289d423..f2bb431ea1a3 100644 --- a/python/mozperftest/mozperftest/metrics/notebook/constant.py +++ b/python/mozperftest/mozperftest/metrics/notebook/constant.py @@ -8,7 +8,7 @@ from types import MappingProxyType from .transformer import get_transformers -class Constant(object): +class Constant: """A singleton class to store all constants.""" __instance = None diff --git a/python/mozperftest/mozperftest/metrics/notebook/perftestetl.py b/python/mozperftest/mozperftest/metrics/notebook/perftestetl.py index bd28d9be6d07..9517c3fe6c39 100644 --- a/python/mozperftest/mozperftest/metrics/notebook/perftestetl.py +++ b/python/mozperftest/mozperftest/metrics/notebook/perftestetl.py @@ -11,7 +11,7 @@ from .constant import Constant from .transformer import SimplePerfherderTransformer, Transformer, get_transformer -class PerftestETL(object): +class PerftestETL: """Controller class for the PerftestETL.""" def __init__( diff --git a/python/mozperftest/mozperftest/metrics/notebook/perftestnotebook.py b/python/mozperftest/mozperftest/metrics/notebook/perftestnotebook.py index 99c3766b42cb..f408976df9d5 100644 --- a/python/mozperftest/mozperftest/metrics/notebook/perftestnotebook.py +++ b/python/mozperftest/mozperftest/metrics/notebook/perftestnotebook.py @@ -8,7 +8,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer from .constant import Constant -class PerftestNotebook(object): +class PerftestNotebook: """Controller class for PerftestNotebook.""" def __init__(self, data, logger, prefix): diff --git a/python/mozperftest/mozperftest/metrics/notebook/transformer.py b/python/mozperftest/mozperftest/metrics/notebook/transformer.py index b4596d7ca6c8..3c4deab98fba 100644 --- a/python/mozperftest/mozperftest/metrics/notebook/transformer.py +++ b/python/mozperftest/mozperftest/metrics/notebook/transformer.py @@ -17,7 +17,7 @@ from mozperftest.runner import HERE from mozperftest.utils import load_class -class Transformer(object): +class Transformer: """Abstract class for data transformers.""" def __init__(self, files=None, custom_transformer=None, logger=None, prefix=None): diff --git a/python/mozperftest/mozperftest/metrics/perfherder.py b/python/mozperftest/mozperftest/metrics/perfherder.py index b1c25a42c198..491afc5d780a 100644 --- a/python/mozperftest/mozperftest/metrics/perfherder.py +++ b/python/mozperftest/mozperftest/metrics/perfherder.py @@ -156,8 +156,8 @@ class Perfherder(Layer): file = "perfherder-data.json" if prefix: - file = "{}-{}".format(prefix, file) - self.info("Writing perfherder results to {}".format(os.path.join(output, file))) + file = f"{prefix}-{file}" + self.info(f"Writing perfherder results to {os.path.join(output, file)}") # XXX "suites" key error occurs when using self.info so a print # is being done for now. @@ -297,7 +297,7 @@ class Perfherder(Layer): allvals.extend(reps) if len(reps) == 0: - self.warning("No replicates found for {}, skipping".format(measurement)) + self.warning(f"No replicates found for {measurement}, skipping") continue # Gather extra settings specified from within a metric specification diff --git a/python/mozperftest/mozperftest/system/android_perf_tuner.py b/python/mozperftest/mozperftest/system/android_perf_tuner.py index e33d98b5d081..d36b8c08ceb4 100644 --- a/python/mozperftest/mozperftest/system/android_perf_tuner.py +++ b/python/mozperftest/mozperftest/system/android_perf_tuner.py @@ -37,12 +37,12 @@ class PerformanceTuner: self.log.info("android device performance tuning complete") def _set_value_and_check_exitcode(self, file_name, value): - self.log.info("setting {} to {}".format(file_name, value)) + self.log.info(f"setting {file_name} to {value}") if self.device.shell_bool( " ".join(["echo", str(value), ">", str(file_name)]), timeout=self.timeout, ): - self.log.info("successfully set {} to {}".format(file_name, value)) + self.log.info(f"successfully set {file_name} to {value}") else: self.log.warning("command failed") @@ -99,9 +99,7 @@ class PerformanceTuner: ) self.log.info( - "CPU for device with ro.product.model '{}' unknown, not scaling_governor".format( - device_name - ) + f"CPU for device with ro.product.model '{device_name}' unknown, not scaling_governor" ) for key, value in commands.items(): @@ -124,9 +122,7 @@ class PerformanceTuner: ) self.log.info( - "GPU for device with ro.product.model '{}' unknown, not setting devfreq".format( - device_name - ) + f"GPU for device with ro.product.model '{device_name}' unknown, not setting devfreq" ) for key, value in commands.items(): diff --git a/python/mozperftest/mozperftest/system/proxy.py b/python/mozperftest/mozperftest/system/proxy.py index d0a8c7ff9704..713893652b1e 100644 --- a/python/mozperftest/mozperftest/system/proxy.py +++ b/python/mozperftest/mozperftest/system/proxy.py @@ -26,7 +26,7 @@ LOG = get_proxy_logger(component="proxy") HERE = os.path.dirname(__file__) -class OutputHandler(object): +class OutputHandler: def __init__(self): self.proc = None self.port = None diff --git a/python/mozperftest/mozperftest/test/browsertime/runner.py b/python/mozperftest/mozperftest/test/browsertime/runner.py index 798bd0972b52..832422932c6a 100644 --- a/python/mozperftest/mozperftest/test/browsertime/runner.py +++ b/python/mozperftest/mozperftest/test/browsertime/runner.py @@ -235,9 +235,7 @@ class BrowsertimeRunner(NodeRunner): expr = r"/tarball/[a-f0-9]{40}$" if not re.search(expr, install_url): raise ValueError( - "New upstream URL does not end with {}: '{}'".format( - expr[:-1], install_url - ) + f"New upstream URL does not end with {expr[:-1]}: '{install_url}'" ) with package_json_path.open() as f: @@ -357,7 +355,7 @@ class BrowsertimeRunner(NodeRunner): msg = msg.replace("{", "{{").replace("}", "}}") level = level.lower() if "error" in level: - self.error("Mozperftest failed to run: {}".format(msg), msg) + self.error(f"Mozperftest failed to run: {msg}", msg) elif "warning" in level: self.warning(msg) else: diff --git a/python/mozperftest/mozperftest/tests/test_binarysetup.py b/python/mozperftest/mozperftest/tests/test_binarysetup.py index 37e4434f1e22..54893857cf57 100644 --- a/python/mozperftest/mozperftest/tests/test_binarysetup.py +++ b/python/mozperftest/mozperftest/tests/test_binarysetup.py @@ -70,7 +70,7 @@ def test_binarysetup_desktop_chrome(mocked_subprocess): mach_cmd, metadata, env = get_running_env(**args) system = env.layers[SYSTEM] - mocked_subprocess.check_output.return_value = "/fake/path/chrome".encode() + mocked_subprocess.check_output.return_value = b"/fake/path/chrome" with system as layer, silence(system): layer(metadata) diff --git a/python/mozperftest/mozperftest/tests/test_shellscript.py b/python/mozperftest/mozperftest/tests/test_shellscript.py index 8db35d65d387..17d0279065af 100644 --- a/python/mozperftest/mozperftest/tests/test_shellscript.py +++ b/python/mozperftest/mozperftest/tests/test_shellscript.py @@ -26,15 +26,13 @@ def test_shell_script_metric_parsing(): runner = ShellScriptRunner(env, mach_cmd) line_handler = runner.line_handler_wrapper() - line_handler(mock.MagicMock(), "don't parse line".encode()) + line_handler(mock.MagicMock(), b"don't parse line") assert len(runner.metrics) == 0 line_handler( - mock.MagicMock(), 'perfMetrics: [{{"name": "metric1", "values": []}}]'.encode() - ) - line_handler( - mock.MagicMock(), 'perfMetrics: {{"name": "metric2", "values": [1]}}'.encode() + mock.MagicMock(), b'perfMetrics: [{{"name": "metric1", "values": []}}]' ) + line_handler(mock.MagicMock(), b'perfMetrics: {{"name": "metric2", "values": [1]}}') assert len(runner.metrics) == 2 parsed_metrics = runner.parse_metrics() diff --git a/python/mozperftest/mozperftest/tests/test_transformer.py b/python/mozperftest/mozperftest/tests/test_transformer.py index b5323eabe63a..c1d768e78e9a 100644 --- a/python/mozperftest/mozperftest/tests/test_transformer.py +++ b/python/mozperftest/mozperftest/tests/test_transformer.py @@ -23,7 +23,7 @@ prefix = "PerftestNotebook" def test_init_failure(): - class TempClass(object): + class TempClass: def temp_fun(): return 1 diff --git a/python/mozrelease/mozrelease/buglist_creator.py b/python/mozrelease/mozrelease/buglist_creator.py index f70076a2f09c..ab6bdb4485ba 100644 --- a/python/mozrelease/mozrelease/buglist_creator.py +++ b/python/mozrelease/mozrelease/buglist_creator.py @@ -160,9 +160,7 @@ def get_previous_tag_version( def _invalid_tag_filter(tag): """Filters by product and removes incorrect major version + base, end releases""" - prod_major_version_re = r"^{product}_{major_version}".format( - product=product.upper(), major_version=current_version.major_number - ) + prod_major_version_re = rf"^{product.upper()}_{current_version.major_number}" return ( "BASE" not in tag @@ -196,12 +194,10 @@ def get_repo_by_version(version): elif version.is_release: return "https://hg.mozilla.org/releases/mozilla-release" elif version.is_esr: - return "https://hg.mozilla.org/releases/mozilla-esr{}".format( - version.major_number - ) + return f"https://hg.mozilla.org/releases/mozilla-esr{version.major_number}" else: raise Exception( - "Unsupported version type {}: {}".format(version.version_type.name, version) + f"Unsupported version type {version.version_type.name}: {version}" ) @@ -239,9 +235,7 @@ Task group: [{task_group_id}]({root_url}/tasks/groups/{task_group_id}) if product in {"firefox", "devedition"}: subject_prefix = "[desktop] " - subject = "{} Build of {} {} build {}".format( - subject_prefix, product, version, build_number - ) + subject = f"{subject_prefix} Build of {product} {version} build {build_number}" # use proxy if configured, otherwise local credentials from env vars if "TASKCLUSTER_PROXY_URL" in os.environ: diff --git a/python/mozrelease/mozrelease/partner_repack.py b/python/mozrelease/mozrelease/partner_repack.py index 80fa4ba686d2..9070fa91b966 100644 --- a/python/mozrelease/mozrelease/partner_repack.py +++ b/python/mozrelease/mozrelease/partner_repack.py @@ -326,7 +326,7 @@ def getBouncerProduct(partner, partner_distro): ) -class RepackBase(object): +class RepackBase: def __init__( self, build: str, diff --git a/python/mozrelease/mozrelease/paths.py b/python/mozrelease/mozrelease/paths.py index 29541732d508..df8907ec636c 100644 --- a/python/mozrelease/mozrelease/paths.py +++ b/python/mozrelease/mozrelease/paths.py @@ -20,10 +20,8 @@ def getCandidatesDir(product, version, buildNumber, protocol=None, server=None): assert server is not None, "server is required with protocol" product = product2ftp(product) - directory = "/{}/candidates/{}-candidates/build{}".format( - product, - str(version), - str(buildNumber), + directory = ( + f"/{product}/candidates/{str(version)}-candidates/build{str(buildNumber)}" ) if protocol: @@ -36,9 +34,9 @@ def getReleasesDir(product, version=None, protocol=None, server=None): if protocol: assert server is not None, "server is required with protocol" - directory = "/{}/releases".format(product) + directory = f"/{product}/releases" if version: - directory = "{}/{}".format(directory, version) + directory = f"{directory}/{version}" if protocol: return urlunsplit((protocol, server, directory, None, None)) diff --git a/python/mozrelease/mozrelease/scriptworker_canary.py b/python/mozrelease/mozrelease/scriptworker_canary.py index db991efdf3c4..dc60ccc0a628 100644 --- a/python/mozrelease/mozrelease/scriptworker_canary.py +++ b/python/mozrelease/mozrelease/scriptworker_canary.py @@ -82,10 +82,10 @@ def push_canary(scriptworkers, addresses, ssh_key_secret): for scriptworker in scriptworkers: worker_tasks = TASK_TYPES.get(scriptworker) if worker_tasks: - logger.info("Running tasks for {}: {}".format(scriptworker, worker_tasks)) + logger.info(f"Running tasks for {scriptworker}: {worker_tasks}") tasks.extend(worker_tasks) else: - logger.info("No tasks for {}.".format(scriptworker)) + logger.info(f"No tasks for {scriptworker}.") mach = Path(GECKO) / "mach" base_command = [str(mach), "try", "scriptworker", "--closed-tree", "--push-to-vcs"] @@ -93,9 +93,9 @@ def push_canary(scriptworkers, addresses, ssh_key_secret): base_command.extend( [ "--route", - "notify.email.{}.on-failed".format(address), + f"notify.email.{address}.on-failed", "--route", - "notify.email.{}.on-exception".format(address), + f"notify.email.{address}.on-exception", ] ) diff --git a/python/mozrelease/mozrelease/update_verify.py b/python/mozrelease/mozrelease/update_verify.py index 90b76299cc65..60123afe2e43 100644 --- a/python/mozrelease/mozrelease/update_verify.py +++ b/python/mozrelease/mozrelease/update_verify.py @@ -12,7 +12,7 @@ class UpdateVerifyError(Exception): pass -class UpdateVerifyConfig(object): +class UpdateVerifyConfig: comment_regex = re.compile("^#") key_write_order = ( "release", diff --git a/python/mozrelease/test/test_versions.py b/python/mozrelease/test/test_versions.py index eaf7d653dbc5..45dd94df5044 100644 --- a/python/mozrelease/test/test_versions.py +++ b/python/mozrelease/test/test_versions.py @@ -67,7 +67,7 @@ ALL_VERSIONS = [ # Keep this sorted @pytest.fixture( scope="function", params=range(len(ALL_VERSIONS) - 1), - ids=lambda x: "{}, {}".format(ALL_VERSIONS[x], ALL_VERSIONS[x + 1]), + ids=lambda x: f"{ALL_VERSIONS[x]}, {ALL_VERSIONS[x + 1]}", ) def comparable_versions(request): index = request.param diff --git a/python/mozterm/mozterm/terminal.py b/python/mozterm/mozterm/terminal.py index f03e19e4ba5a..a094a65f344f 100644 --- a/python/mozterm/mozterm/terminal.py +++ b/python/mozterm/mozterm/terminal.py @@ -6,7 +6,7 @@ import os import sys -class NullTerminal(object): +class NullTerminal: """Replacement for `blessed.Terminal()` that does no formatting.""" number_of_colors = 0 diff --git a/python/mozterm/mozterm/widgets.py b/python/mozterm/mozterm/widgets.py index 2cf5bf250cbc..7cc11d40c44f 100644 --- a/python/mozterm/mozterm/widgets.py +++ b/python/mozterm/mozterm/widgets.py @@ -7,7 +7,7 @@ from .terminal import Terminal DEFAULT = "\x1b(B\x1b[m" -class BaseWidget(object): +class BaseWidget: def __init__(self, terminal=None): self.term = terminal or Terminal() self.stream = self.term.stream diff --git a/python/mozterm/test/test_widgets.py b/python/mozterm/test/test_widgets.py index d6eb241b9440..04cb507acda3 100644 --- a/python/mozterm/test/test_widgets.py +++ b/python/mozterm/test/test_widgets.py @@ -20,7 +20,7 @@ def terminal(): try: term = Terminal(stream=StringIO(), force_styling=True, kind=kind) except blessed.curses.error: - pytest.skip("terminal '{}' not found".format(kind)) + pytest.skip(f"terminal '{kind}' not found") return term diff --git a/python/mozversioncontrol/mozversioncontrol/errors.py b/python/mozversioncontrol/mozversioncontrol/errors.py index fe798105d53e..6ee93bfa6c0f 100644 --- a/python/mozversioncontrol/mozversioncontrol/errors.py +++ b/python/mozversioncontrol/mozversioncontrol/errors.py @@ -20,7 +20,7 @@ class MissingVCSExtension(MissingVCSInfo): def __init__(self, ext): self.ext = ext - msg = "Could not detect required extension '{}'".format(self.ext) + msg = f"Could not detect required extension '{self.ext}'" super(MissingVCSExtension, self).__init__(msg) diff --git a/python/mozversioncontrol/mozversioncontrol/repo/base.py b/python/mozversioncontrol/mozversioncontrol/repo/base.py index ad8a238d0582..c78e34faeac3 100644 --- a/python/mozversioncontrol/mozversioncontrol/repo/base.py +++ b/python/mozversioncontrol/mozversioncontrol/repo/base.py @@ -32,7 +32,7 @@ def get_tool_path(tool: Optional[Union[str, Path]] = None): return str(path) -class Repository(object): +class Repository: """A class wrapping utility methods around version control repositories. This class is abstract and never instantiated. Obtain an instance by diff --git a/python/mozversioncontrol/mozversioncontrol/repo/git.py b/python/mozversioncontrol/mozversioncontrol/repo/git.py index 152142261180..7ba8e37f8d7f 100644 --- a/python/mozversioncontrol/mozversioncontrol/repo/git.py +++ b/python/mozversioncontrol/mozversioncontrol/repo/git.py @@ -133,7 +133,7 @@ class GitRepository(Repository): files = self._run( "log", "--name-only", - "--diff-filter={}".format(diff_filter.upper()), + f"--diff-filter={diff_filter.upper()}", "--oneline", "--topo-order", "--pretty=format:", diff --git a/python/mozversioncontrol/mozversioncontrol/repo/mercurial.py b/python/mozversioncontrol/mozversioncontrol/repo/mercurial.py index c4015e2909e7..882b0f4324d4 100644 --- a/python/mozversioncontrol/mozversioncontrol/repo/mercurial.py +++ b/python/mozversioncontrol/mozversioncontrol/repo/mercurial.py @@ -165,7 +165,7 @@ class HgRepository(Repository): if rev is None: # Use --no-status to print just the filename. df = self._format_diff_filter(diff_filter, for_status=True) - return self._run("status", "--no-status", "-{}".format(df)).splitlines() + return self._run("status", "--no-status", f"-{df}").splitlines() else: template = self._files_template(diff_filter) return self._run("log", "-r", rev, "-T", template).splitlines() diff --git a/python/mozversioncontrol/mozversioncontrol/repo/source.py b/python/mozversioncontrol/mozversioncontrol/repo/source.py index 59c1d5fbd238..6c27bbb2161d 100644 --- a/python/mozversioncontrol/mozversioncontrol/repo/source.py +++ b/python/mozversioncontrol/mozversioncontrol/repo/source.py @@ -70,7 +70,7 @@ class SrcRepository(Repository): list of the patterns to ignore """ ignore = [] - f = open(path + "/.gitignore", "r") + f = open(path + "/.gitignore") while True: line = f.readline() if not line: diff --git a/remote/mach_commands.py b/remote/mach_commands.py index ef264156e902..af5387c2c79c 100644 --- a/remote/mach_commands.py +++ b/remote/mach_commands.py @@ -87,7 +87,7 @@ def vendor_puppeteer(command_context, repository, commitish, install): "-a", "-f", "--prefix", - "{}/".format(puppeteer_dir), + f"{puppeteer_dir}/", worktree=tmpdir, ) @@ -234,7 +234,7 @@ def post_wait_proc(p, cmd=None, exit_on_fail=True): exit(p.returncode, msg) -class MochaOutputHandler(object): +class MochaOutputHandler: def __init__(self, logger, expected): self.hook_re = re.compile('"before\b?.*" hook|"after\b?.*" hook') @@ -296,7 +296,7 @@ class MochaOutputHandler(object): if "timeout" in test_err.lower(): status = "TIMEOUT" if test_name and test_path: - test_name = "{} ({})".format(test_name, os.path.basename(test_path)) + test_name = f"{test_name} ({os.path.basename(test_path)})" # mocha hook failures are not tracked in metadata if status != "PASS" and self.hook_re.search(test_name): self.logger.error("TEST-UNEXPECTED-ERROR %s" % (test_name,)) @@ -304,7 +304,7 @@ class MochaOutputHandler(object): if test_start: self.logger.test_start(test_name) return - expected_name = "[{}] {}".format(test_file_name, test_full_title) + expected_name = f"[{test_file_name}] {test_full_title}" expected_item = next( ( expectation @@ -332,8 +332,8 @@ class MochaOutputHandler(object): result_recorded = self.test_results.get(test_name) if result_recorded: self.logger.warning( - "Received a second status for {}: " - "first {}, now {}".format(test_name, result_recorded, status) + f"Received a second status for {test_name}: " + f"first {result_recorded}, now {status}" ) # mocha intermittently logs an additional test result after the # test has already timed out. Avoid recording this second status. @@ -359,13 +359,13 @@ class MochaOutputHandler(object): # tempfile.TemporaryDirectory missing from Python 2.7 -class TemporaryDirectory(object): +class TemporaryDirectory: def __init__(self): self.path = tempfile.mkdtemp() self._closed = False def __repr__(self): - return "<{} {!r}>".format(self.__class__.__name__, self.path) + return f"<{self.__class__.__name__} {self.path!r}>" def __enter__(self): return self.path @@ -484,7 +484,7 @@ class PuppeteerRunner(MozbuildObject): prefs = {} for k, v in params.get("extra_prefs", {}).items(): - print("Using extra preference: {}={}".format(k, v)) + print(f"Using extra preference: {k}={v}") prefs[k] = mozprofile.Preferences.cast(v) if prefs: @@ -691,7 +691,7 @@ def puppeteer_test( for s in extra_prefs or []: kv = s.split("=") if len(kv) != 2: - logger.error("syntax error in --setpref={}".format(s)) + logger.error(f"syntax error in --setpref={s}") exit(EX_USAGE) prefs[kv[0]] = kv[1].strip() @@ -699,7 +699,7 @@ def puppeteer_test( for s in extra_options or []: kv = s.split("=") if len(kv) != 2: - logger.error("syntax error in --setopt={}".format(s)) + logger.error(f"syntax error in --setopt={s}") exit(EX_USAGE) options[kv[0]] = kv[1].strip() @@ -790,5 +790,5 @@ def exit(code, error=None): traceback.print_exc() else: message = str(error).split("\n")[0].strip() - print("{}: {}".format(sys.argv[0], message), file=sys.stderr) + print(f"{sys.argv[0]}: {message}", file=sys.stderr) sys.exit(code) diff --git a/security/generate_mapfile.py b/security/generate_mapfile.py index 244f499f74c5..8064d0e366eb 100644 --- a/security/generate_mapfile.py +++ b/security/generate_mapfile.py @@ -26,7 +26,7 @@ def main(output, input): "GCC_USE_GNU_LD" ) - with open(input, "r", encoding="utf-8") as f: + with open(input, encoding="utf-8") as f: for line in f: line = line.rstrip() # On everything except MinGW, remove all lines containing ';-' diff --git a/security/manager/ssl/gen_cert_header.py b/security/manager/ssl/gen_cert_header.py index 5c15b15a84e2..d1fa552f6173 100644 --- a/security/manager/ssl/gen_cert_header.py +++ b/security/manager/ssl/gen_cert_header.py @@ -8,7 +8,7 @@ from pyasn1_modules import pem def read_certificate(filename): - with open(filename, "r") as f: + with open(filename) as f: try: return pem.readPemFromFile( f, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----" diff --git a/security/manager/tools/crtshToIdentifyingStruct/crtshToIdentifyingStruct.py b/security/manager/tools/crtshToIdentifyingStruct/crtshToIdentifyingStruct.py index 05e0842e2a45..4170e5d93385 100644 --- a/security/manager/tools/crtshToIdentifyingStruct/crtshToIdentifyingStruct.py +++ b/security/manager/tools/crtshToIdentifyingStruct/crtshToIdentifyingStruct.py @@ -29,11 +29,11 @@ assert sys.version_info >= (3, 2), "Requires Python 3.2 or later" def hex_string_for_struct(bytes): - return ["0x{:02X}".format(x) for x in bytes] + return [f"0x{x:02X}" for x in bytes] def hex_string_human_readable(bytes): - return ["{:02X}".format(x) for x in bytes] + return [f"{x:02X}" for x in bytes] def nameOIDtoString(oid): @@ -47,7 +47,7 @@ def nameOIDtoString(oid): return "O" if oid == NameOID.ORGANIZATIONAL_UNIT_NAME: return "OU" - raise Exception("Unknown OID: {}".format(oid)) + raise Exception(f"Unknown OID: {oid}") def print_block(pemData, identifierType="DN", crtshId=None): @@ -72,18 +72,15 @@ def print_block(pemData, identifierType="DN", crtshId=None): fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256())) - dn_parts = [ - "/{id}={value}".format(id=nameOIDtoString(part.oid), value=part.value) - for part in cert.subject - ] + dn_parts = [f"/{nameOIDtoString(part.oid)}={part.value}" for part in cert.subject] distinguished_name = "".join(dn_parts) - print("// {dn}".format(dn=distinguished_name)) + print(f"// {distinguished_name}") print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16])) print("// " + ":".join(fingerprint[16:])) if crtshId: - print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})".format(crtsh=crtshId)) - print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) + "{") + print(f"// https://crt.sh/?id={crtshId} (crt.sh ID={crtshId})") + print(f"static const uint8_t {block_name}[{len(octets)}] = " + "{") while len(octets) > 0: print(" " + ", ".join(octets[:13]) + ",") @@ -140,7 +137,7 @@ if __name__ == "__main__": print_block(pemFile.read(), identifierType=identifierType) ) except OSError: - r = requests.get("https://crt.sh/?d={}".format(certId)) + r = requests.get(f"https://crt.sh/?d={certId}") r.raise_for_status() blocks.append( print_block(r.content, crtshId=certId, identifierType=identifierType) @@ -149,8 +146,8 @@ if __name__ == "__main__": print("static const DataAndLength " + args.listname + "[]= {") for structName in blocks: if len(structName) < 33: - print(" { " + "{name}, sizeof({name}) ".format(name=structName) + "},") + print(" { " + f"{structName}, sizeof({structName}) " + "},") else: - print(" { " + "{},".format(structName)) - print(" sizeof({})".format(structName) + " },") + print(" { " + f"{structName},") + print(f" sizeof({structName})" + " },") print("};") diff --git a/security/manager/tools/mach_commands.py b/security/manager/tools/mach_commands.py index 283a6167a6bd..e99a4db63bf1 100644 --- a/security/manager/tools/mach_commands.py +++ b/security/manager/tools/mach_commands.py @@ -98,9 +98,7 @@ def generate_test_certs(command_context, specifications): output_is_binary = True else: raise UserError( - "'{}' is not a .certspec, .keyspec, or .pkcs12spec file".format( - specification - ) + f"'{specification}' is not a .certspec, .keyspec, or .pkcs12spec file" ) run_module_main_on(module, os.path.abspath(specification), output_is_binary) return 0 diff --git a/security/manager/tools/pycert.py b/security/manager/tools/pycert.py index f11d2357a1a1..9280366eccd4 100755 --- a/security/manager/tools/pycert.py +++ b/security/manager/tools/pycert.py @@ -361,13 +361,13 @@ def serialBytesToString(serialBytes): the corresponding serial number string.""" serialBytesLen = len(serialBytes) if serialBytesLen > 127: - raise InvalidSerialNumber("{} bytes is too long".format(serialBytesLen)) + raise InvalidSerialNumber(f"{serialBytesLen} bytes is too long") # Prepend the ASN.1 INTEGER tag and length bytes. stringBytes = [getASN1Tag(univ.Integer), serialBytesLen] + serialBytes return bytes(stringBytes) -class Certificate(object): +class Certificate: """Utility class for reading a certificate specification and generating a signed x509 certificate""" diff --git a/security/manager/tools/pycms.py b/security/manager/tools/pycms.py index 1717513fdf9a..a6928a549480 100755 --- a/security/manager/tools/pycms.py +++ b/security/manager/tools/pycms.py @@ -55,7 +55,7 @@ class UnknownDirectiveError(Error): return "Unknown directive %s" % repr(self.directive) -class CMS(object): +class CMS: """Utility class for reading a CMS specification and generating a CMS message""" diff --git a/security/manager/tools/pyct.py b/security/manager/tools/pyct.py index 168cf7447f20..5c0462a9f5a7 100644 --- a/security/manager/tools/pyct.py +++ b/security/manager/tools/pyct.py @@ -61,7 +61,7 @@ class UnknownSignedEntryType(Exception): return 'Unknown SignedEntry type: "%s"' % str(self.signedEntry) -class SignedEntry(object): +class SignedEntry: """Base class for CT entries. Use PrecertEntry or X509Entry.""" @@ -81,7 +81,7 @@ class X509Entry(SignedEntry): self.certificate = certificate -class SCT(object): +class SCT: """SCT represents a Signed Certificate Timestamp.""" def __init__(self, key, date, signedEntry): diff --git a/security/manager/tools/pykey.py b/security/manager/tools/pykey.py index fec8021c2606..56cee0455084 100755 --- a/security/manager/tools/pykey.py +++ b/security/manager/tools/pykey.py @@ -193,7 +193,7 @@ class PrivateKeyInfo(univ.Sequence): ) -class RSAKey(object): +class RSAKey: # For reference, when encoded as a subject public key info, the # base64-encoded sha-256 hash of this key is # VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8= @@ -784,7 +784,7 @@ def longToEvenLengthHexString(val): return h -class ECCKey(object): +class ECCKey: secp256k1KeyPair = ( "35ee7c7289d8fef7a86afe5da66d8bc2ebb6a8543fd2fead089f45ce7acd0fa6" + "4382a9500c41dad770ffd4b511bf4b492eb1238800c32c4f76c73a3f3294e7c5", diff --git a/security/manager/tools/pypkcs12.py b/security/manager/tools/pypkcs12.py index fa140c137d74..6c1ac5448836 100644 --- a/security/manager/tools/pypkcs12.py +++ b/security/manager/tools/pypkcs12.py @@ -62,7 +62,7 @@ def runUtil(util, args): return proc.returncode -class PKCS12(object): +class PKCS12: """Utility class for reading a specification and generating a PKCS12 file""" diff --git a/taskcluster/android_taskgraph/build_config.py b/taskcluster/android_taskgraph/build_config.py index ebfba81ff4ca..61aba5343247 100644 --- a/taskcluster/android_taskgraph/build_config.py +++ b/taskcluster/android_taskgraph/build_config.py @@ -35,9 +35,7 @@ def get_extensions(component): ].get("artifact-type", "aar") if artifact_type not in EXTENSIONS: raise ValueError( - "For '{}', 'artifact-type' must be one of {}".format( - component, repr(EXTENSIONS.keys()) - ) + f"For '{component}', 'artifact-type' must be one of {repr(EXTENSIONS.keys())}" ) return [ @@ -75,12 +73,10 @@ def get_variant(build_type, build_name): ] number_of_matching_variants = len(matching_variants) if number_of_matching_variants == 0: - raise ValueError('No variant found for build type "{}"'.format(build_type)) + raise ValueError(f'No variant found for build type "{build_type}"') elif number_of_matching_variants > 1: raise ValueError( - 'Too many variants found for build type "{}"": {}'.format( - build_type, matching_variants - ) + f'Too many variants found for build type "{build_type}"": {matching_variants}' ) return matching_variants.pop() diff --git a/taskcluster/android_taskgraph/transforms/build_android_app.py b/taskcluster/android_taskgraph/transforms/build_android_app.py index e325dd09c832..f268d5ec5400 100644 --- a/taskcluster/android_taskgraph/transforms/build_android_app.py +++ b/taskcluster/android_taskgraph/transforms/build_android_app.py @@ -122,7 +122,7 @@ def _get_secrets_keys_and_target_files(task): [ ( "firebase", - "app/src/{}/res/values/firebase.xml".format(gradle_build_type), + f"app/src/{gradle_build_type}/res/values/firebase.xml", ), ("wallpaper_url", ".wallpaper_url"), ("pocket_consumer_key", ".pocket_consumer_key"), diff --git a/taskcluster/android_taskgraph/transforms/notify.py b/taskcluster/android_taskgraph/transforms/notify.py index 20fea476e3e4..d4fe097e3ee7 100644 --- a/taskcluster/android_taskgraph/transforms/notify.py +++ b/taskcluster/android_taskgraph/transforms/notify.py @@ -18,7 +18,7 @@ def resolve_keys(config, tasks): item_name=task["name"], **{ "level": config.params["level"], - } + }, ) yield task @@ -40,7 +40,7 @@ def add_notify_email(config, tasks): routes = task.setdefault("routes", []) routes.extend( [ - "notify.email.{}.on-{}".format(address, reason) + f"notify.email.{address}.on-{reason}" for address in email_config["to-addresses"] for reason in email_config["on-reasons"] ] diff --git a/taskcluster/android_taskgraph/util/scriptworker.py b/taskcluster/android_taskgraph/util/scriptworker.py index a624bf56fd7b..c250ec83770d 100644 --- a/taskcluster/android_taskgraph/util/scriptworker.py +++ b/taskcluster/android_taskgraph/util/scriptworker.py @@ -58,7 +58,7 @@ def generate_beetmover_upstream_artifacts( elif job.get("primary-dependency"): dependencies = [job["primary-dependency"].kind] else: - raise Exception("Unsupported type of dependency. Got job: {}".format(job)) + raise Exception(f"Unsupported type of dependency. Got job: {job}") for locale, dep in itertools.product(locales, dependencies): paths = list() @@ -114,7 +114,7 @@ def generate_beetmover_upstream_artifacts( upstream_artifacts.append( { - "taskId": {"task-reference": "<{}>".format(dep)}, + "taskId": {"task-reference": f"<{dep}>"}, "taskType": map_config["tasktype_map"].get(dep), "paths": sorted(paths), "locale": locale, @@ -275,7 +275,7 @@ def generate_beetmover_artifact_map(config, job, **kwargs): paths = jsone.render(paths, kwargs) artifacts.append( { - "taskId": {"task-reference": "<{}>".format(dep)}, + "taskId": {"task-reference": f"<{dep}>"}, "locale": locale, "paths": paths, } diff --git a/taskcluster/docker/funsize-update-generator/scripts/funsize.py b/taskcluster/docker/funsize-update-generator/scripts/funsize.py index 0e72da46fc84..0fd4a076ce82 100644 --- a/taskcluster/docker/funsize-update-generator/scripts/funsize.py +++ b/taskcluster/docker/funsize-update-generator/scripts/funsize.py @@ -112,15 +112,13 @@ def validate_mar_channel_id(mar, channel_ids): product_info = MarReader(open(mar, "rb")).productinfo if not isinstance(product_info, tuple): - raise ValueError( - "Malformed product information in mar: {}".format(product_info) - ) + raise ValueError(f"Malformed product information in mar: {product_info}") found_channel_ids = set(product_info[1].split(",")) if not found_channel_ids.issubset(channel_ids): raise ValueError( - "MAR_CHANNEL_ID mismatch, {} not in {}".format(product_info[1], channel_ids) + f"MAR_CHANNEL_ID mismatch, {product_info[1]} not in {channel_ids}" ) log.info("%s channel %s in %s", mar, product_info[1], channel_ids) @@ -142,9 +140,7 @@ async def retry_download(*args, semaphore=None, **kwargs): # noqa: E999 def verify_allowed_url(mar, allowed_url_prefixes): if not any(mar.startswith(prefix) for prefix in allowed_url_prefixes): raise ValueError( - "{mar} is not in allowed URL prefixes: {p}".format( - mar=mar, p=allowed_url_prefixes - ) + f"{mar} is not in allowed URL prefixes: {allowed_url_prefixes}" ) @@ -307,7 +303,7 @@ async def run_command(cmd, cwd="/", env=None, label=None, silent=False): env=env, ) if label: - label = "{}: ".format(label) + label = f"{label}: " else: label = "" @@ -479,7 +475,7 @@ def main(): with open(manifest_file, "w") as fp: json.dump(manifest, fp, indent=2, sort_keys=True) - log.debug("{}".format(json.dumps(manifest, indent=2, sort_keys=True))) + log.debug(f"{json.dumps(manifest, indent=2, sort_keys=True)}") if __name__ == "__main__": diff --git a/taskcluster/docker/periodic-updates/scripts/getCTKnownLogs.py b/taskcluster/docker/periodic-updates/scripts/getCTKnownLogs.py index 6e05d6232c32..0c6fa1222bfc 100755 --- a/taskcluster/docker/periodic-updates/scripts/getCTKnownLogs.py +++ b/taskcluster/docker/periodic-updates/scripts/getCTKnownLogs.py @@ -103,7 +103,7 @@ def get_timestamp(time_str): def get_hex_lines(blob, width): """Convert a binary string to a multiline text of C escape sequences.""" - text = "".join(["\\x{:02x}".format(c) for c in blob]) + text = "".join([f"\\x{c:02x}" for c in blob]) # When escaped, a single byte takes 4 chars (e.g. "\x00"). # Make sure we don't break an escaped byte between the lines. return textwrap.wrap(text, width - width % 4) @@ -116,10 +116,8 @@ def get_operator_index(json_data, target_name): for (index, operator) in enumerate(json_data["operators"]) if operator["name"] == target_name ] - assert len(matches) != 0, "No operators with id {0} defined.".format(target_name) - assert len(matches) == 1, "Found multiple operators with id {0}.".format( - target_name - ) + assert len(matches) != 0, f"No operators with id {target_name} defined." + assert len(matches) == 1, f"Found multiple operators with id {target_name}." return matches[0][1] @@ -180,16 +178,14 @@ def get_log_info_structs(json_data): # Not perfect but close enough. description=json.dumps(log["description"]), operator_index=operator_index, - operator_comment="operated by {0}". - # The comment must not contain "/". - format(operator_name).replace("/", "|"), + operator_comment=f"operated by {operator_name}".replace("/", "|"), state=state, timestamp=timestamp, spaces=spaces, timestamp_comment=timestamp_comment, # Maximum line width is 80. indented_log_key="\n".join( - [' "{0}"'.format(l) for l in get_hex_lines(log_key, 74)] + [f' "{l}"' for l in get_hex_lines(log_key, 74)] ), log_key_len=len(log_key), ) diff --git a/taskcluster/docker/snap-coreXX-build/parse.py b/taskcluster/docker/snap-coreXX-build/parse.py index f1b4c7c6ab7a..d6a51f1cf066 100644 --- a/taskcluster/docker/snap-coreXX-build/parse.py +++ b/taskcluster/docker/snap-coreXX-build/parse.py @@ -30,7 +30,7 @@ def iter_pkgs(part, all_pkgs, arch): def parse(yaml_file, arch): all_pkgs = [] - with open(yaml_file, "r") as inp: + with open(yaml_file) as inp: snap = yaml.safe_load(inp) parts = snap["parts"] for p in parts: diff --git a/taskcluster/docker/snap-coreXX-build/snap-tests/basic_tests.py b/taskcluster/docker/snap-coreXX-build/snap-tests/basic_tests.py index 8592fb1f35d6..34ca73da3a1b 100644 --- a/taskcluster/docker/snap-coreXX-build/snap-tests/basic_tests.py +++ b/taskcluster/docker/snap-coreXX-build/snap-tests/basic_tests.py @@ -33,13 +33,11 @@ class SnapTestsBase: def __init__(self, exp): self._INSTANCE = os.environ.get("TEST_SNAP_INSTANCE") - self._PROFILE_PATH = "~/snap/{}/common/.mozilla/firefox/".format(self._INSTANCE) - self._LIB_PATH = r"/snap/{}/current/usr/lib/firefox/libxul.so".format( - self._INSTANCE - ) + self._PROFILE_PATH = f"~/snap/{self._INSTANCE}/common/.mozilla/firefox/" + self._LIB_PATH = rf"/snap/{self._INSTANCE}/current/usr/lib/firefox/libxul.so" # This needs to be the snap-based symlink geckodriver to properly setup # the Snap environment - self._EXE_PATH = r"/snap/bin/{}.geckodriver".format(self._INSTANCE) + self._EXE_PATH = rf"/snap/bin/{self._INSTANCE}.geckodriver" # This needs to be the full path to the binary because at the moment of # its execution it will already be under the Snap environment, and @@ -57,9 +55,7 @@ class SnapTestsBase: # One should see output generated in the instance-specific temp dir # /tmp/snap-private-tmp/snap.{}/tmp/snap-test.txt # denoting that everything properly runs under Snap as expected. - self._BIN_PATH = r"/snap/{}/current/usr/lib/firefox/firefox".format( - self._INSTANCE - ) + self._BIN_PATH = rf"/snap/{self._INSTANCE}/current/usr/lib/firefox/firefox" snap_profile_path = tempfile.mkdtemp( prefix="snap-tests", @@ -124,7 +120,7 @@ class SnapTestsBase: self._wait = WebDriverWait(self._driver, self.get_timeout()) self._longwait = WebDriverWait(self._driver, 60) - with open(exp, "r") as j: + with open(exp) as j: self._expectations = json.load(j) # exit code ; will be set to 1 at first assertion failure @@ -135,8 +131,8 @@ class SnapTestsBase: channel = "esr-128" core_base = self.snap_core_base() - channel_and_core = "{}core{}".format(channel, core_base) - self._logger.info("Channel & Core: {}".format(channel_and_core)) + channel_and_core = f"{channel}core{core_base}" + self._logger.info(f"Channel & Core: {channel_and_core}") for m in object_methods: self._logger.test_start(m) @@ -153,7 +149,7 @@ class SnapTestsBase: assert rv is not None, "test returned no value" tabs_after = set(self._driver.window_handles) - self._logger.info("tabs_after OK {}".format(tabs_after)) + self._logger.info(f"tabs_after OK {tabs_after}") self._driver.switch_to.parent_frame() if rv: @@ -170,33 +166,31 @@ class SnapTestsBase: test_message = repr(ex) self.save_screenshot( - "screenshot_{}_{}.png".format(m.lower(), test_status.lower()) + f"screenshot_{m.lower()}_{test_status.lower()}.png" ) self._driver.switch_to.parent_frame() self.save_screenshot( - "screenshot_{}_{}_parent.png".format(m.lower(), test_status.lower()) + f"screenshot_{m.lower()}_{test_status.lower()}_parent.png" ) self._logger.test_end(m, status=test_status, message=test_message) traceback.print_exc() tabs_after = set(self._driver.window_handles) - self._logger.info("tabs_after EXCEPTION {}".format(tabs_after)) + self._logger.info(f"tabs_after EXCEPTION {tabs_after}") finally: - self._logger.info("tabs_before {}".format(tabs_before)) + self._logger.info(f"tabs_before {tabs_before}") tabs_opened = tabs_after - tabs_before - self._logger.info("opened {} tabs".format(len(tabs_opened))) - self._logger.info("opened {} tabs".format(tabs_opened)) + self._logger.info(f"opened {len(tabs_opened)} tabs") + self._logger.info(f"opened {tabs_opened} tabs") closed = 0 for tab in tabs_opened: - self._logger.info("switch to {}".format(tab)) + self._logger.info(f"switch to {tab}") self._driver.switch_to.window(tab) - self._logger.info("close {}".format(tab)) + self._logger.info(f"close {tab}") self._driver.close() closed += 1 self._logger.info( - "wait EC.number_of_windows_to_be({})".format( - len(tabs_after) - closed - ) + f"wait EC.number_of_windows_to_be({len(tabs_after) - closed})" ) self._wait.until( EC.number_of_windows_to_be(len(tabs_after) - closed) @@ -207,7 +201,7 @@ class SnapTestsBase: if not "TEST_NO_QUIT" in os.environ.keys(): self._driver.quit() - self._logger.info("Exiting with {}".format(ec)) + self._logger.info(f"Exiting with {ec}") self._logger.suite_end() sys.exit(ec) @@ -219,7 +213,7 @@ class SnapTestsBase: def save_screenshot(self, name): final_name = self.get_screenshot_destination(name) - self._logger.info("Saving screenshot '{}' to '{}'".format(name, final_name)) + self._logger.info(f"Saving screenshot '{name}' to '{final_name}'") self._driver.save_screenshot(final_name) def get_timeout(self): @@ -260,7 +254,7 @@ class SnapTestsBase: self._update_channel = self._driver.execute_script( "return Services.prefs.getStringPref('app.update.channel');" ) - self._logger.info("Update channel: {}".format(self._update_channel)) + self._logger.info(f"Update channel: {self._update_channel}") self._driver.set_context("content") return self._update_channel @@ -270,7 +264,7 @@ class SnapTestsBase: self._snap_core_base = self._driver.execute_script( "return Services.sysinfo.getProperty('distroVersion');" ) - self._logger.info("Snap Core: {}".format(self._snap_core_base)) + self._logger.info(f"Snap Core: {self._snap_core_base}") self._driver.set_context("content") return self._snap_core_base @@ -280,7 +274,7 @@ class SnapTestsBase: self._version_major = self._driver.execute_script( "return AppConstants.MOZ_APP_VERSION.split('.')[0];" ) - self._logger.info("Version major: {}".format(self._version_major)) + self._logger.info(f"Version major: {self._version_major}") self._driver.set_context("content") return self._version_major @@ -308,9 +302,7 @@ class SnapTestsBase: new_ref = "new_{}".format(exp["reference"]) new_ref_file = self.get_screenshot_destination(new_ref) self._logger.info( - "Collecting new reference screenshot: {} => {}".format( - new_ref, new_ref_file - ) + f"Collecting new reference screenshot: {new_ref} => {new_ref_file}" ) with open(new_ref_file, "wb") as current_screenshot: @@ -340,7 +332,7 @@ class SnapTestsBase: draw_diff.rectangle(bbox, outline="red") # Some differences have been found, let's verify - self._logger.info("Non empty differences bbox: {}".format(bbox)) + self._logger.info(f"Non empty differences bbox: {bbox}") buffered = io.BytesIO() diff.save(buffered, format="PNG") @@ -370,12 +362,10 @@ class SnapTestsBase: svg_ref.save(current_screenshot) (left, upper, right, lower) = bbox - assert right >= left, "Inconsistent boundaries right={} left={}".format( - right, left - ) - assert lower >= upper, "Inconsistent boundaries lower={} upper={}".format( - lower, upper - ) + assert right >= left, f"Inconsistent boundaries right={right} left={left}" + assert ( + lower >= upper + ), f"Inconsistent boundaries lower={lower} upper={upper}" if ((right - left) <= 2) or ((lower - upper) <= 2): self._logger.info("Difference is a <= 2 pixels band, ignoring") return @@ -407,16 +397,14 @@ class SnapTests(SnapTestsBase): EC.visibility_of_element_located((By.ID, "version-box")) ) self._wait.until(lambda d: len(version_box.text) > 0) - self._logger.info("about:support version: {}".format(version_box.text)) + self._logger.info(f"about:support version: {version_box.text}") assert version_box.text == exp["version_box"], "version text should match" distributionid_box = self._wait.until( EC.visibility_of_element_located((By.ID, "distributionid-box")) ) self._wait.until(lambda d: len(distributionid_box.text) > 0) - self._logger.info( - "about:support distribution ID: {}".format(distributionid_box.text) - ) + self._logger.info(f"about:support distribution ID: {distributionid_box.text}") assert ( distributionid_box.text == exp["distribution_id"] ), "distribution_id should match" @@ -424,9 +412,7 @@ class SnapTests(SnapTestsBase): windowing_protocol = self._driver.execute_script( "return document.querySelector('th[data-l10n-id=\"graphics-window-protocol\"').parentNode.lastChild.textContent;" ) - self._logger.info( - "about:support windowing protocol: {}".format(windowing_protocol) - ) + self._logger.info(f"about:support windowing protocol: {windowing_protocol}") assert windowing_protocol == "wayland", "windowing protocol should be wayland" return True @@ -438,7 +424,7 @@ class SnapTests(SnapTestsBase): EC.visibility_of_element_located((By.CSS_SELECTOR, "a")) ) self._wait.until(lambda d: len(source_link.text) > 0) - self._logger.info("about:buildconfig source: {}".format(source_link.text)) + self._logger.info(f"about:buildconfig source: {source_link.text}") assert source_link.text.startswith( exp["source_repo"] ), "source repo should exists and match" @@ -447,7 +433,7 @@ class SnapTests(SnapTestsBase): EC.visibility_of_element_located((By.CSS_SELECTOR, "p:last-child")) ) self._wait.until(lambda d: len(build_flags_box.text) > 0) - self._logger.info("about:support buildflags: {}".format(build_flags_box.text)) + self._logger.info(f"about:support buildflags: {build_flags_box.text}") assert ( build_flags_box.text.find(exp["official"]) >= 0 ), "official build flag should be there" @@ -530,7 +516,7 @@ class SnapTests(SnapTestsBase): ), "youtube video should perform playback" except TimeoutException as ex: self._logger.info("video detection timed out") - self._logger.info("video: {}".format(video)) + self._logger.info(f"video: {video}") if video: self._logger.info( "video duration: {}".format(video.get_property("duration")) diff --git a/taskcluster/docker/snap-coreXX-build/snap-tests/qa_tests.py b/taskcluster/docker/snap-coreXX-build/snap-tests/qa_tests.py index 273afe151b60..db183ff11bc0 100644 --- a/taskcluster/docker/snap-coreXX-build/snap-tests/qa_tests.py +++ b/taskcluster/docker/snap-coreXX-build/snap-tests/qa_tests.py @@ -24,7 +24,7 @@ class QATests(SnapTestsBase): super(QATests, self).__init__( exp=os.path.join( - self._dir, "qa_expectations_{}.json".format(self._distro_release()) + self._dir, f"qa_expectations_{self._distro_release()}.json" ) ) @@ -41,7 +41,7 @@ class QATests(SnapTestsBase): def _test_audio_playback( self, url, iframe_selector=None, click_to_play=False, video_selector=None ): - self._logger.info("open url {}".format(url)) + self._logger.info(f"open url {url}") if url: self.open_tab(url) @@ -107,9 +107,7 @@ class QATests(SnapTestsBase): paused = video.get_property("paused") time.sleep(1) datum_after_sleep = video.get_property("currentTime") - self._logger.info( - "datum={} datum_after_sleep={}".format(datum, datum_after_sleep) - ) + self._logger.info(f"datum={datum} datum_after_sleep={datum_after_sleep}") assert datum == datum_after_sleep, "