Example #1
0
 it(`should create symlink dir using src ${srcpath} and dst ${dstpath}`, () => {
   fn.apply(null, args)
   const relative = symlinkPathsSync(srcpath, dstpath)
   const srcContents = fs.readdirSync(relative.toCwd)
   const dstDir = path.dirname(dstpath)
   const dstBasename = path.basename(dstpath)
   const isSymlink = fs.lstatSync(dstpath).isSymbolicLink()
   const dstContents = fs.readdirSync(dstpath)
   const dstDirContents = fs.readdirSync(dstDir)
   assert.equal(isSymlink, true)
   assert.deepEqual(srcContents, dstContents)
   assert(dstDirContents.indexOf(dstBasename) >= 0)
 })
module.exports = function(source) {
  this.cacheable && this.cacheable();
  this.addContextDependency(path.join(__dirname, 'dir'));
  var items = fs.readdirSync(path.join(__dirname, 'dir'));
  items.sort();
  var subdir = items[items.length - 1];
  var subitems = fs.readdirSync(path.join(__dirname, 'dir', subdir));
  subitems.sort();
  var name = subitems[subitems.length - 1];
  return [
    '// ' + subdir + '/' + name,
    source
  ].join('\n');
};
Example #3
0
 const callback = err => {
   if (err) return done(err)
   const relative = symlinkPathsSync(srcpath, dstpath)
   const srcContents = fs.readdirSync(relative.toCwd)
   const dstDir = path.dirname(dstpath)
   const dstBasename = path.basename(dstpath)
   const isSymlink = fs.lstatSync(dstpath).isSymbolicLink()
   const dstContents = fs.readdirSync(dstpath)
   const dstDirContents = fs.readdirSync(dstDir)
   assert.equal(isSymlink, true)
   assert.deepEqual(srcContents, dstContents)
   assert(dstDirContents.indexOf(dstBasename) >= 0)
   return done()
 }
Component.prototype.assemble = function assemble (opts) {
  var _this = this
  if (debug) console.info('Assembling component: ' + _this.name)
  fs.readdirSync(opts.location.src + _this.path).filter(function (file) {
    var extension = (path.extname(file) === undefined) ? 'folder' : path.extname(file).toLowerCase()
    // only files with the same name as template or '_' in front
    if (file.substr(0, file.indexOf('.')) === _this.name ||
      file.substr(0, file.indexOf('.')) === '_' + _this.name) {
        
      // Ad demo file to component if it exists.
      if( RegExp(".*\.demo" + opts.extensions.template).test(file) ) {
        _this.demo = path.join(_this.path, file)
      } else {
        switch (extension) {
          case '.json':
            _this.data = path.join(_this.path, file)
            break
          case '.md':
            _this.info.path = path.join(_this.path, file)
            break
          case '.js':
            _this.js = path.join(_this.path, file)
            break
          case '.scss':
            _this.style = path.join(_this.path, file)
            break
        }
      }

    }
  })

  opts.components.push(_this)
  return _this
}
Example #5
0
/** Recursively walks over directory. */
function walkSync(localPath, returnCallback) {
	localPath = cleanPath(localPath);

	var results = [];
	var stats = fs.statSync(localPath);

	// Check return condition.
	if (returnCallback && returnCallback(localPath, stats)) {
		return results;
	}

	// Add current item.
	results.push(localPath);

	// No need for recursion if not a directory.
	if (!stats.isDirectory()) {
		return results;
	}

	// Iterate over list of children.
	var list = fs.readdirSync(localPath);
	list.forEach(function (file) {
		file = localPath + "/" + file;
		results = results.concat(walkSync(file, returnCallback));
	});

	return results;
}
Example #6
0
  // Iterate folders and push filepaths to track data workers
  generateLibrary(path) {
    let self = this;
    if (!fs.existsSync(path)) {
      console.log(path ," does not exist.");
      return;
    }
    // Dragging in a single file
    if (pathTools.extname(path) === ".mp3") {
      this.newTrackProcessor.push(path, function(err) {
        if (!err) {
          console.log('Processed ', path);
        } else {
          console.log(err);
        }
      });
      return;
    }

    let items = fs.readdirSync(path);
    for (let i = 0; i < items.length; i++) {
      let curFilePath = pathTools.join(path, items[i]);
      let curFileStats = fs.lstatSync(curFilePath);
      if (curFileStats.isDirectory()) {
        this.generateLibrary(curFilePath);
      } else if (pathTools.extname(curFilePath) === ".mp3") {
        this.newTrackProcessor.push(curFilePath, function(err) {
          if (!err) {
            console.log('Processed ', curFilePath);
          } else {
            console.log(err);
          }
        });
      }
    }
  }
