DiffManager.coffee 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. UpdatesManager = require "./UpdatesManager"
  2. DocumentUpdaterManager = require "./DocumentUpdaterManager"
  3. DiffGenerator = require "./DiffGenerator"
  4. logger = require "logger-sharelatex"
  5. module.exports = DiffManager =
  6. getLatestDocAndUpdates: (project_id, doc_id, fromVersion, toVersion, callback = (error, lines, version, updates) ->) ->
  7. UpdatesManager.getUpdatesWithUserInfo doc_id, from: fromVersion, to: toVersion, (error, updates) ->
  8. return callback(error) if error?
  9. DocumentUpdaterManager.getDocument project_id, doc_id, (error, lines, version) ->
  10. return callback(error) if error?
  11. callback(null, lines, version, updates)
  12. getDiff: (project_id, doc_id, fromVersion, toVersion, callback = (error, diff) ->) ->
  13. logger.log project_id: project_id, doc_id: doc_id, from: fromVersion, to: toVersion, "getting diff"
  14. DiffManager.getLatestDocAndUpdates project_id, doc_id, fromVersion, null, (error, lines, version, updates) ->
  15. return callback(error) if error?
  16. logger.log lines: lines, version: version, updates: updates, "got doc and updates"
  17. lastUpdate = updates[0]
  18. if lastUpdate? and lastUpdate.v != version - 1
  19. return callback new Error("latest update version, #{lastUpdate.v}, does not match doc version, #{version}")
  20. updatesToApply = []
  21. for update in updates.reverse()
  22. if update.v <= toVersion
  23. updatesToApply.push update
  24. logger.log project_id: project_id, doc_id: doc_id, updatesToApply: updatesToApply, "got updates to apply"
  25. try
  26. startingContent = DiffGenerator.rewindUpdates lines.join("\n"), updates
  27. logger.log project_id: project_id, doc_id: doc_id, startingContent: startingContent, "rewound doc"
  28. diff = DiffGenerator.buildDiff startingContent, updatesToApply
  29. catch e
  30. return callback(e)
  31. callback(null, diff)