Esempio n. 1
0
  uidNumber(buildDescription.uid, buildDescription.gid, function (err, uid, gid) {
    if (err) {
      return callback(err);
    }

    async.waterfall([
      fs.readFile.bind(fs, pkgFile),
      updatePackage,
      chownr.bind(chownr, dir, uid, gid)
    ], function (err) {
      callback(err, buildDescription);
    });
  });
	findup(root, EXT_SCRIPTS, (err, dir) => {
		if (err) {
			cb(err);
		}
		else {
			// In parallel, read the external-scripts.json and package.json
			async.parallel([
				fs.readFile.bind(null, path.resolve(dir, EXT_SCRIPTS), {encoding: 'utf8'}),
				fs.readFile.bind(null, path.resolve(dir, PKG), {encoding: 'utf8'})],
				(err, files) => {
					if (err) {
						cb(err);
					}
					// If there are no errors, parse the contents to find out the versino of our bot
					const pkgContents = JSON.parse(files[1]);
					const metadata = {name: pkgContents.name, version: pkgContents.version, dependencies: {}};

					try {
						const scripts = JSON.parse(files[0]);

						// Find all of the external scripts under node_modules
						async.map(scripts, (file, complete) => fs.readFile(path.resolve(dir, 'node_modules', file, PKG), {encoding: 'utf8'}, (err, content) => complete(null, !err ? content : undefined)), (e, files) => {
							// errors correspond with undefined items in the array and the error argument should always be null
							files.forEach(file => {
								if (file) {
									const pkgContents = JSON.parse(file);
									metadata.dependencies[pkgContents.name] = pkgContents.version;
								}
							});
							cb(null, metadata);
						});
					}
					catch (e) {
						cb(new Error('Contents of external-scripts.json is not an array.'));
					}
				});
		}
	});
Esempio n. 3
0
  'reads multiline json at top of html': function () {
    fs.exists.withArgs('some/test.html').yields(true);
    fs.readFile.withArgs('some/test.html').yields(null,
        new Buffer('{\n  "some": "json"\n}\n\n<em>html</em>'));
    var spy = sinon.spy();

    fileReader.read('some/test', {}, spy);

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWithMatch(spy, null, {
      html : '<em>html</em>',
      some : 'json'
    });
  },
        testPublish: function (test) {
            var fs = testHelper.fsForTest(test);
            fs.readFile.expect(
                {file: this.packageFile, data: this.packageJSONSrc});
            fs.readFile.expect(
                {file: this.historyFile, data: "0.0.7 / 2012-04-06\n"
                                             +"==================\n"
                                             + "  * ...\n"});
            fs.writeFile.expect(
                {file: this.packageFile, data: this.packageJSONSrcWithMinorInc});
            var exec = testHelper.execForTest(test).expect(
                {cmd: 'git st package.json --porcelain', cwd: 'foo/bar', out: 'modified: package.json'},
                {cmd: 'git add package.json && git ci -m "version 0.0.7"', cwd: 'foo/bar'},
                {cmd: 'git tag 0.0.7', cwd: 'foo/bar'},
                {cmd: 'git push && git push --tags', cwd: 'foo/bar'},
                {cmd: 'npm publish', cwd: 'foo/bar'});

            publish({fs: fs, exec: exec}, null, this.scriptDir);
            fs.readFile.assertAllCalled();
            fs.writeFile.assertAllCalled();
            exec.assertAllCalled();
            test.done();
        }
Esempio n. 5
0
/**
 * Single page templates are a complicated business. Since they need to be
 * parsed with a custom set of locals, they cannot be rendered purely through
 * webpack's pipeline, unless we required a function wrapper for the locals
 * object like spike-collections does. As such, we render them manually, but in
 * a way that exactly replicates the way they are rendered through the reshape
 * loader webpack uses internally.
 *
 * When called in the webpack emit hook above, it per key -- that is, if the
 * user has specified:
 *
 * { test: { url: 'http://example.com' }, test2: { file: './foo.json' } }
 *
 * This method will get the 'test' and 'test2' keys along with their resolved
 * data from the data sources specified.
 *
 * @param  {Compilation} compilation - webpack compilation instance
 * @param  {Compiler} compiler - webpack compiler instance
 * @param  {Object} _data - resolved data for the user-given key
 * @param  {String} k - key name for the data
 * @return {Promise} promise for written templates
 */
