all files / src/utils/FileTree/ index.js

16.74% Statements 37/221
5.56% Branches 6/108
18.18% Functions 6/33
17.37% Lines 37/213
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * 文件结构模块
 */
 
class FileTree {
  /**
   * 初始化文件结构
   * @param {object} options 配置参数 ()
   */
  constructor (options = {}) {
    this.rmEmpty = !!options.rmEmpty
 
    // 初始化
    this.fileCount = 0
    this.folderCount = 0
    this.allCount = 0
 
    this.files = []
    this.folders = []
    this.addFolder('.', {})
  }
 
  /**
   * 更新统计数据
   */
  updateCount () {
    let filesCount = 0
    let foldersCount = 0
 
    // 自调用迭代统计
    const traverseFolder = (folder) => {
      folder.folders.map(item => {
        traverseFolder(item)
        foldersCount++
      })
 
      filesCount += folder.files.length
    }
 
    traverseFolder(this.folders[0])
 
    this.filesCount = filesCount
    this.foldersCount = foldersCount
    this.allCount = this.filesCount + this.foldersCount
  }
 
  /**
   * 按标准格式化路径
   * @param {string} path 路径
   */
  formatPath (path = '') {
    Iif (typeof path !== 'string') {
      console.warn('[formatPath]: path is not valid')
      return false
    }
 
    // 去除多余空格,重复的/,首尾的/
    let newPath = path.trim()
    newPath = newPath.replace(/\/+/g, '/')
    newPath = newPath.replace(/\/$/, '')
    newPath = newPath.replace(/^\//, '')
    // 开头位置的'./'
    Iif (newPath !== '.' && newPath.search('./') !== 0) {
      newPath = './' + newPath
    }
 
    return newPath
  }
 
  /**
   * 增加文件夹
   * @param {string} path 路径
   * @param {object} data 数据
   * @return {object} 成功返回创建的文件夹/失败返回null
   */
  addFolder (path = '', data = {}) {
    Iif (typeof path !== 'string') {
      console.warn('[addFolder]: path is not valid')
      return null
    }
 
    Iif (typeof data !== 'object') {
      console.warn('[addFolder]: data is not valid')
      return null
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    let folders = this.folders
    let folder
 
    // 按照路径层层迭代, 在最后一层迭代时增加文件夹
    pathArr.map(item => {
      let find = folders.find(folder => item === folder.name)
      Iif (find) {
        folder = find
        folders = find.folders
      } else {
        folder = {
          folders: [],
          files: [],
          name: item
        }
 
        Object.assign(folder, data)
 
        folders.push(folder)
        folders = folder.folders
      }
    })
 
    // 更新统计数据
    this.updateCount()
 
    return folder
  }
 
  /**
   * 删除文件夹
   * @param {string} path 路径
   * @return {boolean} 成功或失败
   */
  rmFolder (path = '') {
    if (typeof path !== 'string') {
      console.warn('[rmFolder]: path is not valid')
      return false
    }
 
    const emptyFolder = folder => {
      let folders = folder.folders.concat()
      folders.map((item, index) => {
        emptyFolder(item)
        folder.folders.splice(index, 1)
 
        // 执行回调
        if (item.onRemove && typeof item.onRemove === 'function') {
          item.onRemove.call(this, item)
        }
      })
 
      let files = folder.files.concat()
      files.map((file, index) => {
        folder.files.splice(index, 1)
 
        // 执行回调
        if (file.onRemove && typeof file.onRemove === 'function') {
          file.onRemove.call(this, file)
        }
      })
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    // 将最后一级弹出来
    const pathLast = pathArr.pop()
 
    let folders = this.folders
    let folder
 
    // 按照路径层层迭代,false即退出循环
    pathArr.every(item => {
      let find = folders.find(folder => item === folder.name)
 
      if (find) {
        folder = find
        folders = find.folders
      } else {
        folder = null
        folders = null
      }
 
      return find
    })
 
    // 查找最后一级目录
    if (folder && folders) {
      let index = folders.findIndex(item => item.name === pathLast)
 
      // 存在则删除
      if (index !== -1) {
        let folder = folders[index]
 
        emptyFolder(folder)
        folders.splice(index, 1)
 
        // 执行回调
        if (folder.onRemove && typeof folder.onRemove === 'function') {
          folder.onRemove.call(this, folder)
        }
 
        // 根据配置决定是否删除空目录
        if (this.rmEmpty) {
          this.formatFolder()
        }
 
        // 更新统计数据
        this.updateCount()
 
        return true
      }
    }
 
    return false
  }
 
  /**
   * 获取文件夹
   * @param {string} path 路径
   * @return {object} 文件夹或者null
   */
  getFolder (path = '') {
    if (typeof path !== 'string') {
      console.warn('[getFolder]: path is not valid')
      return false
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    let folders = this.folders
    let folder
 
    // 按照路径层层迭代,false即退出循环
    for (const item of pathArr) {
      const index = folders.findIndex((folder) => item === folder.name)
 
      if (index !== -1) {
        folder = folders[index]
        folders = folder.folders
      } else {
        return null
      }
    }
 
    return folder
  }
 
  /**
   * 增加文件[增加路径中不存在的所有文件夹]
   * @param {string} path 路径
   * @param {object} data 添加的参数
   * @return {object} 成功返回创建的文件/失败返回null
   */
  addFile (path = '', data = {}) {
    if (typeof path !== 'string') {
      console.warn('[addFile]: path is not valid')
      return null
    }
 
    if (typeof data !== 'object') {
      console.warn('[addFile]: data is not valid')
      return null
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    // 将最后一级弹出来
    const pathLast = pathArr.pop()
 
    const folder = this.addFolder(pathArr.join('/'))
    const file = {
      name: pathLast
    }
 
    Object.assign(file, data)
    folder.files.push(file)
 
    // 更新统计数据
    this.updateCount()
 
    return file
  }
 
  /**
   * 删除文件
   * @param {string} path 路径
   * @return {boolean} 成功/失败
   */
  rmFile (path = '') {
    if (typeof path !== 'string') {
      console.warn('[rmFile]: path is not valid')
      return null
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    // 将最后一级弹出来
    const pathLast = pathArr.pop()
 
    let folders = this.folders
    let folder
 
    // 按照路径层层迭代,false即退出循环
    pathArr.every(item => {
      let find = folders.find(folder => item === folder.name)
 
      if (find) {
        folder = find
        folders = find.folders
      } else {
        folder = null
        folders = null
      }
 
      return find
    })
 
    // 查找最后一级目录
    if (folder && folders) {
      let index = folder.files.findIndex(item => item.name === pathLast)
 
      // 存在则删除
      if (index !== -1) {
        let file = folder.files[index]
 
        folder.files.splice(index, 1)
 
        // 执行回调
        if (file.onRemove && typeof file.onRemove === 'function') {
          file.onRemove.call(this, file)
        }
 
        // 根据配置决定是否删除空目录
        if (this.rmEmpty) {
          this.formatFolder()
        }
 
        // 更新统计数据
        this.updateCount()
 
        return true
      }
    }
 
    return false
  }
 
  /**
   * 获取文件
   * @param {string} 文件路径
   * @return {object} 文件或者null
   */
  getFile (path = '') {
    if (typeof path !== 'string') {
      console.warn('[getFile]: path is not valid')
      return null
    }
 
    // 将文件路径分级
    const newPath = this.formatPath(path)
    const pathArr = newPath.split('/')
 
    // 将最后一级弹出来
    const pathLast = pathArr.pop()
 
    let folders = this.folders
    let folder
 
    // 按照路径层层迭代,false即退出循环
    pathArr.every(item => {
      let find = folders.find(folder => item === folder.name)
 
      if (find) {
        folder = find
        folders = find.folders
      } else {
        folder = null
        folders = null
      }
 
      return find
    })
 
    // 查找最后一级目录
    if (folder && folders) {
      let index = folder.files.findIndex(item => item.name === pathLast)
 
      // 存在则返回
      if (index !== -1) {
        const file = folder.files[index]
 
        return file
      }
    }
 
    return null
  }
 
  /**
   * 删除空目录
   * @return {number} 删除掉的目录个数
   */
  formatFolder () {
    let retCount = 0
 
    const removeFolder = folder => {
      let folders = folder.folders.concat()
 
      folders.map((item, index) => {
        if (removeFolder(item)) {
          // 可以删除
          retCount++
          folder.folders.splice(index, 1)
 
          // 执行回调
          if (item.onRemove && typeof item.onRemove === 'function') {
            item.onRemove.call(this, item)
          }
        }
      })
 
      // 文件夹内空则返回true,否则返回false
      return (folder.folders.length === 0 && folder.files.length === 0)
    }
 
    // 从./开始嵌套
    removeFolder(this.folders[0])
 
    // 更新统计数据
    this.updateCount()
 
    return retCount
  }
 
  /**
   * 获取树形结构
   * @params {boolean} toLog 打印到log输出
   * @return {string} 树形结构
   */
  getTree (toLog = false) {
    const depth = 0
 
    let tree = ''
 
    const folder2tree = (folder, depth, last = []) => {
      folder.folders.map((item, index, arr) => {
        tree += ('\n')
 
        for (let j = 0; j < depth; j++) {
          if (j === depth - 1) {
            if (index === arr.length - 1 && arr.length === 0) {
              tree += (' └')
            } else {
              tree += (' ├')
            }
          } else {
            if (last[j]) {
              tree += ('  ')
            } else {
              tree += (' |')
            }
          }
        }
 
        tree += '-'
        tree += item.name
        tree += '/'
 
        last.push(index === arr.length - 1 && arr.length === 0)
 
        folder2tree(item, depth + 1, last)
      })
 
      folder.files.map((item, index, arr) => {
        tree += ('\n')
 
        for (let j = 0; j < depth; j++) {
          if (j === depth - 1) {
            if (index === arr.length - 1) {
              tree += (' └')
            } else {
              tree += (' ├')
            }
          } else {
            if (last[j]) {
              tree += ('  ')
            } else {
              tree += (' |')
            }
          }
        }
 
        tree += '-'
        tree += item.name
      })
    }
 
    tree += '.'
    tree += '/'
    folder2tree(this.folders[0], depth + 1)
 
    // 打印
    if (toLog) {
      console.log(...[tree])
    }
 
    return tree
  }
}
 
export default FileTree