file_map.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. 'use strict'
  2. const _ = require('lodash')
  3. const assert = require('check-types').assert
  4. const OError = require('@overleaf/o-error')
  5. const pMap = require('p-map')
  6. const File = require('./file')
  7. const safePathname = require('./safe_pathname')
  8. class PathnameError extends OError {}
  9. class NonUniquePathnameError extends PathnameError {
  10. constructor(pathnames) {
  11. super('pathnames are not unique: ' + pathnames, { pathnames })
  12. this.pathnames = pathnames
  13. }
  14. }
  15. class BadPathnameError extends PathnameError {
  16. constructor(pathname) {
  17. super(pathname + ' is not a valid pathname', { pathname })
  18. this.pathname = pathname
  19. }
  20. }
  21. class PathnameConflictError extends PathnameError {
  22. constructor(pathname) {
  23. super(`pathname '${pathname}' conflicts with another file`, { pathname })
  24. this.pathname = pathname
  25. }
  26. }
  27. class FileNotFoundError extends PathnameError {
  28. constructor(pathname) {
  29. super(`file ${pathname} does not exist`, { pathname })
  30. this.pathname = pathname
  31. }
  32. }
  33. /**
  34. * A set of {@link File}s. Several properties are enforced on the pathnames:
  35. *
  36. * 1. File names and paths are case sensitive and can differ by case alone. This
  37. * is consistent with most Linux file systems, but it is not consistent with
  38. * Windows or OS X. Ideally, we would be case-preserving and case insensitive,
  39. * like they are. And we used to be, but it caused too many incompatibilities
  40. * with the old system, which was case sensitive. See
  41. * https://github.com/overleaf/overleaf-ot-prototype/blob/
  42. * 19ed046c09f5a4d14fa12b3ea813ce0d977af88a/editor/core/lib/file_map.js
  43. * for an implementation of this map with those properties.
  44. *
  45. * 2. Uniqueness: No two pathnames are the same.
  46. *
  47. * 3. No type conflicts: A pathname cannot refer to both a file and a directory
  48. * within the same snapshot. That is, you can't have pathnames `a` and `a/b` in
  49. * the same file map; {@see FileMap#wouldConflict}.
  50. */
  51. class FileMap {
  52. static PathnameError = PathnameError
  53. static NonUniquePathnameError = NonUniquePathnameError
  54. static BadPathnameError = BadPathnameError
  55. static PathnameConflictError = PathnameConflictError
  56. static FileNotFoundError = FileNotFoundError
  57. /**
  58. * @param {Object.<String, File>} files
  59. */
  60. constructor(files) {
  61. // create bare object for use as Map
  62. // http://ryanmorr.com/true-hash-maps-in-javascript/
  63. this.files = Object.create(null)
  64. _.assign(this.files, files)
  65. checkPathnamesAreUnique(this.files)
  66. checkPathnamesDoNotConflict(this)
  67. }
  68. static fromRaw(raw) {
  69. assert.object(raw, 'bad raw files')
  70. return new FileMap(_.mapValues(raw, File.fromRaw))
  71. }
  72. /**
  73. * Convert to raw object for serialization.
  74. *
  75. * @return {Object}
  76. */
  77. toRaw() {
  78. function fileToRaw(file) {
  79. return file.toRaw()
  80. }
  81. return _.mapValues(this.files, fileToRaw)
  82. }
  83. /**
  84. * Create the given file.
  85. *
  86. * @param {string} pathname
  87. * @param {File} file
  88. */
  89. addFile(pathname, file) {
  90. checkPathname(pathname)
  91. assert.object(file, 'bad file')
  92. checkNewPathnameDoesNotConflict(this, pathname)
  93. addFile(this.files, pathname, file)
  94. }
  95. /**
  96. * Remove the given file.
  97. *
  98. * @param {string} pathname
  99. */
  100. removeFile(pathname) {
  101. checkPathname(pathname)
  102. const key = findPathnameKey(this.files, pathname)
  103. if (!key) {
  104. throw new FileMap.FileNotFoundError(pathname)
  105. }
  106. delete this.files[key]
  107. }
  108. /**
  109. * Move or remove a file. If the origin file does not exist, or if the old
  110. * and new paths are identical, this has no effect.
  111. *
  112. * @param {string} pathname
  113. * @param {string} newPathname if a blank string, {@link FileMap#removeFile}
  114. */
  115. moveFile(pathname, newPathname) {
  116. if (pathname === newPathname) return
  117. if (newPathname === '') return this.removeFile(pathname)
  118. checkPathname(pathname)
  119. checkPathname(newPathname)
  120. checkNewPathnameDoesNotConflict(this, newPathname, pathname)
  121. const key = findPathnameKey(this.files, pathname)
  122. if (!key) {
  123. throw new FileMap.FileNotFoundError(pathname)
  124. }
  125. const file = this.files[key]
  126. delete this.files[key]
  127. addFile(this.files, newPathname, file)
  128. }
  129. /**
  130. * The number of files in the file map.
  131. *
  132. * @return {number}
  133. */
  134. countFiles() {
  135. return _.size(this.files)
  136. }
  137. /**
  138. * Get a file by its pathname.
  139. *
  140. * @param {string} pathname
  141. * @return {File | null | undefined}
  142. */
  143. getFile(pathname) {
  144. const key = findPathnameKey(this.files, pathname)
  145. return key && this.files[key]
  146. }
  147. /**
  148. * Whether the given pathname conflicts with any file in the map.
  149. *
  150. * Paths conflict in type if one path is a strict prefix of the other path. For
  151. * example, 'a/b' conflicts with 'a', because in the former case 'a' is a
  152. * folder, but in the latter case it is a file. Similarly, the pathname 'a/b/c'
  153. * conflicts with 'a' and 'a/b', but it does not conflict with 'a/b/c', 'a/x',
  154. * or 'a/b/x'. (In our case, identical paths don't conflict, because AddFile
  155. * and MoveFile overwrite existing files.)
  156. *
  157. * @param {string} pathname
  158. * @param {string} [ignoredPathname] pretend this pathname does not exist
  159. */
  160. wouldConflict(pathname, ignoredPathname) {
  161. checkPathname(pathname)
  162. assert.maybe.string(ignoredPathname)
  163. const pathnames = this.getPathnames()
  164. const dirname = pathname + '/'
  165. // Check the filemap to see whether the supplied pathname is a
  166. // parent of any entry, or any entry is a parent of the pathname.
  167. for (let i = 0; i < pathnames.length; i++) {
  168. // First check if pathname is a strict prefix of pathnames[i] (and that
  169. // pathnames[i] is not ignored)
  170. if (
  171. pathnames[i].startsWith(dirname) &&
  172. !pathnamesEqual(pathnames[i], ignoredPathname)
  173. ) {
  174. return true
  175. }
  176. // Now make the reverse check, whether pathnames[i] is a strict prefix of
  177. // pathname. To avoid expensive string concatenation on each pathname we
  178. // first perform a partial check with a.startsWith(b), and then do the
  179. // full check for a subsequent '/' if this passes. This saves about 25%
  180. // of the runtime. Again only return a conflict if pathnames[i] is not
  181. // ignored.
  182. if (
  183. pathname.startsWith(pathnames[i]) &&
  184. pathname.length > pathnames[i].length &&
  185. pathname[pathnames[i].length] === '/' &&
  186. !pathnamesEqual(pathnames[i], ignoredPathname)
  187. ) {
  188. return true
  189. }
  190. }
  191. // No conflicts - after excluding ignoredPathname, there were no entries
  192. // which were a strict prefix of pathname, and pathname was not a strict
  193. // prefix of any entry.
  194. return false
  195. }
  196. /** @see Snapshot#getFilePathnames */
  197. getPathnames() {
  198. return _.keys(this.files)
  199. }
  200. /**
  201. * Map the files in this map to new values.
  202. * @param {function} iteratee
  203. * @return {Object}
  204. */
  205. map(iteratee) {
  206. return _.mapValues(this.files, iteratee)
  207. }
  208. /**
  209. * Map the files in this map to new values asynchronously, with an optional
  210. * limit on concurrency.
  211. * @param {function} iteratee like for _.mapValues
  212. * @param {number} [concurrency]
  213. * @return {Promise<Object>}
  214. */
  215. async mapAsync(iteratee, concurrency) {
  216. assert.maybe.number(concurrency, 'bad concurrency')
  217. const pathnames = this.getPathnames()
  218. const files = await pMap(
  219. pathnames,
  220. file => {
  221. return iteratee(this.getFile(file), file, pathnames)
  222. },
  223. { concurrency: concurrency || 1 }
  224. )
  225. return _.zipObject(pathnames, files)
  226. }
  227. }
  228. function pathnamesEqual(pathname0, pathname1) {
  229. return pathname0 === pathname1
  230. }
  231. function pathnamesAreUnique(files) {
  232. const keys = _.keys(files)
  233. return _.uniqWith(keys, pathnamesEqual).length === keys.length
  234. }
  235. function checkPathnamesAreUnique(files) {
  236. if (pathnamesAreUnique(files)) return
  237. throw new FileMap.NonUniquePathnameError(_.keys(files))
  238. }
  239. function checkPathname(pathname) {
  240. assert.nonEmptyString(pathname, 'bad pathname')
  241. if (safePathname.isClean(pathname)) return
  242. throw new FileMap.BadPathnameError(pathname)
  243. }
  244. function checkNewPathnameDoesNotConflict(fileMap, pathname, ignoredPathname) {
  245. if (fileMap.wouldConflict(pathname, ignoredPathname)) {
  246. throw new FileMap.PathnameConflictError(pathname)
  247. }
  248. }
  249. function checkPathnamesDoNotConflict(fileMap) {
  250. const pathnames = fileMap.getPathnames()
  251. // check pathnames for validity first
  252. pathnames.forEach(checkPathname)
  253. // convert pathnames to candidate directory names
  254. const dirnames = []
  255. for (let i = 0; i < pathnames.length; i++) {
  256. dirnames[i] = pathnames[i] + '/'
  257. }
  258. // sort in lexical order and check if one directory contains another
  259. dirnames.sort()
  260. for (let i = 0; i < dirnames.length - 1; i++) {
  261. if (dirnames[i + 1].startsWith(dirnames[i])) {
  262. // strip trailing slash to get original pathname
  263. const conflictPathname = dirnames[i + 1].substr(0, -1)
  264. throw new FileMap.PathnameConflictError(conflictPathname)
  265. }
  266. }
  267. }
  268. //
  269. // This function is somewhat vestigial: it was used when this map used
  270. // case-insensitive pathname comparison. We could probably simplify some of the
  271. // logic in the callers, but in the hope that we will one day return to
  272. // case-insensitive semantics, we've just left things as-is for now.
  273. //
  274. function findPathnameKey(files, pathname) {
  275. // we can check for the key without worrying about properties
  276. // in the prototype because we are now using a bare object/
  277. if (pathname in files) return pathname
  278. }
  279. function addFile(files, pathname, file) {
  280. const key = findPathnameKey(files, pathname)
  281. if (key) delete files[key]
  282. files[pathname] = file
  283. }
  284. module.exports = FileMap