Skip to content

Instantly share code, notes, and snippets.

@Avaray
Last active August 4, 2024 06:55
Show Gist options
  • Select an option

  • Save Avaray/23bd3f5214ee8c945f7f164875cd0ff6 to your computer and use it in GitHub Desktop.

Select an option

Save Avaray/23bd3f5214ee8c945f7f164875cd0ff6 to your computer and use it in GitHub Desktop.
Bun.sh - function to get GitHub-style hash for file
// When you are using GitHub Api to get contents from repository,
// file hashes will be different than hashes you get with 'sha1sum'.
// This example shows how you can get same hashes using Bun.sh
import { CryptoHasher } from 'bun';
async function getGitFileHash(filePath: string): Promise<string> {
const file = await Bun.file(filePath).arrayBuffer();
const content = new Uint8Array(file);
const header = `blob ${content.length}\0`;
const headerArray = new TextEncoder().encode(header);
const fullContent = new Uint8Array(headerArray.length + content.length);
fullContent.set(headerArray);
fullContent.set(content, headerArray.length);
const hasher = new CryptoHasher('sha1');
hasher.update(fullContent);
return hasher.digest('hex');
}
const fileHash = await getGitFileHash('default.sh');
console.log(fileHash);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment