enso/app/ide-desktop/lib/client/tasks/computeHashes.cjs

79 lines
2.7 KiB
JavaScript
Raw Normal View History

/** @file Definition of hash computing functions. */
// Eslint is not (and should not be) set up to recognize CommonJS imports.
/* eslint-disable no-restricted-syntax */
const cryptoModule = require('crypto')
const fs = require('fs')
const pathModule = require('path')
/* eslint-enable no-restricted-syntax */
// =================
// === Constants ===
// =================
/** @typedef {"md5" | "sha1" | "sha256"} ChecksumType */
const CHECKSUM_TYPE = 'sha256'
// ================
// === Checksum ===
// ================
/**
* The `type` argument can be one of `md5`, `sha1`, or `sha256`.
* @param {string} path - Path to the file.
* @param {ChecksumType} type - The checksum algorithm to use. */
function getChecksum(path, type) {
return new Promise(
// This JSDoc annotation is required for correct types that are also type-safe.
/** @param {(value: string) => void} resolve - Fulfill the promise with the given value. */
function (resolve, reject) {
const hash = cryptoModule.createHash(type)
const input = fs.createReadStream(path)
input.on('error', reject)
input.on('data', function (chunk) {
hash.update(chunk)
})
input.on('close', function () {
resolve(hash.digest('hex'))
})
}
)
}
/** Based on https://stackoverflow.com/a/57371333.
* @param {string} file - The path to the file.
* @param {string} extension - The new extension of the file.
* @returns A path with the new exension. */
2022-05-23 05:16:04 +03:00
function changeExtension(file, extension) {
const basename = pathModule.basename(file, pathModule.extname(file))
return pathModule.join(pathModule.dirname(file), `${basename}.${extension}`)
2022-05-23 05:16:04 +03:00
}
/** Write the file checksum to the provided path.
* @param {string} path - The path to the file.
* @param {ChecksumType} type - The checksum algorithm to use. */
async function writeFileChecksum(path, type) {
let checksum = await getChecksum(path, type)
2022-05-23 05:16:04 +03:00
let targetPath = changeExtension(path, type)
console.log(`Writing ${targetPath}.`)
fs.writeFile(targetPath, checksum, 'utf8', err => {
if (err) {
throw err
}
})
}
// ================
// === Callback ===
// ================
/** Generates checksums for all build artifacts.
* @param {import('electron-builder').BuildResult} context - Build information. */
2022-05-23 05:16:04 +03:00
exports.default = async function (context) {
// `context` is BuildResult, see https://www.electron.build/configuration/configuration.html#buildresult
for (const file of context.artifactPaths) {
console.log(`Generating ${CHECKSUM_TYPE} checksum for ${file}.`)
await writeFileChecksum(file, CHECKSUM_TYPE)
}
return []
}