Example #7
0
    var getDirs = function (baseDir, ignore) {
        var inputPaths = [],
            paths = [],
            i, d, isIgnored, subpath,
            stat, possibleDirs, fullPath;

        var inputPath = '';
        while (inputPath !== undefined) {
            fullPath = path.join(baseDir, inputPath);
            stat = fs.lstatSync(fullPath);

            if (stat.isDirectory()) {
                if (fullPath !== baseDir) {
                    paths.push(fullPath);
                }
                possibleDirs = fs.readdirSync(fullPath);
                for (d=0;d<possibleDirs.length;d++) {
                    subpath = path.join(inputPath, possibleDirs[d]);
                    isIgnored = false;
                    for (i=0;i<ignore.length;i++) {
                        if (subpath.indexOf(ignore[i]) === 0) {
                          isIgnored = true;
                          break;
                        }
                    }
                    if (!isIgnored) {
                      inputPaths.push(subpath);
                    }
                }
            }
            inputPath = inputPaths.pop();
        }

        return paths;
    };
Example #8
0
TumblrConnection.prototype.scanLocalDirectory = function(){
  var that = this
  var path = '.' //'/home/arch-nicky/' //'.'

  var files = fs.readdirSync(path)
  if (files){
    //console.log(files)
    files.forEach(function(element,index,fullArray){
      //console.log(element)
      that.decomposeFilename(element)
    })
  }

  //async readdir call
  // fs.readdir(path,function(err,files){
  //   if (err) {
  //     console.log(err)
  //   }
  //   if (files){
  //     //console.log(files)
  //     files.forEach(function(element,index,fullArray){
  //       console.log(element)
  //       that.decomposeFilename(element)
  //     })
  //   }
  // })
}
Example #9
0
exports.cacheClear = function() {
  var jspmDir = path.resolve(config.HOME, '.jspm'),
      packagesCacheDir = path.join(jspmDir, 'packages'),
      loaderCacheDir = path.join(jspmDir, 'loader-files'),
      files, filesLength, fileName, i;

  // Clear loader files
  if (fs.existsSync(loaderCacheDir))
    rimraf.sync(loaderCacheDir);
  ui.log('ok', 'Loader file cache cleared.');

  // Clear packages cache folder
  if (fs.existsSync(packagesCacheDir))
    rimraf.sync(packagesCacheDir);
  ui.log('ok', 'Package cache cleared.');

  // Clear registry cache folders
  files = fs.readdirSync(jspmDir);
  filesLength = files.length;
  for (i = 0; i < filesLength; i++) {
    fileName = files[i];
    if (fileName.endsWith('-cache')) {
      rimraf.sync(path.join(jspmDir, fileName));
      ui.log('ok', '%' + fileName.substr(0, fileName.length - '-cache'.length) + '% cache cleared.');
    }
  }

  ui.log('warn', 'All caches cleared.');
  ui.log('info', 'Please post an issue if you suspect the cache isn\'t invalidating properly.');
  ui.log('info', '%jspm install -f% is equivalent to running a cache clear for that specific package tree.');
};
Example #10
0
  it('should overwrite the destination directory if overwrite = true', function (done) {
    // Create src
    const src = path.join(TEST_DIR, 'src')
    fse.ensureDirSync(src)
    fse.mkdirsSync(path.join(src, 'some-folder'))
    fs.writeFileSync(path.join(src, 'some-file'), 'hi')

    const dest = path.join(TEST_DIR, 'a-folder')

    // verify dest has stuff in it
    const paths = fs.readdirSync(dest)
    assert(paths.indexOf('another-file') >= 0)
    assert(paths.indexOf('another-folder') >= 0)

    fse.move(src, dest, {overwrite: true}, err => {
      assert.ifError(err)

      // verify dest does not have old stuff
      const paths = fs.readdirSync(dest)
      assert.strictEqual(paths.indexOf('another-file'), -1)
      assert.strictEqual(paths.indexOf('another-folder'), -1)

      // verify dest has new stuff
      assert(paths.indexOf('some-file') >= 0)
      assert(paths.indexOf('some-folder') >= 0)

      done()
    })
  })
  vacuum(fullPath, {purge : false, base : testBase, log : log}, function (er) {
    t.ifError(er, "cleaned up to base")

    t.equal(messages.length, 6, "got 5 removal & 1 finish message")
    t.equal(messages[5], "finished vacuuming up to " + testBase)

    var stat
    var verifyPath = fullPath

    function verify() { stat = statSync(verifyPath) }

    // handle the file separately
    t.throws(verify, verifyPath + " cannot be statted")
    t.notOk(stat && stat.isFile(), verifyPath + " is totally gone")
    verifyPath = path.dirname(verifyPath)

    for (var i = 0; i < 4; i++) {
      t.throws(verify, verifyPath + " cannot be statted")
      t.notOk(stat && stat.isDirectory(), verifyPath + " is totally gone")
      verifyPath = path.dirname(verifyPath)
    }

    t.doesNotThrow(function () {
      stat = statSync(testBase)
    }, testBase + " can be statted")
    t.ok(stat && stat.isDirectory(), testBase + " is still a directory")

    var files = readdirSync(testBase)
    t.equal(files.length, 0, "nothing left in base directory")

    t.end()
  })
