Skip to content

Instantly share code, notes, and snippets.

@therightstuff
Created June 12, 2023 20:36
Show Gist options
  • Save therightstuff/3640c39f9647f3416e69be4007a6b52c to your computer and use it in GitHub Desktop.
Save therightstuff/3640c39f9647f3416e69be4007a6b52c to your computer and use it in GitHub Desktop.
checksums
// calculate md5 hash for entire src directory
// according to https://unix.stackexchange.com/a/35834/305967
console.log(`calculating md5 hash for ${layer}...`);
let hash = process.execSync(`tar -cf - ${layerSrcPath} | md5sum | cut -d ' ' -f 1`, { encoding: 'utf8' }).trim();
// inspired by https://stackoverflow.com/a/44643479/2860309
function checksumFile(path, algorithm=DEFAULT_ALGORITHM) {
const hash = crypto.createHash(algorithm);
return new Promise((resolve, reject) => {
const stream = fs.createReadStream(path);
stream.on('error', err => reject(err));
stream.on('data', chunk => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
});
}
function checksumDirectory(path, algorithm=DEFAULT_ALGORITHM) {
const hash = crypto.createHash(algorithm);
return new Promise(async (resolve, reject) => {
fs.readdir(path, { withFileTypes: true }, async (err, files) => {
if (err) {
reject(err);
} else {
files.sort((a, b) => a.name.localeCompare(b.name));
for (let file of files) {
if (file.isDirectory()) {
hash.update(await checksumDirectory(path + '/' + file.name, algorithm));
} else {
hash.update(await checksumFile(path + '/' + file.name, algorithm));
}
}
resolve(hash.digest('hex'));
}
});
});
}
let hash = await checksumDirectory(layerSrcPath, 'md5');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment