HashManager.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* eslint-disable
  2. no-undef,
  3. no-unused-vars,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. import { promisify } from 'node:util'
  14. import fs from 'node:fs'
  15. import crypto from 'node:crypto'
  16. import OError from '@overleaf/o-error'
  17. import { pipeline } from 'node:stream'
  18. export function _getBlobHashFromString(string) {
  19. const byteLength = Buffer.byteLength(string)
  20. const hash = crypto.createHash('sha1')
  21. hash.setEncoding('hex')
  22. hash.update('blob ' + byteLength + '\x00')
  23. hash.update(string, 'utf8')
  24. hash.end()
  25. return hash.read()
  26. }
  27. export function _getBlobHash(fsPath, callback) {
  28. return fs.stat(fsPath, function (err, stats) {
  29. if (err != null) {
  30. OError.tag(err, 'failed to stat file in _getBlobHash', { fsPath })
  31. return callback(err)
  32. }
  33. const byteLength = stats.size
  34. const hash = crypto.createHash('sha1')
  35. hash.setEncoding('hex')
  36. hash.update('blob ' + byteLength + '\x00')
  37. pipeline(fs.createReadStream(fsPath), hash, err => {
  38. if (err) {
  39. callback(
  40. OError.tag(err, 'error streaming file from disk', {
  41. fsPath,
  42. byteLength,
  43. })
  44. )
  45. } else {
  46. hash.end()
  47. callback(null, hash.read(), byteLength)
  48. }
  49. })
  50. })
  51. }
  52. export const promises = {
  53. _getBlobHash: promisify(_getBlobHash),
  54. }