function writeTemplates (compilation, compiler, _data, k) {
  const tpl = this.opts[k].template
  const root = compiler.options.context

  // If the template option doesn't exist or is malformed, we return or error.
  if (!tpl) { return _data }
  if (!tpl.path) { throw new Error('missing template.path') }
  if (!tpl.output) { throw new Error('missing template.output') }

  // If there is also a template transform function, we run that here
  const data = tpl.transform ? tpl.transform(_data) : _data
  // We must ensure that template data is an array to render each item
  if (!Array.isArray(data)) { throw new Error('template data is not an array') }

  // First we read the template file
  const tplPath = path.join(root, tpl.path)
  return node.call(fs.readFile.bind(fs), tplPath, 'utf8')
    .then((template) => {
      // Now we go through each item in the data array to render a template
      return W.map(data, (item) => {
        // The template gets all the default locals as well as an "item" prop
        // that contains the data specific to the template, and a filename
        const newLocals = Object.assign({}, this.opts.addDataTo, {
          item,
          filename: path.join(root, tpl.path)
        })

        // We need to precisely replicate the way reshape is set up internally
        // in order to render the template correctly, so we run the reshape
        // loader's options parsing with the real loader context and the user's
        // reshape options from the config
        const options = loader.parseOptions.call(this.loaderContext, this.util.getSpikeOptions().reshape, {})

        // And finally, we run reshape to generate the template!
        return reshape(Object.assign(options, {
          locals: newLocals,
          filename: tplPath
        }))
          .process(template)
          .then((res) => {
            const rendered = res.output(newLocals)
            // And then add the generated template to webpack's output assets
            compilation.assets[tpl.output(item)] = {
              source: () => rendered,
              size: () => rendered.length
            }
          })
      })
    })
}
Esempio n. 6
0
  'reads multiline json at top of markdown': function () {
    fs.exists.withArgs('some/test.md').yields(true);
    fs.readFile.withArgs('some/test.md').yields(null,
        new Buffer('{\n  "some": "json"\n}\n\n_markdown_'));
    var spy = sinon.spy();

    fileReader.read('some/test', {}, spy);

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWithMatch(spy, null, {
      md   : '<p><em>markdown</em></p>',
      some : 'json'
    });
  },
Esempio n. 7
0
 return function getPassword(callback) {
     // Prompt for password
     if (!config.password) {
         if (config.cachePassword) {
             // If cache password option is given, check for an existing password.
             var password;
             async.waterfall([
                 // read reaper pid id and kill it the reaper if it's found
                 function (callback) {
                     fs.readFile(config.passwordCacheReaperPid, function (err, data) {
                         if (!err) {
                             if (/^[0-9]+$/.test(data)) {
                                 return exec('kill -2 ' + data, function () {
                                     callback();
                                 });
                             }
                         }
                         callback();
                     });
                 },
                 // attempt to read password file
                 fs.readFile.bind(fs, config.passwordCacheFile),
                 function (data, callback) {
                     data = JSON.parse(data);
                     password = new kpio.Credentials.Password('temp');
                     password.__hashBuffer = new Buffer(data.buffer);
                     callback();
                 },
                 // start a new reaper
                 startReaper.bind(null, config.cachePassword),
                 function (callback) {
                     callback(null, password);
                 }
             ], function (err, password) {
                 if (err) {
                     // found no password file, better get one
                     return require('./passwordPrompt')(config, function (err, password) {
                         callback(err, password);
                     });
                 }
                 return callback(null, password);
             });
         } else {
             return require('./passwordPrompt')(config, callback);
         }
     } else {
         return callback(null, config.password);
     }
 }
Esempio n. 8
0
  it('does not write file if read failed', function () {
    fs.exists.yields(true);
    var error = new Error('Oh noes!');
    fs.readFile.yields(error);
    var spy = sinon.spy();

    writer.write([{
      path : 'file.html',
      data : '<h1>foo</h1>'
    }], 'site', spy);

    sinon.assert.notCalled(fs.writeFile);
    sinon.assert.calledOnce(spy);
    sinon.assert.calledWith(spy, error);
  });
