HashManager.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 fs from 'fs'
  14. import crypto from 'crypto'
  15. import OError from '@overleaf/o-error'
  16. import { pipeline } from 'stream'
  17. export function _getBlobHashFromString(string) {
  18. const byteLength = Buffer.byteLength(string)
  19. const hash = crypto.createHash('sha1')
  20. hash.setEncoding('hex')
  21. hash.update('blob ' + byteLength + '\x00')
  22. hash.update(string, 'utf8')
  23. hash.end()
  24. return hash.read()
  25. }
  26. export function _getBlobHash(fsPath, callback) {
  27. return fs.stat(fsPath, function (err, stats) {
  28. if (err != null) {
  29. OError.tag(err, 'failed to stat file in _getBlobHash', { fsPath })
  30. return callback(err)
  31. }
  32. const byteLength = stats.size
  33. const hash = crypto.createHash('sha1')
  34. hash.setEncoding('hex')
  35. hash.update('blob ' + byteLength + '\x00')
  36. pipeline(fs.createReadStream(fsPath), hash, err => {
  37. if (err) {
  38. callback(
  39. OError.tag(err, 'error streaming file from disk', {
  40. fsPath,
  41. byteLength,
  42. })
  43. )
  44. } else {
  45. hash.end()
  46. callback(null, hash.read(), byteLength)
  47. }
  48. })
  49. })
  50. }