Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: two-package.json electron version query #7511

Merged
merged 7 commits into from
Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/new-cats-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"app-builder-lib": patch
"electron-builder": patch
---

fix: utilizing frameworkInfo as primary manner of fetching electron version for installation. (fixes: #7494)
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ electron-builder-*.d.ts

tsconfig.tsbuildinfo

.pnpm-store/
.pnpm-store/
**/node_modules
3 changes: 1 addition & 2 deletions packages/app-builder-lib/src/electron/ElectronFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import BluebirdPromise from "bluebird-lst"
import { asArray, executeAppBuilder, log } from "builder-util"
import { CONCURRENCY, copyDir, DO_NOT_USE_HARD_LINKS, statOrNull, unlinkIfExists } from "builder-util/out/fs"
import { emptyDir, readdir, rename } from "fs-extra"
import { Lazy } from "lazy-val"
import * as path from "path"
import { Configuration } from "../configuration"
import { BeforeCopyExtraFilesOptions, Framework, PrepareApplicationStageDirectoryOptions } from "../Framework"
Expand Down Expand Up @@ -155,7 +154,7 @@ export async function createElectronFrameworkSupport(configuration: Configuratio
throw new Error(`Cannot compute electron version for prepacked asar`)
}
} else {
version = await computeElectronVersion(packager.projectDir, new Lazy(() => Promise.resolve(packager.metadata)))
version = await computeElectronVersion(packager.projectDir)
}
configuration.electronVersion = version
}
Expand Down
24 changes: 14 additions & 10 deletions packages/app-builder-lib/src/electron/electronVersion.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getProjectRootPath } from "@electron/rebuild/lib/src/search-module"
import { InvalidConfigurationError, log } from "builder-util"
import { parseXml } from "builder-util-runtime"
import { httpExecutor } from "builder-util/out/nodeHttpExecutor"
Expand All @@ -13,21 +14,17 @@ export type MetadataValue = Lazy<{ [key: string]: any } | null>

const electronPackages = ["electron", "electron-prebuilt", "electron-prebuilt-compile", "electron-nightly"]

