asar.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. 'use strict'
  2. const fs = process.versions.electron ? require('original-fs') : require('fs')
  3. const path = require('path')
  4. const minimatch = require('minimatch')
  5. const mkdirp = require('mkdirp')
  6. const Filesystem = require('./filesystem')
  7. const disk = require('./disk')
  8. const crawlFilesystem = require('./crawlfs')
  9. const createSnapshot = require('./snapshot')
  10. // Return whether or not a directory should be excluded from packing due to
  11. // "--unpack-dir" option
  12. //
  13. // @param {string} path - diretory path to check
  14. // @param {string} pattern - literal prefix [for backward compatibility] or glob pattern
  15. // @param {array} unpackDirs - Array of directory paths previously marked as unpacked
  16. //
  17. const isUnpackDir = function (path, pattern, unpackDirs) {
  18. if (path.indexOf(pattern) === 0 || minimatch(path, pattern)) {
  19. if (unpackDirs.indexOf(path) === -1) {
  20. unpackDirs.push(path)
  21. }
  22. return true
  23. } else {
  24. for (let i = 0; i < unpackDirs.length; i++) {
  25. if (path.indexOf(unpackDirs[i]) === 0) {
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. }
  32. module.exports.createPackage = function (src, dest, callback) {
  33. return module.exports.createPackageWithOptions(src, dest, {}, callback)
  34. }
  35. module.exports.createPackageWithOptions = function (src, dest, options, callback) {
  36. const globOptions = options.globOptions ? options.globOptions : {}
  37. globOptions.dot = options.dot === undefined ? true : options.dot
  38. let pattern = src + '/**/*'
  39. if (options.pattern) {
  40. pattern = src + options.pattern
  41. }
  42. return crawlFilesystem(pattern, globOptions, function (error, filenames, metadata) {
  43. if (error) { return callback(error) }
  44. module.exports.createPackageFromFiles(src, dest, filenames, metadata, options, callback)
  45. })
  46. }
  47. /*
  48. createPackageFromFiles - Create an asar-archive from a list of filenames
  49. src: Base path. All files are relative to this.
  50. dest: Archive filename (& path).
  51. filenames: Array of filenames relative to src.
  52. metadata: Object with filenames as keys and {type='directory|file|link', stat: fs.stat} as values. (Optional)
  53. options: The options.
  54. callback: The callback function. Accepts (err).
  55. */
  56. module.exports.createPackageFromFiles = function (src, dest, filenames, metadata, options, callback) {
  57. if (typeof metadata === 'undefined' || metadata === null) { metadata = {} }
  58. const filesystem = new Filesystem(src)
  59. const files = []
  60. const unpackDirs = []
  61. let filenamesSorted = []
  62. if (options.ordering) {
  63. const orderingFiles = fs.readFileSync(options.ordering).toString().split('\n').map(function (line) {
  64. if (line.includes(':')) { line = line.split(':').pop() }
  65. line = line.trim()
  66. if (line.startsWith('/')) { line = line.slice(1) }
  67. return line
  68. })
  69. const ordering = []
  70. for (const file of orderingFiles) {
  71. const pathComponents = file.split(path.sep)
  72. let str = src
  73. for (const pathComponent of pathComponents) {
  74. str = path.join(str, pathComponent)
  75. ordering.push(str)
  76. }
  77. }
  78. let missing = 0
  79. const total = filenames.length
  80. for (const file of ordering) {
  81. if (!filenamesSorted.includes(file) && filenames.includes(file)) {
  82. filenamesSorted.push(file)
  83. }
  84. }
  85. for (const file of filenames) {
  86. if (!filenamesSorted.includes(file)) {
  87. filenamesSorted.push(file)
  88. missing += 1
  89. }
  90. }
  91. console.log(`Ordering file has ${((total - missing) / total) * 100}% coverage.`)
  92. } else {
  93. filenamesSorted = filenames
  94. }
  95. const handleFile = function (filename, done) {
  96. let file = metadata[filename]
  97. let type
  98. if (!file) {
  99. const stat = fs.lstatSync(filename)
  100. if (stat.isDirectory()) { type = 'directory' }
  101. if (stat.isFile()) { type = 'file' }
  102. if (stat.isSymbolicLink()) { type = 'link' }
  103. file = {stat, type}
  104. }
  105. let shouldUnpack
  106. switch (file.type) {
  107. case 'directory':
  108. shouldUnpack = options.unpackDir
  109. ? isUnpackDir(path.relative(src, filename), options.unpackDir, unpackDirs)
  110. : false
  111. filesystem.insertDirectory(filename, shouldUnpack)
  112. break
  113. case 'file':
  114. shouldUnpack = false
  115. if (options.unpack) {
  116. shouldUnpack = minimatch(filename, options.unpack, {matchBase: true})
  117. }
  118. if (!shouldUnpack && options.unpackDir) {
  119. const dirName = path.relative(src, path.dirname(filename))
  120. shouldUnpack = isUnpackDir(dirName, options.unpackDir, unpackDirs)
  121. }
  122. files.push({filename: filename, unpack: shouldUnpack})
  123. filesystem.insertFile(filename, shouldUnpack, file, options, done)
  124. return
  125. case 'link':
  126. filesystem.insertLink(filename, file.stat)
  127. break
  128. }
  129. return process.nextTick(done)
  130. }
  131. const insertsDone = function () {
  132. return mkdirp(path.dirname(dest), function (error) {
  133. if (error) { return callback(error) }
  134. return disk.writeFilesystem(dest, filesystem, files, metadata, function (error) {
  135. if (error) { return callback(error) }
  136. if (options.snapshot) {
  137. return createSnapshot(src, dest, filenames, metadata, options, callback)
  138. } else {
  139. return callback(null)
  140. }
  141. })
  142. })
  143. }
  144. const names = filenamesSorted.slice()
  145. const next = function (name) {
  146. if (!name) { return insertsDone() }
  147. return handleFile(name, function () {
  148. return next(names.shift())
  149. })
  150. }
  151. return next(names.shift())
  152. }
  153. module.exports.statFile = function (archive, filename, followLinks) {
  154. const filesystem = disk.readFilesystemSync(archive)
  155. return filesystem.getFile(filename, followLinks)
  156. }
  157. module.exports.listPackage = function (archive) {
  158. return disk.readFilesystemSync(archive).listFiles()
  159. }
  160. module.exports.extractFile = function (archive, filename) {
  161. const filesystem = disk.readFilesystemSync(archive)
  162. return disk.readFileSync(filesystem, filename, filesystem.getFile(filename))
  163. }
  164. module.exports.extractAll = function (archive, dest) {
  165. const filesystem = disk.readFilesystemSync(archive)
  166. const filenames = filesystem.listFiles()
  167. // under windows just extract links as regular files
  168. const followLinks = process.platform === 'win32'
  169. // create destination directory
  170. mkdirp.sync(dest)
  171. return filenames.map((filename) => {
  172. filename = filename.substr(1) // get rid of leading slash
  173. const destFilename = path.join(dest, filename)
  174. const file = filesystem.getFile(filename, followLinks)
  175. if (file.files) {
  176. // it's a directory, create it and continue with the next entry
  177. mkdirp.sync(destFilename)
  178. } else if (file.link) {
  179. // it's a symlink, create a symlink
  180. const linkSrcPath = path.dirname(path.join(dest, file.link))
  181. const linkDestPath = path.dirname(destFilename)
  182. const relativePath = path.relative(linkDestPath, linkSrcPath);
  183. // try to delete output file, because we can't overwrite a link
  184. (() => {
  185. try {
  186. fs.unlinkSync(destFilename)
  187. } catch (error) {}
  188. })()
  189. const linkTo = path.join(relativePath, path.basename(file.link))
  190. fs.symlinkSync(linkTo, destFilename)
  191. } else {
  192. // it's a file, extract it
  193. const content = disk.readFileSync(filesystem, filename, file)
  194. fs.writeFileSync(destFilename, content)
  195. }
  196. })
  197. }
  198. module.exports.uncache = function (archive) {
  199. return disk.uncacheFilesystem(archive)
  200. }
  201. module.exports.uncacheAll = function () {
  202. disk.uncacheAll()
  203. }