Esempio n. 9
0
  'adds name and path to file object': function () {
    fs.exists.withArgs('some/test.json').yields(true);
    fs.readFile.withArgs('some/test.json').yields(null, new Buffer('{}'));
    var spy = sinon.spy();

    fileReader.read('some/test', {}, spy);

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWithMatch(spy, null, {
      file   : {
        name : 'test',
        path : 'some/test.html'
      }
    });
  },
Esempio n. 10
0
        it("读取并返回项目页面", function () {
            var fakeResponse = {
                writeHead: sandbox.stub(),
                write: sandbox.stub(),
                end: sandbox.stub()
            };
            var content = "<html></html>";
            sandbox.stub(config, "indexPath", "C:/output/view/index.html");

            controller.index({}, fakeResponse);
            fs.readFile.callArgWith(2, null, content);

            expect(tool.changeToUnixifyPath(fs.readFile.firstCall.args[0])).toEqual("C:/output/view/index.html");
            expect(fakeResponse.write.calledWith(content)).toBeTruthy();
        });
Esempio n. 11
0
	async.every(["./build/typescript/typescript.d.ts", "./build/typescript/index.js", "./build/doc.js"], fs.exists.bind(fs), function (allExist) {
		if (allExist) {
			callback();
			return;
		}

		var typescriptPath = path.join(require.resolve("typescript"), "..", "..");

		async.waterfall([
			async.parallel.bind(async, [
				fs.readFile.bind(fs, path.join(typescriptPath, "lib", "typescript.d.ts"), "utf8"),
				fs.readFile.bind(fs, "./build/typescript/extras.d.ts", "utf8")
			]),
			function (results, callback) {
				var newDts = results[0] + "\n\n" + results[1];
				fs.writeFile("./build/typescript/typescript.d.ts", newDts, "utf8", callback);
			},
			function (callback) {
				npm.load(function () {
					npm.commands["run-script"](["build"], callback);
				});
			}
		], callback);
	});
Esempio n. 12
0
var CLI = function(config) {
	config = config || {};

	this.flags = config.flags || flags;

	this._args = config.args || argv._;
	this._cwd = config.cwd || base.CWD;
	this._async = config.async || async;
	this._exec = config.exec || cli.exec.bind(cli);
	this.junit = config.junit || junit;
	this._log = config.log || console.log.bind(console);
	this._logger = config.logger || Logger;
	this._read = config.read || fs.readFile.bind(fs);
	this._write = config.write || fs.writeFile.bind(fs);
};
Esempio n. 13
0
    return new Promise((resolve, reject) => {
        const params = [
            file,
            format,
            (err, data) => {
                if (err) {
                    return reject(err);
                }

                return resolve(data);
            }
        ];

        fs.readFile.apply(fs, params.filter(p => p));
    });
Esempio n. 14
0
function readFile(path, options, callback) {
  var key = resolve(path);

  readFile._readCount[key] = (readFile._readCount[key] || 0) + 1;

  if (readFile._nextError) {
    var cb = callback || options;
    var err = readFile._nextError;

    readFile._nextError = null;

    return cb (err);
  }

  return fs.readFile.apply(this, arguments);
}
Esempio n. 15
0
server.prototype.page = function (pagename, vars) {
    if (vars == undefined)
        vars = {};
    var pagestr;
    self = this;
    vars._options = self._options;
    if (self.compiled[pagename] != undefined) {
        pagestr = self.compiled[pagename](vars);
    } else {
        var pagePath = path.resolve(path.join(self.root, 'template', pagename + '.jtpl'));
        var filestr = fs.readFile.sync(null, pagePath);
        self.compiled[pagename] = ejs.compile(filestr.toString('utf-8'), self.eJSoptions);
        pagestr = self.compiled[pagename](vars);
    }
    return pagestr;
}.async();
Esempio n. 16
0
        beforeEach(function(done) {
            // @todo Must be sync yields, else the beforeEach completes
            // before the read finishes. Make this neater.
            fs.readFile.yields(null, '1');

            listener = sinon.spy();
            gpio.on('change', listener);

            gpio.setup(1, gpio.DIR_IN, onSetupComplete);

            function onSetupComplete() {
                var cb = fs.watchFile.getCall(0).args[1];
                cb();
                done();
            }
        });
Esempio n. 17
0
	function compareItem(filename, itemCallback) {
		var loaders = [
			fs.readFile.bind(null, path.join(targetPath, filename)),
			request.get.bind(null, couchurl + '/' + filename)
		];

		async.parallel(loaders, function(err, results) {
			if (err) return itemCallback(err);

			// hash both the results
			assert.equal(results[0].toString(), results[1][0].body);

			// trigger the item callback
			itemCallback();
		});
	}
Esempio n. 18
0
    return function (request, response) {
        async.waterfall([
            async.series.bind(async, [
                Student.get.bind(Student, request.params.id),
                fs.readFile.bind(fs, request.files['0'].path)
            ]),
            function (results, callback) {
                var student = results[0],
                    fileContents = results[1];

                student[documentName] = fileContents;
                student.save(callback);
            },
            fs.unlink.bind(fs, request.files['0'].path)
        ], response.handle());
    };
Esempio n. 19
0
  'allows to define a custom suffix to be used in the path': function () {
    fs.exists.withArgs('some/test.json').yields(true);
    fs.readFile.withArgs('some/test.json').yields(null,
        new Buffer('{"file":{"suffix":"rss"}}'));
    var spy = sinon.spy();

    fileReader.read('some/test', {}, spy);

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWithMatch(spy, null, {
      file   : {
        name : 'test',
        path : 'some/test.rss'
      }
    });
  },
Esempio n. 20
0
File: Exp.js Progetto: aiba/xde
async function createNewExpAsync(root, info, opts = {}) {
  let pp = path.parse(root);
  let name = pp.name;

  let author = await userSettings.getAsync('email', null);

  let dependencies = {
    'react-native': await _getReactNativeVersionAsync(),
  };

  let data = Object.assign({
    name,
    version: '0.0.0',
    description: "Hello Exponent!",
    main: 'main.js',
    author,
    dependencies,
    //license: "MIT",
    // scripts: {
    //   "test": "echo \"Error: no test specified\" && exit 1"
    // },
  }, info);

  let pkgJson = jsonFile(path.join(root, 'package.json'));

  let exists = await existsAsync(pkgJson.file);
  if (exists && !opts.force) {
    throw NewExpError('WONT_OVERWRITE_WITHOUT_FORCE', "Refusing to create new Exp because package.json already exists at root");
  }

  await mkdirp.promise(root);

  let result = await pkgJson.writeAsync(data);

  // Copy the template directory, which contains node_modules, without its
  // package.json
  await fsExtra.promise.copy(TEMPLATE_ROOT, root, {
    filter: filePath => filePath !== path.join(TEMPLATE_ROOT, 'package.json')
  });

  // Custom code for replacing __NAME__ in main.js
  let mainJs = await fs.readFile.promise(path.join(TEMPLATE_ROOT, 'main.js'), 'utf8');
  let customMainJs = mainJs.replace(/__NAME__/g, data.name);
  result = await fs.writeFile.promise(path.join(root, 'main.js'), customMainJs, 'utf8');

  return data;
}
Esempio n. 21
0
test("saveProfile saves a profile to disk", async(function* (assert) {
    yield repo.saveProfile({
        name: "named-profile",
        commands: {
            "command one": {
                name: "command one",
                command: "node",
                args: "app.js",
            }
        }
    })
    var loc = path.join(dir, "named-profile.json")
    var str = yield fs.readFile.bind(null, loc)

    var json = JSON.parse(str)
    assert.equal(json.name, "named-profile")
}))
Esempio n. 22
0
const getNpmConfig = (
    dirname,
    readFile = fs.readFile.bind(fs),
    joinPath = path.join.bind(path),
    parseJSON = JSON.parse.bind(JSON)
) =>
    new Promise((resolve, reject) => {
        readFile(joinPath(dirname, 'package.json'), (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(
                    parseJSON(data.toString())
                );
            }
        });
    });
