liudong
2023-05-29 340f156319b863525e50e900c58e59b86ecb3d5e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
 * @module file-set
 */
 
const glob = require('glob')
const arrayify = require('array-back')
 
/**
 * @param {string | string[]} - One or more file paths or glob expressions to inspect.
 * @alias module:file-set
 */
class FileSet {
  constructor (patternList) {
    /**
     * The existing files found
     * @type {string[]}
     */
    this.files = []
 
    /**
     * The existing directories found
     * @type {string[]}
     */
    this.dirs = []
 
    /**
     * Paths which were not found
     * @type {string[]}
     */
    this.notExisting = []
 
    this.add(patternList)
  }
 
  /**
   * Add file patterns to the set.
   * @param files {string|string[]} - One or more file paths or glob expressions to inspect.
   */
  add (files) {
    const fs = require('fs')
 
    files = arrayify(files)
    for (const file of files) {
      try {
        const stat = fs.statSync(file)
        if (stat.isFile()) {
          if (this.files.indexOf(file) === -1) this.files.push(file)
        } else if (stat.isDirectory()) {
          if (this.dirs.indexOf(file) === -1) this.dirs.push(file)
        }
      } catch (err) {
        if (err.code === 'ENOENT') {
          const found = glob.sync(file, { mark: true })
          if (found.length) {
            for (const match of found) {
              if (match.endsWith('/')) {
                if (this.dirs.indexOf(match) === -1) this.dirs.push(match)
              } else {
                if (this.files.indexOf(match) === -1) this.files.push(match)
              }
            }
          } else {
            if (this.notExisting.indexOf(file) === -1) this.notExisting.push(file)
          }
        } else {
          throw err
        }
      }
    }
  }
}
 
module.exports = FileSet