Example #12
0
module.exports = function () {
  var componentDir = fecom.componentRoot;
  var rootComponentJson = path.join(fecom.root, 'component.json');
  var files = [];
  var dependencies = fecom.config.dependencies || [];
  var children;
  dependencies = dependencies.map(function (semantic) {
    var parsed = fecom.parse(semantic);

    if (!(parsed.hasOwnProperty('resolved') && parsed.resolved)) {
      parsed.specified = true;
    }

    return parsed;
  });

  children = dependencies.map(function (parsed) {
    return {
      props: parsed
    };
  });

  var rootComponent = new Component(null, 'root', {
    children: children
  });

  if (fs.existsSync(componentDir)) {
    files = fs.readdirSync(componentDir);
  }

  files = files.filter(function (file) {
    return !_.startsWith(file, '.');
  });

  return rootComponent.getLocalDependenciesTree()
    .then(function (filledTree) {
      var treeModel = new Tree(filledTree);
      var installed = treeModel.getAllNodes('DFS').slice(1);
      return Promise.all(files.map(function (file) {
        var matchedSpecified = _.find(dependencies, { name: file }) || {};
        var matchedInstalled = _.find(installed, { name: file}) || {};

        if (!fs.existsSync(rootComponentJson)) {
          var json = jsonfile.readFileSync(path.join(componentDir, file, 'component.json'));
          matchedInstalled.owner = json.owner;
          matchedInstalled.version = json.version;
        }

        var schema = {
          name: file,
          owner: matchedSpecified.owner || matchedInstalled.owner || fecom.config.owner,
          specified: Boolean(matchedSpecified.specified),
          resolved: Boolean(matchedSpecified.resolved)
        };

        return fecom.async(new Component(schema, 'local'));
      }));
    });

};
Example #13
0
function templates() {
  const prefix = "(function(){var template=Handlebars.template," +
    "templates=Handlebars.templates=Handlebars.templates||{};";
  const suffix = "Handlebars.partials=Handlebars.templates})();";

  return prefix + fs.readdirSync(paths.templates).map(file => {
    const p = path.join(paths.templates, file);
    const name = file.replace(/\..+$/, "");
    let html = htmlMinifier.minify(fs.readFileSync(p, "utf8"), opts.htmlMinifier);

    // remove whitespace around {{fragments}}
    html = html.replace(/(>|^|}}) ({{|<|$)/g, "$1$2");

    // trim whitespace inside {{fragments}}
    html = html.replace(/({{2,})([\s\S\n]*?)(}{2,})/gm, (_, p1, p2, p3) => {
      return p1 + p2.replace(/\n/gm, " ").replace(/ {2,}/gm, " ").trim() + p3;
    }).trim();

    // remove {{!-- comments --}}
    html = html.replace(/{{![\s\S]+?..}}/, "");

    const compiled = handlebars.precompile(html, {data: false});
    return "templates['" + name + "']=template(" + compiled + ");";
  }).join("") + suffix;
}
Example #14
0
  vacuum(fullPath, {purge: false, base: testBase, log: log}, function (er) {
    t.ifError(er, 'cleaned up to base')

    t.equal(messages.length, 3, 'got 2 removal & 1 quit message')
    t.equal(messages[2], 'quitting because new (racy) entries in ' + partialPath)

    var stat
    var verifyPath = fullPath

    function verify () { stat = statSync(verifyPath) }

    // handle the file separately
    t.throws(verify, verifyPath + ' cannot be statted')
    t.notOk(stat && stat.isFile(), verifyPath + ' is totally gone')
    verifyPath = path.dirname(verifyPath)

    for (var i = 0; i < 4; i++) {
      t.doesNotThrow(function () {
        stat = statSync(verifyPath)
      }, verifyPath + ' can be statted')
      t.ok(stat && stat.isDirectory(), verifyPath + ' is still a directory')
      verifyPath = path.dirname(verifyPath)
    }

    t.doesNotThrow(function () {
      stat = statSync(testBase)
    }, testBase + ' can be statted')
    t.ok(stat && stat.isDirectory(), testBase + ' is still a directory')

    var files = readdirSync(testBase)
    t.equal(files.length, 1, 'base directory untouched')

    t.end()
  })