export async function getElectronVersion(
projectDir: string,
config?: Configuration,
projectMetadata: MetadataValue = new Lazy(() => orNullIfFileNotExist(readJson(path.join(projectDir, "package.json"))))
): Promise<string> {
export async function getElectronVersion(projectDir: string, config?: Configuration): Promise<string> {
if (config == null) {
config = await getConfig(projectDir, null, null)
}
if (config.electronVersion != null) {
return config.electronVersion
}
return await computeElectronVersion(projectDir, projectMetadata)
return computeElectronVersion(projectDir)
}

export async function getElectronVersionFromInstalled(projectDir: string) {
export async function getElectronVersionFromInstalled(projectDir: string): Promise<string | null> {
for (const name of electronPackages) {
try {
return (await readJson(path.join(projectDir, "node_modules", name, "package.json"))).version
Expand All @@ -54,13 +51,21 @@ export async function getElectronPackage(projectDir: string) {
}

/** @internal */
export async function computeElectronVersion(projectDir: string, projectMetadata: MetadataValue): Promise<string> {
export async function computeElectronVersion(projectDir: string): Promise<string> {
const result = await getElectronVersionFromInstalled(projectDir)
if (result != null) {
return result
}

const dependency = findFromPackageMetadata(await projectMetadata.value)
const potentialRootDirs = [projectDir, await getProjectRootPath(projectDir)]
let dependency: NameAndVersion | null = null
for await (const dir of potentialRootDirs) {
const metadata = await orNullIfFileNotExist(readJson(path.join(dir, "package.json")))
dependency = metadata ? findFromPackageMetadata(metadata) : null
if (dependency) {
break
}
}
if (dependency?.name === "electron-nightly") {
log.info("You are using a nightly version of electron, be warned that those builds are highly unstable.")
const feedXml = await httpExecutor.request({
Expand Down Expand Up @@ -95,7 +100,6 @@ export async function computeElectronVersion(projectDir: string, projectMetadata

throw new InvalidConfigurationError(`Cannot find electron dependency to get electron version in the '${path.join(projectDir, "package.json")}'`)
}

const version = dependency?.version
if (version == null || !/^\d/.test(version)) {
const versionMessage = version == null ? "" : ` and version ("${version}") is not fixed in project`
Expand Down
2 changes: 1 addition & 1 deletion packages/app-builder-lib/src/packager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ export class Packager {
const frameworkInfo = { version: this.framework.version, useCustomDist: true }
const config = this.config
if (config.nodeGypRebuild === true) {
await nodeGypRebuild(Arch[arch])
await nodeGypRebuild(frameworkInfo, Arch[arch])
}

if (config.npmRebuild === false) {
Expand Down
17 changes: 8 additions & 9 deletions packages/app-builder-lib/src/util/yarn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { homedir } from "os"
import * as path from "path"
import { Configuration } from "../configuration"
import { NodeModuleDirInfo } from "./packageDependencies"
import { getElectronVersion } from "../electron/electronVersion"
import * as electronRebuild from "@electron/rebuild"
import * as searchModule from "@electron/rebuild/lib/src/search-module"

Expand All @@ -26,7 +25,7 @@ export async function installOrRebuild(config: Configuration, appDir: string, op
}
await installDependencies(appDir, effectiveOptions)
} else {
await rebuild(appDir, config.buildDependenciesFromSource === true, options.arch)
await rebuild(appDir, config.buildDependenciesFromSource === true, options.frameworkInfo, options.arch)
}
}

Expand Down Expand Up @@ -119,8 +118,8 @@ function installDependencies(appDir: string, options: RebuildOptions): Promise<a
})
}

export async function nodeGypRebuild(arch: string) {
return rebuild(process.cwd(), false, arch)
export async function nodeGypRebuild(frameworkInfo: DesktopFrameworkInfo, arch: string) {
return rebuild(process.cwd(), false, frameworkInfo, arch)
}

function getPackageToolPath() {
Expand Down Expand Up @@ -149,15 +148,15 @@ export interface RebuildOptions {
}

/** @internal */
export async function rebuild(appDir: string, buildFromSource: boolean, arch = process.arch) {
log.info({ appDir, arch }, "executing @electron/rebuild")
export async function rebuild(appDir: string, buildFromSource: boolean, frameworkInfo: DesktopFrameworkInfo, arch = process.arch) {
log.info({ arch, version: frameworkInfo.version, appDir }, "executing @electron/rebuild")
const rootPath = await searchModule.getProjectRootPath(appDir)
const options: electronRebuild.RebuildOptions = {
buildPath: appDir,
electronVersion: await getElectronVersion(appDir),
electronVersion: frameworkInfo.version,
arch,
force: true,
debug: log.isDebugEnabled,
projectRootPath: await searchModule.getProjectRootPath(appDir),
projectRootPath: rootPath,
}
if (buildFromSource) {
options.prebuildTagPrefix = "totally-not-a-real-prefix-to-force-rebuild"
Expand Down
4 changes: 3 additions & 1 deletion packages/electron-builder/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { createSelfSignedCert } from "./create-self-signed-cert"
import { configureInstallAppDepsCommand, installAppDeps } from "./install-app-deps"
import { start } from "./start"
import { nodeGypRebuild } from "app-builder-lib/out/util/yarn"
import { getElectronVersion } from "app-builder-lib/out/electron/electronVersion"

// tslint:disable:no-unused-expression
void createYargs()
Expand Down Expand Up @@ -75,6 +76,7 @@ async function checkIsOutdated() {
}

async function rebuildAppNativeCode(args: any) {
const projectDir = process.cwd()
// this script must be used only for electron
return nodeGypRebuild(args.arch)
return nodeGypRebuild({ version: await getElectronVersion(projectDir), useCustomDist: true }, args.arch)
}
2 changes: 1 addition & 1 deletion packages/electron-builder/src/cli/install-app-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export async function installAppDeps(args: any) {
projectDir,
use(config.directories, it => it.app)
),
getElectronVersion(projectDir, config, packageMetadata),
getElectronVersion(projectDir, config),
])

// if two package.json — force full install (user wants to install/update app deps in addition to dev)
Expand Down
25 changes: 25 additions & 0 deletions test/fixtures/test-app-two-native-modules/app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<script>
const {ipcRenderer} = require("electron")
function saveAppData() {
ipcRenderer.send("saveAppData")
}
</script>
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.

Args: <script>document.write("<br><br><pre>" + JSON.stringify(require("electron").remote.process.argv, null, 2) + "</pre>")</script>.

Env: <script>document.write("<br><br><pre>" + JSON.stringify(process.env, null, 2) + "</pre>")</script>.

<button onclick="saveAppData()">Save app data</button>
</body>
</html>
77 changes: 77 additions & 0 deletions test/fixtures/test-app-two-native-modules/app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
'use strict'

const { app, ipcMain, BrowserWindow, Menu, Tray } = require("electron")
const fs = require("fs")
const path = require("path")

// Module to control application life.
// Module to create native browser window.

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

let tray = null

function createWindow () {
if (process.platform === "linux" && process.env.APPDIR != null) {
tray = new Tray(path.join(process.env.APPDIR, "testapp.png"))
const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio'},
{label: 'Item2', type: 'radio'},
{label: 'Item3', type: 'radio', checked: true},
{label: 'Item4', type: 'radio'}
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
}

// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});

// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');

// Open the DevTools.
mainWindow.webContents.openDevTools();

mainWindow.webContents.executeJavaScript(`console.log("appData: ${app.getPath("appData").replace(/\\/g, "\\\\")}")`)
mainWindow.webContents.executeJavaScript(`console.log("userData: ${app.getPath("userData").replace(/\\/g, "\\\\")}")`)

// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On MacOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});

app.on("activate", function () {
if (mainWindow === null) {
createWindow()
}
})

ipcMain.on("saveAppData", () => {
try {
// electron doesn't escape / in the product name
fs.writeFileSync(path.join(app.getPath("appData"), "Test App ßW", "testFile"), "test")
}
catch (e) {
mainWindow.webContents.executeJavaScript(`console.log(\`userData: ${e}\`)`)
}
})
8 changes: 8 additions & 0 deletions test/fixtures/test-app-two-native-modules/app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "test-app-two-native-modules",
"main": "index.js",
"version": "1.1.1",
"dependencies": {
"install": "0.13.0"
}
}
8 changes: 8 additions & 0 deletions test/fixtures/test-app-two-native-modules/app/yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


install@0.13.0:
version "0.13.0"
resolved "https://registry.yarnpkg.com/install/-/install-0.13.0.tgz#6af6e9da9dd0987de2ab420f78e60d9c17260776"
integrity sha512-zDml/jzr2PKU9I8J/xyZBQn8rPCAY//UOYNmR01XwNwyfhEWObo2SWfSl1+0tm1u6PhxLwDnfsT/6jB7OUxqFA==
38 changes: 38 additions & 0 deletions test/fixtures/test-app-two-native-modules/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"private": true,
"name": "TestApp2",
"productName": "Test App ßW2",
"version": "1.1.0",
"homepage": "http://foo.example.com",
"description": "Test Application (test quite \" #378)",
"author": "Foo Bar <foo@example.com>",
"license": "MIT",
"devDependencies": {
"electron": "23.2.0"
},
"build": {
"appId": "org.electron-builder.testApp2",
"compression": "store",
"npmRebuild": true,
"directories": {
"app": "app"
},
"files": [
"index.html",
"index.js",
"package.json"
],
"mac": {
"category": "your.app.category.type"
},
"linux": {
"category": "Development"
},
"deb": {
"packageCategory": "devel"
},
"squirrelWindows": {
"iconUrl": "https://raw.githubusercontent.com/szwacz/electron-boilerplate/master/resources/windows/icon.ico"
}
}
}
Loading