FileHashManager.coffee 1010 B

1234567891011121314151617181920212223242526272829303132333435
  1. crypto = require "crypto"
  2. logger = require("logger-sharelatex")
  3. fs = require("fs")
  4. _ = require("underscore")
  5. module.exports = FileHashManager =
  6. computeHash: (filePath, callback = (error, hashValue) ->) ->
  7. callback = _.once(callback) # avoid double callbacks
  8. # taken from v1/history/storage/lib/blob_hash.js
  9. getGitBlobHeader = (byteLength) ->
  10. return 'blob ' + byteLength + '\x00'
  11. getByteLengthOfFile = (cb) ->
  12. fs.stat filePath, (err, stats) ->
  13. return cb(err) if err?
  14. cb(null, stats.size)
  15. getByteLengthOfFile (err, byteLength) ->
  16. return callback(err) if err?
  17. input = fs.createReadStream(filePath)
  18. input.on 'error', (err) ->
  19. logger.err {filePath: filePath, err:err}, "error opening file in computeHash"
  20. return callback(err)
  21. hash = crypto.createHash("sha1")
  22. hash.setEncoding('hex')
  23. hash.update(getGitBlobHeader(byteLength))
  24. hash.on 'readable', () ->
  25. result = hash.read()
  26. if result?
  27. callback(null, result.toString('hex'))
  28. input.pipe(hash)