ProjectRootDocManager.coffee 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. ProjectEntityHandler = require "./ProjectEntityHandler"
  2. ProjectEntityUpdateHandler = require "./ProjectEntityUpdateHandler"
  3. Path = require "path"
  4. async = require("async")
  5. _ = require("underscore")
  6. module.exports = ProjectRootDocManager =
  7. setRootDocAutomatically: (project_id, callback = (error) ->) ->
  8. ProjectEntityHandler.getAllDocs project_id, (error, docs) ->
  9. return callback(error) if error?
  10. root_doc_id = null
  11. jobs = _.map docs, (doc, path)->
  12. return (cb)->
  13. rootDocId = null
  14. for line in doc.lines || []
  15. # We've had problems with this regex locking up CPU.
  16. # Previously /.*\\documentclass/ would totally lock up on lines of 500kb (data text files :()
  17. # This regex will only look from the start of the line, including whitespace so will return quickly
  18. # regardless of line length.
  19. match = /^\s*\\documentclass/.test(line)
  20. isRootDoc = /\.R?tex$/.test(Path.extname(path)) and match
  21. if isRootDoc
  22. rootDocId = doc?._id
  23. cb(rootDocId)
  24. async.series jobs, (root_doc_id)->
  25. if root_doc_id?
  26. ProjectEntityUpdateHandler.setRootDoc project_id, root_doc_id, callback
  27. else
  28. callback()
  29. setRootDocFromName: (project_id, rootDocName, callback = (error) ->) ->
  30. ProjectEntityHandler.getAllDocPathsFromProjectById project_id, (error, docPaths) ->
  31. return callback(error) if error?
  32. # find the root doc from the filename
  33. root_doc_id = null
  34. for doc_id, path of docPaths
  35. # docpaths have a leading / so allow matching "folder/filename" and "/folder/filename"
  36. if path == rootDocName or path == "/#{rootDocName}"
  37. root_doc_id = doc_id
  38. # try a basename match if there was no match
  39. if !root_doc_id
  40. for doc_id, path of docPaths
  41. if Path.basename(path) == Path.basename(rootDocName)
  42. root_doc_id = doc_id
  43. # set the root doc id if we found a match
  44. if root_doc_id?
  45. ProjectEntityUpdateHandler.setRootDoc project_id, root_doc_id, callback
  46. else
  47. callback()