Last active
August 4, 2024 06:55
-
-
Save Avaray/23bd3f5214ee8c945f7f164875cd0ff6 to your computer and use it in GitHub Desktop.
Bun.sh - function to get GitHub-style hash for file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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