Example #15
0
	Tools.loadMods = function () {
		if (Tools.modsLoaded) return;
		var parentMods = {};

		try {
			var mods = fs.readdirSync('./mods/');

			mods.forEach(function (mod) {
				if (fs.existsSync('./mods/' + mod + '/scripts.js')) {
					parentMods[mod] = require('./mods/' + mod + '/scripts.js').BattleScripts.inherit || 'base';
				} else {
					parentMods[mod] = 'base';
				}
			});

			var didSomething = false;
			do {
				didSomething = false;
				for (var i in parentMods) {
					if (!moddedTools[i] && moddedTools[parentMods[i]]) {
						moddedTools[i] = Tools.construct(i, parentMods[i]);
						didSomething = true;
					}
				}
			} while (didSomething);
		} catch (e) {
			console.log("Error while loading mods: " + e);
		}
		Tools.modsLoaded = true;
	};
Example #16
0
File: fs.js Project: hexojs/hexo-fs
function ensurePathSync(path) {
  if (!path) throw new TypeError('path is required!');
  if (!fs.existsSync(path)) return path;

  const files = fs.readdirSync(dirname(path));

  return _findUnusedPath(path, files);
}
Example #17
0
 _loadMod: function(parentElementName, elementName, modName, modDirPath) {
     var _this = this;
     filterFiles(fs.readdirSync(modDirPath)).forEach(function(filename) {
         var fullname = modDirPath + '/' + filename,
             stat = fs.statSync(fullname);
         _this._processFile(fullname, stat, parentElementName, elementName, modName);
     });
 },
