123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- 'use strict'
- const fs = require('fs')
- const path = require('path')
- const debug = require('debug')('joystream:util:fs:walk')
- class Walker {
- constructor(archive, base, cb) {
- this.archive = archive
- this.base = base
- this.slice_offset = this.base.length
- if (this.base[this.slice_offset - 1] !== '/') {
- this.slice_offset += 1
- }
- this.cb = cb
- this.pending = 0
- }
-
- checkPending(name) {
-
- this.pending -= 1
- debug('Finishing', name, 'decreases pending to', this.pending)
- if (!this.pending) {
- debug('No more pending.')
- this.cb(null)
- }
- }
-
- reportAndRecurse(relname, fname, lstat, linktarget) {
-
- this.cb(null, relname, lstat, linktarget)
-
- if (lstat.isDirectory()) {
- this.walk(fname)
- }
- this.checkPending(fname)
- }
- walk(dir) {
-
-
-
-
-
-
-
-
- this.pending += 1
- this.archive.readdir(dir, (err, files) => {
- if (err) {
- this.cb(err)
- return
- }
-
- this.pending += files.length
- debug('Reading', dir, 'bumps pending to', this.pending)
- files.forEach(name => {
- const fname = path.resolve(dir, name)
- this.archive.lstat(fname, (err2, lstat) => {
- if (err2) {
- this.cb(err2)
- return
- }
-
- const relname = fname.slice(this.slice_offset)
-
- if (lstat.isSymbolicLink()) {
- this.archive.readlink(fname, (err3, linktarget) => {
- if (err3) {
- this.cb(err3)
- return
- }
- this.reportAndRecurse(relname, fname, lstat, linktarget)
- })
- } else {
- this.reportAndRecurse(relname, fname, lstat)
- }
- })
- })
- this.checkPending(dir)
- })
- }
- }
- module.exports = function(base, archive, cb) {
-
- if (!cb) {
- cb = archive
- archive = fs
- }
- const resolved = path.resolve(base)
- const w = new Walker(archive, resolved, cb)
- w.walk(resolved)
- }
|