overleaf/services/web/app/coffee/Features/FileStore/FileHashManager.coffee
Brian Gough 07b7566466 Merge pull request #1089 from overleaf/bg-compute-filestore-hash
compute filestore hash

GitOrigin-RevId: 23a909d2c2ea7aba3abfdb8f0c060e414a17e52e
2019-05-13 08:49:42 +00:00

35 lines
No EOL
1,010 B
CoffeeScript

crypto = require "crypto"
logger = require("logger-sharelatex")
fs = require("fs")
_ = require("underscore")
module.exports = FileHashManager =
computeHash: (filePath, callback = (error, hashValue) ->) ->
callback = _.once(callback) # avoid double callbacks
# taken from v1/history/storage/lib/blob_hash.js
getGitBlobHeader = (byteLength) ->
return 'blob ' + byteLength + '\x00'
getByteLengthOfFile = (cb) ->
fs.stat filePath, (err, stats) ->
return cb(err) if err?
cb(null, stats.size)
getByteLengthOfFile (err, byteLength) ->
return callback(err) if err?
input = fs.createReadStream(filePath)
input.on 'error', (err) ->
logger.err {filePath: filePath, err:err}, "error opening file in computeHash"
return callback(err)
hash = crypto.createHash("sha1")
hash.setEncoding('hex')
hash.update(getGitBlobHeader(byteLength))
hash.on 'readable', () ->
result = hash.read()
if result?
callback(null, result.toString('hex'))
input.pipe(hash)