HashManager.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 _ from 'lodash'
  16. import logger from '@overleaf/logger'
  17. import OError from '@overleaf/o-error'
  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. if (_callback == null) {
  29. _callback = function () {}
  30. }
  31. const callback = _.once(_callback)
  32. return fs.stat(fsPath, function (err, stats) {
  33. if (err != null) {
  34. OError.tag(err, 'failed to stat file in _getBlobHash', { fsPath })
  35. return callback(err)
  36. }
  37. const byteLength = stats.size
  38. const hash = crypto.createHash('sha1')
  39. hash.setEncoding('hex')
  40. hash.update('blob ' + byteLength + '\x00')
  41. const stream = fs.createReadStream(fsPath)
  42. stream.on('error', function (err) {
  43. return callback(
  44. OError.tag(err, 'error streaming file from disk', {
  45. fsPath,
  46. byteLength,
  47. })
  48. )
  49. })
  50. stream.on('end', function () {
  51. hash.end()
  52. return callback(null, hash.read(), byteLength)
  53. })
  54. return stream.pipe(hash)
  55. })
  56. }