Files
Samuel Attard 826ffcf375 chore: remove dead code, unused chromium_src sources and orphaned files (#54229)
* build: remove unused and duplicated sources from chromium_src

- global_accelerator_listener{,_linux}.cc were compiled here and again by
  the //ui/base/accelerators/global_accelerator_listener dep; keep the dep
  (as a public_dep, shell/ includes its header) and drop the copies.
- native_window_tracker_aura duplicates //ui/native_window_tracker, which
  is already linked; //ui/views/native_window_tracker.h no longer exists.
- chrome's platform_util{,_aura,_mac} were added for the colour chooser
  in 2018 and nothing includes chrome/browser/platform_util.h any more.
- browser_theme_pack, custom_theme_supplier and window_frame_util.cc only
  reference each other; theme_properties and window_frame_util.h stay.
- back_to_tab_label_button, skip_ad_label_button, resize_handle_button
  and overlay_window_live_caption_button are never constructed on desktop
  or sit entirely inside our #if 0 hunks.
- scoped_picture_in_picture_occlusion_observation, predictors_features
  (+ its proto dep), exclusive_access_bubble_type.cc and the spellcheck
  language policy handlers have no callers in anything Electron builds.
- delegated_source_list_capturer is only used by thumbnail_capturer_mac,
  printing_service.cc only by pdf_to_emf_converter (Windows), and the
  hang_crash_dump.cc Linux stub is never called.
- web_request_resource_type.{cc,h} moved upstream in June; the
  enable_electron_extensions=false branch could not gn gen with it listed.

* refactor: remove unregistered browserAction/pageAction extension classes

browser_action.json is not part of the function registration target, so
the twelve BrowserAction*Function and seven PageAction*Function classes
were never instantiated, and the ExtensionActionAPI keyed service was
never built because nothing referenced its factory. Drop them together
with a few other extension leftovers that have no callers:
ElectronExtensionSystem::OnExtensionRegisteredWithRequestContexts,
ElectronExtensionsBrowserClient::SetAPIClientForTest and
ElectronExtensionsRendererClient::AllowPopup (its upstream virtual is
gone), and use extensions::util::AllowFileAccess instead of two local
copies of it.

* refactor: remove unreferenced C++ from shell/

None of these have a caller on any platform:

- OffScreenRenderWidgetHostView::AddGuestHostView/RemoveGuestHostView/
  RemoveViewProxy and guest_host_views_ (never populated, so every loop
  over it was dead too)
- FileSelectHelper::IsAcceptTypeValid/GetSanitizedFileName/
  SetFileSelectListenerForTesting
- FileSystemAccessPermissionContext::OriginHasReadAccess/WriteAccess
- ElectronBrowserClient::GetSiteInstanceFromAffinity
- ElectronPermissionManager::HasPermissionRequestHandler
- api::BaseWindow::SetGTKDarkThemeEnabled and the NativeWindow virtual
  behind it (NativeWindowViews keeps its own private helper)
- crash_reporter::IsCrashReporterEnabled/GetGlobalCrashKeys
- InspectableWebContents::GetDelegate
- NativeWindowObserver::WillCreatePopupWindow/WillNavigate
- WebRequest::RequestFilter's three-argument constructor
- declarations with no definition: ServiceWorkerContext::
  StopWorkersForScope, WebContents::OnElectronBrowserConnectionError/
  OnGetZoomLevel, NetworkContextService::CreateNetworkContextParams,
  WindowsToastNotification::ShowInternal, ElectronApiServiceImpl::
  ProcessPendingMessages
- NativeWindow::is_closed(), WebContentsZoomController::
  persist_zoom_mode(), BrowserProcessImpl::CreateGlobalFeaturesForTesting()
- the Linux stubs for asar::Archive::HeaderIntegrity/RelativePath and the
  non-mac Clipboard::ReadFindText stub (their callers are already
  platform-guarded, so guard the declarations instead)
- the 'render-view-deleted' event, which existed for the removed remote
  module's object registry

* refactor: remove unused gin_helper and converter code

- gin_helper::ErrorThrower::ThrowReferenceError/ThrowSyntaxError, the
  zero-argument PromiseBase::Reject() and PromiseBase::RejectPromise had
  no callers.
- CreateDataPropertyCallback and Dispatcher::DispatchToCallbackForProperty
  were never instantiated.
- Converter<blink::mojom::Referrer> (Electron uses content::Referrer) and
  Converter<blink::mojom::MenuItem::Type>::ToV8 had no users; drop the
  full popup_menu.mojom.h include from content_converter.h and only pull
  the ReferrerPolicy enum into blink_converter.

* refactor: remove native bindings and methods that JS never calls

- The electron_common_environment binding has had no caller since the
  forwarded WebContents events moved native (#53975).
- Nothing requests the electron_browser_printing binding;
  webContents.getPrintersAsync() calls GetPrinterListAsync() directly.
- features.isExtensionsEnabled(), the top-level executeInWorld/
  exposeAPIInWorld exports on the context_bridge binding,
  webFrameMain._fromIdIfExists/_fromFtnIdIfExists,
  WebContents._getPreloadScript, webFrame._isEvalAllowed and
  Menu._getUserAcceleratorAt are not used by lib/ or spec/.
- Protocol::IsProtocolHandled was installed on the prototype template and
  then unconditionally replaced by the JS implementation in
  lib/browser/api/protocol.ts, so the C++ copy could never run.

* chore: remove dead code and stale typings from lib/

- WebFrameMain.prototype._sendInternal, WebViewImpl.setupEventProperty/
  on/onAttach, the 'setLayoutZoomLevelLimits' webview method (removed in
  Electron 9) and WEB_VIEW_ATTRIBUTES.NAME had no callers.
- The Electron 20 sandbox-default deprecation log could never fire:
  getLastWebPreferences() never contains 'preload' and always contains
  'sandbox'.
- lib/browser/api/crash-reporter.ts only ships in the browser bundle, so
  its process.type checks were constant.
- WebSQL was removed in Electron 31; drop enableWebSQL from the inherited
  guest preferences and the docs, and the no-op 'webSQL' clearData type.
- Drop typings for things that no longer exist (ProcessType, ReplyChannel/
  _replyChannel, the WebContents '-ipc-*' and '-window-visibility-change'
  overloads, ElectronInternal.LoadURLOptions, Chrome.Tabs, NodeJS.Global
  augmentations, Process.log/mainModule/_serviceStartupScript, the
  document-start/end overloads, NetBinding.Net/net, App: Function,
  Window.ELECTRON_*_SECURITY_WARNINGS, _awaitNextLoad) and the .oxlintrc
  globs for lib/preload_realm and lib/sandboxed_renderer.

* chore: remove orphaned fixtures, scripts and CI leftovers

- spec/fixtures/release-notes/ (its spec left with the release scripts in
  #52100), devtools-extensions/bad-manifest/, assets/osr.png,
  pages/storage/web_sql.html, pages/history.html, module/hello-child.js,
  esm/local.mjs and api/local-ai-handler/no-language-model.js are not
  referenced by any spec.
- script/verify-chromedriver.py and script/run-if-exists.js lost their
  last callers with the AppVeyor removal; script/lib/npm.py,
  script/lib/native_tests.py, build/args/native_tests.gn, the pyyaml DEPS
  entry and shell/browser/ui/{accelerator_util_unittests,run_all_unittests}.cc
  are leftovers of the native test target removed in #40190.
- script/lib/git.py is_repo_root/get_repo_root and script/lib/utils.js
  getCurrentBranch/handleGitCall have no callers.
- pipeline-electron-build-and-test-and-nan.yml is not referenced by any
  workflow since #49072.
- Three spec/disabled-tests.json titles, one node-disabled-tests entry, a
  wayland allowlist entry, a sysroots.json arch and two CODEOWNERS paths
  named things that no longer exist; four docs/images files are unlinked.
2026-09-24 00:12:45 +02:00

190 lines
5.7 KiB
JavaScript

const childProcess = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { styleText } = require('node:util');
const ELECTRON_DIR = path.resolve(__dirname, '..', '..');
const SRC_DIR = path.resolve(ELECTRON_DIR, '..');
const CHROMIUM_VERSION_DEPS_REGEX = /chromium_version':\n +'(.+?)',/m;
// oxlint-disable-next-line @typescript-eslint/no-unused-vars
const pass = styleText('green', '✓');
function getElectronExec() {
const OUT_DIR = getOutDir();
switch (process.platform) {
case 'darwin':
return `out/${OUT_DIR}/Electron.app/Contents/MacOS/Electron`;
case 'win32':
return `out/${OUT_DIR}/electron.exe`;
case 'linux':
return `out/${OUT_DIR}/electron`;
default:
throw new Error('Unknown platform');
}
}
function getOutDir(options = {}) {
const shouldLog = options.shouldLog || false;
const presetDirs = ['Testing', 'Release', 'Default', 'Debug'];
if (options.outDir || process.env.ELECTRON_OUT_DIR) {
const outDir = options.outDir || process.env.ELECTRON_OUT_DIR;
const outPath = path.resolve(SRC_DIR, 'out', outDir);
// Check that user-set variable is a valid/existing directory
if (fs.existsSync(outPath)) {
if (shouldLog) console.log(`OUT_DIR is: ${outDir}`);
return outDir;
}
// Throw error if user passed/set nonexistent directory.
throw new Error(`${outDir} directory not configured on your machine.`);
} else {
for (const buildType of presetDirs) {
const outPath = path.resolve(SRC_DIR, 'out', buildType);
if (fs.existsSync(outPath)) {
if (shouldLog) console.log(`OUT_DIR is: ${buildType}`);
return buildType;
}
}
}
// If we got here, it means process.env.ELECTRON_OUT_DIR was not
// set and none of the preset options could be found in /out, so throw
throw new Error(
`No valid out directory found; use one of ${presetDirs.join(',')} or set process.env.ELECTRON_OUT_DIR`
);
}
function getAbsoluteElectronExec() {
return path.resolve(SRC_DIR, getElectronExec());
}
function chunkFilenames(filenames, offset = 0) {
// Windows has a max command line length of 2047 characters, so we can't
// provide too many filenames without going over that. To work around that,
// chunk up a list of filenames such that it won't go over that limit when
// used as args. Other platforms may have higher limits, but 4095 might be
// the limit on Linux systems according to `termios(3)`, so cap it there.
const MAX_FILENAME_ARGS_LENGTH = (os.platform() === 'win32' ? 2047 : 4095) - offset;
return filenames.reduce(
(chunkedFilenames, filename) => {
const currChunk = chunkedFilenames[chunkedFilenames.length - 1];
const currChunkLength = currChunk.reduce((totalLength, _filename) => totalLength + _filename.length + 1, 0);
if (currChunkLength + filename.length + 1 > MAX_FILENAME_ARGS_LENGTH) {
chunkedFilenames.push([filename]);
} else {
currChunk.push(filename);
}
return chunkedFilenames;
},
[[]]
);
}
/**
* @param {string} top
* @param {(filename: string) => boolean} test
* @returns {Promise<string[]>}
*/
async function findMatchingFiles(top, test) {
return fs.promises.readdir(top, { encoding: 'utf8', recursive: true }).then((files) => {
return files
.filter((name) => path.basename(name) !== '.bin')
.filter((name) => test(name))
.map((name) => path.join(top, name));
});
}
function compareVersions(v1, v2) {
const [split1, split2] = [v1.split('.'), v2.split('.')];
if (split1.length !== split2.length) {
throw new Error(`Expected version strings to have same number of sections: ${split1} and ${split2}`);
}
for (let i = 0; i < split1.length; i++) {
const p1 = parseInt(split1[i], 10);
const p2 = parseInt(split2[i], 10);
if (p1 > p2) return 1;
else if (p1 < p2) return -1;
// Continue checking the value if this portion is equal
}
return 0;
}
function getChromiumVersionFromDEPS(depsContent) {
return CHROMIUM_VERSION_DEPS_REGEX.exec(depsContent)?.[1] ?? null;
}
function getDepotToolsEnv() {
let depotToolsEnv;
const findDepotToolsOnPath = () => {
const result = childProcess.spawnSync(os.platform() === 'win32' ? 'where' : 'which', ['gclient']);
if (result.status === 0) {
return process.env;
}
};
const checkForBuildTools = () => {
const result = childProcess.spawnSync('electron-build-tools', ['show', 'env', '--json'], { shell: true });
if (result.status === 0) {
return {
...process.env,
...JSON.parse(result.stdout.toString().trim())
};
}
};
try {
depotToolsEnv = checkForBuildTools();
if (!depotToolsEnv) depotToolsEnv = findDepotToolsOnPath();
} catch {}
if (!depotToolsEnv) {
throw new Error("Couldn't find depot_tools, ensure it's on your PATH");
}
const result = childProcess.spawnSync(
'python3',
[
'-c',
'\'from lib.util import get_chromium_buildtools_path_value; print(get_chromium_buildtools_path_value() or "")\''
],
{ env: depotToolsEnv, shell: true, encoding: 'utf8', cwd: path.join(ELECTRON_DIR, 'script') }
);
if (result.status !== 0) {
throw new Error(result.stderr);
}
const chromiumBuildtoolsPathValue = result.status === 0 ? result.stdout.trim() : null;
// Only set CHROMIUM_BUILDTOOLS_PATH if we're on an older version of depot_tools which requires it
if (chromiumBuildtoolsPathValue) {
depotToolsEnv.CHROMIUM_BUILDTOOLS_PATH = chromiumBuildtoolsPathValue;
}
return depotToolsEnv;
}
module.exports = {
chunkFilenames,
compareVersions,
findMatchingFiles,
getChromiumVersionFromDEPS,
getDepotToolsEnv,
getElectronExec,
getOutDir,
getAbsoluteElectronExec,
ELECTRON_DIR,
SRC_DIR
};