Example #18
0
            .spread(function () {
                var dirs = fs.readdirSync(sourceDir);

                expect(arguments.length).to.equal(0);
                expect(dirs).to.contain('0.0.1');
                expect(dirs).to.contain('0.2.0');
                next();
            })
Example #19
0
Glob.prototype._readdir = function (f, cb) {
  assert(this instanceof Glob)
  var abs = f
  if (f.charAt(0) === "/") {
    abs = path.join(this.root, f)
  } else if (isAbsolute(f)) {
    abs = f
  } else if (this.changedCwd) {
    abs = path.resolve(this.cwd, f)
  }

  this.log('readdir', [this.cwd, f, abs])
  if (f.length > this.maxLength) {
    var er = new Error("Path name too long")
    er.code = "ENAMETOOLONG"
    er.path = f
    return this._afterReaddir(f, abs, cb, er)
  }

  if (this.statCache.hasOwnProperty(f)) {
    var c = this.statCache[f]
    if (Array.isArray(c)) {
      if (this.sync) {
        return cb.call(this, null, c)
      }
      return process.nextTick(cb.bind(this, null, c))
    }

    if (!c || c === 1) {
      // either ENOENT or ENOTDIR
      var code = c ? "ENOTDIR" : "ENOENT"
        , er = new Error((c ? "Not a directory" : "Not found") + ": " + f)
      er.path = f
      er.code = code
      this.log(f, er)
      if (this.sync) {
        return cb.call(this, er)
      }
      return process.nextTick(cb.bind(this, er))
    }

    // at this point, c === 2, meaning it's a dir, but we haven't
    // had to read it yet, or c === true, meaning it's *something*
    // but we don't have any idea what.  Need to read it, either way.
  }

  if (this.sync) {
    var er, entries
    try {
      entries = fs.readdirSync(abs)
    } catch (e) {
      er = e
    }
    return this._afterReaddir(f, abs, cb, er, entries)
  }

  fs.readdir(abs, this._afterReaddir.bind(this, f, abs, cb))
}
Example #20
0
	this.init = function (name) {
		this._name = name;
		this._path = common.paths.addons(name);
		this._paths = {};

		fs.readdirSync(this._path).forEach(function (filename) {
			this._paths[filename] = true;
		}, this);
	}
Example #21
0
fs.exists(obj.mapper_output, function(exists) {
  	if(exists) {
  		fs.unlinkSync(obj.mapper_output);
  		fs.readdirSync(obj.grouper_output_dir).forEach(function(file){
  			fs.unlinkSync(obj.grouper_output_dir + file);
  		})
  		fs.unlinkSync(obj.reducer_output);
  	}
  })
            .then(function (dir) {
                expect(dir).to.be.a('string');

                var files = fs.readdirSync(dir);

                expect(files).to.contain('foo');
                expect(files).to.not.contain('bar');
                next();
            })
Example #23
0
file.withExt = function (filepath, ext) {
  var files = fs.readdirSync(filepath);
  var list = [];
  files.forEach(function (filename) {
    if (file.containsExt(filename, ext)) {
      list.push(filename);
    }
  });
  return list;
};
Example #24
0
 it(`should create broken symlink dir using src ${srcpath} and dst ${dstpath}`, () => {
   fn.apply(null, args)
   const dstDir = path.dirname(dstpath)
   const dstBasename = path.basename(dstpath)
   const isSymlink = fs.lstatSync(dstpath).isSymbolicLink()
   const dstDirContents = fs.readdirSync(dstDir)
   assert.equal(isSymlink, true)
   assert(dstDirContents.indexOf(dstBasename) >= 0)
   assert.throws(() => fs.readdirSync(dstpath), Error)
 })
 it(`should create broken symlink file using src ${srcpath} and dst ${dstpath}`, () => {
   fn(...args)
   const dstDir = path.dirname(dstpath)
   const dstBasename = path.basename(dstpath)
   const isSymlink = fs.lstatSync(dstpath).isSymbolicLink()
   const dstDirContents = fs.readdirSync(dstDir)
   assert.strictEqual(isSymlink, true)
   assert(dstDirContents.indexOf(dstBasename) >= 0)
   assert.throws(() => fs.readFileSync(dstpath, 'utf8'), Error)
 })
