From 57cebf4dd4c722456245286d2fd795f7a5fc862c Mon Sep 17 00:00:00 2001 From: beyondkmp Date: Wed, 2 Oct 2024 20:27:23 +0800 Subject: [PATCH] fix: check if the file already starts with a UTF-8 BOM (#8551) fix https://github.com/electron-userland/electron-builder/issues/8512 If the file is already in UTF-8 BOM format, there's no need to convert it again. If it's converted again, it will result in garbled characters. --------- Co-authored-by: beyondkmp --- .changeset/six-spoons-heal.md | 5 +++++ .../src/targets/nsis/nsisLicense.ts | 21 ++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) create mode 100644 .changeset/six-spoons-heal.md diff --git a/.changeset/six-spoons-heal.md b/.changeset/six-spoons-heal.md new file mode 100644 index 00000000000..5dbedd721af --- /dev/null +++ b/.changeset/six-spoons-heal.md @@ -0,0 +1,5 @@ +--- +"app-builder-lib": patch +--- + +Check if the file already starts with a UTF-8 BOM diff --git a/packages/app-builder-lib/src/targets/nsis/nsisLicense.ts b/packages/app-builder-lib/src/targets/nsis/nsisLicense.ts index 817ff2ddf81..66733ad2fe1 100644 --- a/packages/app-builder-lib/src/targets/nsis/nsisLicense.ts +++ b/packages/app-builder-lib/src/targets/nsis/nsisLicense.ts @@ -1,3 +1,4 @@ +import { log } from "builder-util" import { lcid } from "../../util/langs" import { getLicenseFiles, getNotLocalizedLicenseFile } from "../../util/license" import * as path from "path" @@ -9,17 +10,27 @@ import * as fs from "fs" function convertFileToUtf8WithBOMSync(filePath: string): boolean { try { + const UTF8_BOM_HEADER = Buffer.from([0xef, 0xbb, 0xbf]) const data = fs.readFileSync(filePath) - // UTF-8 BOM is EF BB BF - const BOM = Buffer.from([0xef, 0xbb, 0xbf]) - const dataWithBOM = Buffer.concat([BOM, data]) + + // Check if the file already starts with a UTF-8 BOM + log.debug({ file: log.filePath(filePath) }, "checking file for BOM header") + if (data.length >= UTF8_BOM_HEADER.length && data.subarray(0, UTF8_BOM_HEADER.length).equals(UTF8_BOM_HEADER)) { + log.debug({ file: log.filePath(filePath) }, "file is already in BOM format, skipping conversion.") + return true + } + + // If not, add the BOM + const dataWithBOM = Buffer.concat([UTF8_BOM_HEADER, data]) fs.writeFileSync(filePath, dataWithBOM) + log.debug({ file: log.filePath(filePath) }, "file successfully converted to UTF-8 with BOM") return true - } catch (err) { - console.error("Failed to convert file to UTF-8 with BOM: ", err) + } catch (err: any) { + log.error({ file: log.filePath(filePath), message: err.message ?? err.stack }, "unable to convert file to UTF-8 with BOM") return false } } + export async function computeLicensePage(packager: WinPackager, options: NsisOptions, scriptGenerator: NsisScriptGenerator, languages: Array): Promise { const license = await getNotLocalizedLicenseFile(options.license, packager) if (license != null) {