ProjectHelper.coffee 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ENGINE_TO_COMPILER_MAP = {
  2. latex_dvipdf: "latex"
  3. pdflatex: "pdflatex"
  4. xelatex: "xelatex"
  5. lualatex: "lualatex"
  6. }
  7. module.exports = ProjectHelper =
  8. compilerFromV1Engine: (engine) ->
  9. return ENGINE_TO_COMPILER_MAP[engine]
  10. ensureNameIsUnique: (nameList, name, suffixes = [], maxLength, callback = (error, name, changed)->) ->
  11. # create a set of all project names
  12. allNames = new Set(nameList)
  13. isUnique = (x) -> !allNames.has(x)
  14. # check if the supplied name is already unique
  15. if isUnique(name)
  16. return callback(null, name, false)
  17. # the name already exists, try adding the user-supplied suffixes to generate a unique name
  18. for suffix in suffixes
  19. candidateName = ProjectHelper._addSuffixToProjectName(name, suffix, maxLength)
  20. if isUnique(candidateName)
  21. return callback(null, candidateName, true)
  22. # if there are no (more) suffixes, use a numeric one
  23. uniqueName = ProjectHelper._addNumericSuffixToProjectName(name, allNames, maxLength)
  24. if uniqueName?
  25. callback(null, uniqueName, true)
  26. else
  27. callback(new Error("Failed to generate a unique name for: #{name}"))
  28. _addSuffixToProjectName: (name, suffix = '', maxLength) ->
  29. # append the suffix and truncate the project title if needed
  30. truncatedLength = maxLength - suffix.length
  31. return name.substr(0, truncatedLength) + suffix
  32. _addNumericSuffixToProjectName: (name, allProjectNames, maxLength) ->
  33. NUMERIC_SUFFIX_MATCH = / \((\d+)\)$/
  34. suffixedName = (basename, number) ->
  35. suffix = " (#{number})"
  36. return basename.substr(0, maxLength - suffix.length) + suffix
  37. match = name.match(NUMERIC_SUFFIX_MATCH)
  38. basename = name
  39. n = 1
  40. last = allProjectNames.size + n
  41. if match?
  42. basename = name.replace(NUMERIC_SUFFIX_MATCH, '')
  43. n = parseInt(match[1])
  44. while n <= last
  45. candidate = suffixedName(basename, n)
  46. return candidate unless allProjectNames.has(candidate)
  47. n += 1
  48. return null