Example #26
0
            .then(function () {
                var files;

                expect(fs.existsSync(cacheDir)).to.be(true);

                files = fs.readdirSync(cacheDir);
                expect(files.length).to.be(0);

                next();
            })
function verify (t, files, err, code) {
  if (code) {
    t.fail('exited with failure: ' + code)
    return t.end()
  }
  var actual = fs.readdirSync(target).sort()
  var expect = files.concat(['.npmignore', 'package.json']).sort()
  t.same(actual, expect)
  t.end()
}
Example #28
0
        !function(){
            var file  = keys.shift();
            var stat = fs.statSync(file);

            if(stat.isDirectory()){
                fs.mkdirSync(list[file]);
                var files = fs.readdirSync(file);
                files.forEach(function(path){
                    list[file + path + '/'] = list[file] + path + '/';
                    keys.push(file + path + '/');
                });
            }else{
                var input =  fs.createReadStream(file);
                var output = fs.createWriteStream(list[file]);
//                input.pipe(output);
                input.on('data', function(data){
                    if(output.write(data) === false){
                        input.pause();
                        pauseTotal++;
                    }
                    dataTotal++;
                });
                output.on('drain', function(){
                    input.resume();
                    resumeTotal++;
                });

                input.on('error', function(){
                    console.log('error');
                });

                input.on('end', function(){
                    endTotal++;
                    console.log('end' + endTotal + '>>close' + closeTotal+ '>>dataTota' + dataTotal + '>>pauseTota' + pauseTotal+ '>>resumeTota' + resumeTotal+ '>>outFinish'+outFinishTo + '>>outClose'+outCloseTo );
                });

                input.on('close', function(){
                    closeTotal++;
                    console.log('end' + endTotal + '>>close' + closeTotal+ '>>dataTota' + dataTotal + '>>pauseTota' + pauseTotal+ '>>resumeTota' + resumeTotal+ '>>outFinish'+outFinishTo + '>>outClose'+outCloseTo );
                });

                output.on('finish', function(){
                    outFinishTo++;
//                    console.log('end' + endTotal + '>>close' + closeTotal+ '>>dataTotal' + dataTotal + '>>pauseTotal' + pauseTotal+ '>>resumeTotal' + resumeTotal+ '>>outFinish'+outFinishTo + '>>outClose'+outCloseTo );
                });

                output.on('close', function(){
                    outCloseTo++;
//                    console.log('end' + endTotal + '>>close' + closeTotal+ '>>dataTotal' + dataTotal + '>>pauseTotal' + pauseTotal+ '>>resumeTotal' + resumeTotal+ '>>outFinish'+outFinishTo + '>>outClose'+outCloseTo );
                });
                fileTotal++;
            }
            delete list[file];
            console.log(keys.length);
        }();
Example #29
0
 const callback = err => {
   if (err) return done(err)
   const dstDir = path.dirname(dstpath)
   const dstBasename = path.basename(dstpath)
   const isSymlink = fs.lstatSync(dstpath).isSymbolicLink()
   const dstDirContents = fs.readdirSync(dstDir)
   assert.equal(isSymlink, true)
   assert(dstDirContents.indexOf(dstBasename) >= 0)
   assert.throws(() => fs.readdirSync(dstpath), Error)
   return done()
 }
Example #30
0
 it(`should do nothing using src ${srcpath} and dst ${dstpath}`, done => {
   const destinationContentBefore = fs.readdirSync(dstpath)
   const callback = err => {
     if (err) return done(err)
     const destinationContentAfter = fs.readdirSync(dstpath)
     assert.deepEqual(destinationContentBefore, destinationContentAfter)
     return done()
   }
   args.push(callback)
   return fn.apply(null, args)
 })