Esempio n. 23
0
function loadPkg(pkgPath, cb) {
    async.waterfall([
        assertPkgFileExists,
        fs.readFile.bind(fs, pkgPath, {encoding: 'utf8'}),
        function(pkgText, cb) { cb(null, JSON.parse(pkgText)); }
    ], cb);

    function assertPkgFileExists(cb) {
        fs.exists(pkgPath, then);

        function then(exists) {
            cb(exists ? null :
                new Error('Can\'t load ' + pkgPath +
                          '\nMake sure you have a package.json available'));
        }
    }
}
  pit('should loadFileAndTransform', function() {
    workers.mockImpl(function(data, callback) {
      callback(null, { code: 'transformed', map: 'sourceMap' });
    });
    fs.readFile.mockImpl(function(file, callback) {
      callback(null, 'content');
    });

    return new Transformer(options).loadFileAndTransform('file')
      .then(function(data) {
        expect(data).toEqual({
          code: 'transformed',
          map: 'sourceMap',
          sourcePath: 'file',
          sourceCode: 'content'
        });
      });
  });
Esempio n. 25
0
            it("将post传入的值保存到页面的隐藏域中", function () {
                var outputData = "[1,{}, \"aaa\"]";
                sandbox.stub(querystring, "parse").returns({
                    outputData: outputData
                });
                var pageHtml = "<html><body><input type='hidden' value='__RESULT__'/></body></html>"
                var fakeResponse = {
                    writeHead: sandbox.stub(),
                    write: sandbox.stub(),
                    end: sandbox.stub()
                };

                controller.showResult(fakeRequest, fakeResponse);
                fakeRequest.on.secondCall.callArg(1);
                fs.readFile.callArgWith(2, null, pageHtml);

                expect(fakeResponse.write.firstCall.args[0]).toContain("value='"+outputData+"'");
            })
Esempio n. 26
0
exports.asyncparallelresult = function(callback){
	async.parallel([
	   function(cb){
		request.get('http://www.localeplanet.com/api/auto/currencymap.json?name=',function(error,response,body){
			cb(error,body)
		});
	  },
	  function(cb){
		request.get('http://openexchangerates.org/api/latest.json?app_id=11c058108ce448238a2c48274ce67f15',function(error,response,body){
			cb(error,body)
		});
	  },
	  fs.readFile.bind(fs,"./files/rate.txt",'utf8')
	], function(error, results){
		console.log(results);
		callback(results);
	});

}
Esempio n. 27
0
exports.modify = function (done) {
  var change = path.resolve(exports.fixture, 'change.json');

  async.waterfall([

    // read source
    fs.readFile.bind(fs, change, 'utf8'),

    // modify and save to source
    function (content, callback) {
      var obj = JSON.parse(content);
          obj.state += 1;

      fs.writeFile(change, JSON.stringify(obj), function (error) {
        callback(error, obj.state);
      });
    }
  ], done);
};
Esempio n. 28
0
  ], function (error, results) {
    /* istanbul ignore if */
    if (error) {
      return callback(error)
    }

    var sourceTime = results[0]
    var targetTime = results[1]
    var hasUpdate = sourceTime > targetTime

    var get = hasUpdate ? buildBundle.bind(null, config, hoodieClientPath) : fs.readFile.bind(null, bundleTargetPath)

    get(function (error, buffer) {
      if (error) {
        return callback(error)
      }

      callback(null, buffer, hasUpdate)
    })
  })
Esempio n. 29
0
$class.save = function(path, content, callback) {
  var match = MODULE_WRAP_REGEX.exec(content);
  if (!match) {
    callback(new Error('The new content is not a valid node.js script.'));
    return;
  }
  var newSource = match[1];
  async.waterfall([
    fs.readFile.bind(fs, path, 'utf-8'),

    function(oldContent, cb) {
      var match = /^(\#\!.*)/.exec(oldContent);
      if (match)
        newSource = match[1] + newSource;

      fs.writeFile(path, newSource, cb);
    }
  ],
  callback);
};
Esempio n. 30
0
  ]), function (error, results) {
    /* istanbul ignore if */
    if (error) {
      return callback(error)
    }

    var targetTime = results.pop()
    var sourceTime = Math.max.apply(null, results)
    var hasUpdate = sourceTime > targetTime

    var get = hasUpdate ? buildBundle.bind(null, options, plugins) : fs.readFile.bind(null, bundleTargetPath)

    get(function (error, buffer) {
      if (error) {
        return callback(error)
      }

      callback(null, buffer, hasUpdate)
    })
  })