function wrapTranslations(options) {
  var template =
    '\'use strict\';\n' +
    '/** This file was autogenerated by gulp task i18n-autogenerate **/\n' +
    'angular\n' +
    '  .module(\'<%= module %>\')\n' +
    '  .constant(\'translationList\', [\n' +
    '<%= contents %>\n' +
    '  ]\n' +
    ');';
  return es.map(function(file, callback) {
    file.contents = new Buffer(gutil.template(template, {
      contents: file.contents,
      file: file,
      module: options.module || 'translate'
    }));
    callback(null, file);
  });
}
Example #2
0
module.exports = function (opts) {
  'use strict';

  opts = opts || {
    showStack: false
  };

  return es.map(function (file, cb) {
    if(file.isNull()){
      return  cb(null, file);
    }  
    try {
      file.contents = new Buffer(htmlmin.minify(String(file.contents), opts));
    } catch (err) {
      return cb(new gutil.PluginError('gulp-htmlmin', err, opts));
    }
    cb(null, file);
  });
};
Example #3
0
  gulp.task('markdown', ['clean'], function(){
    return gulp.src(config.templatesDir + '/**/*.md')
      .pipe(markdown())
      .pipe(es.map(function(file, cb) {

        var ghURL = packageJSON.name + '/blob/master' + file.path.replace(process.cwd(), '').replace('.html','.md');

        var html = jadeEngine.renderFile(config.markdownLayout, {
          basedir: config.templatesBaseDir,
          pretty: true,
          content: file.contents.toString('utf8'),
          siteColor: packageJSON.siteColor ? packageJSON.siteColor : config.siteColor,
          path: ghURL
        });
        file.contents = new Buffer(html);
        cb(null, file);
      }))
      .pipe(gulp.dest(config.templatesDistDir));
  })
Example #4
0
module.exports = function (options) {
	options = options || {
		showStack: false,
	};
	options.env = options.env || 'development';
	// snipets stripPath, toArray & unixify based on gulp-inject
	// https://github.com/klei/gulp-inject/blob/master/index.js
	function ignorePath (basedir, filepath) {
		return toArray(basedir).reduce(function (path, remove) {
			var regex = remove;
			if(!(remove instanceof RegExp)){
				remove = remove.replace(/\//g, '\\/');
				regex = new RegExp(remove, 'g');
			}
			path = path.replace(regex, '');
			return path;
		}, filepath);
	}
	function toArray (arr) {
		if (!Array.isArray(arr)) {
			return arr ? [arr] : [];
		}
		return arr;
	}
	function unixify (filepath) {
		return filepath.replace(/\\/g, '/');
	}
	return es.map(function (file, cb) {
		try {
			// if in dev mode html should not be minified
			// instead only output stream after checking ignore path.
			if(options.env === 'development'){
				file.path = ignorePath(options.ignorePath, unixify(file.path));
			} else {
				file.path = ignorePath(options.ignorePath, unixify(file.path));
				file.contents = new Buffer(htmlmin.minify(String(file.contents), options));
			}
		} catch (err) {
			return cb(new gutil.PluginError('gulp-htmlmin', err, options));
		}
		cb(null, file);
	});
};
Example #5
0
 return function (transmute) {
   // If it's a stream, add it to the reserve pipeline.
   if (transmute && (transmute.writable || transmute.readable)) {
     streams.push(transmute);
     d.add(transmute);
     return transmute;
   }
   // If it's a function, create a map stream with it.
   if (transmute) {
     transmute = es.map(transmute);
     streams.push(transmute);
     d.add(transmute);
     return transmute;
   }
   // If called without arguments, return a pipeline linking all streams.
   if (streams.length > 0) return es.pipeline.apply(es, streams);
   // But, if no streams were added, just pass back a through stream.
   return es.through();
 };
Example #6
0
 }, function(err, res, json) {
     update_seq = json.update_seq;
     log.info('Fetching module list to clone.. (this may take a bit..)');
     var modules = 0;
     request({
         url: options.registry + '-/all'
     })
         .pipe(JSONStream.parse('*'))
         .pipe(es.map(function(data, callback) {
             //get the complete package.json
             if (!data.name) {
                 return callback();
             }
                 request.get({
                     url: options.registry + data.name,
                     json: true
                 }, function(err, res, body) {
                     if (err || !body || !body.name || !body.versions) {
                         if (err) {
                             log.err(err);
                         }
                         return callback();
                     }
                     modules++;
                     var data = registry.split(body);
                     var json = patch.json(data.json, options.domain);
                     data.versions.forEach(function(item) {
                         item.json = patch.json(item.json, options.domain);
                     });
                     files.saveJSON(data, function() {
                         var num = Object.keys(json.versions).length;
                         log.info('Done processing', num, 'version' + ((num > 1) ? 's' : '') + ' of', json.name);
                         callback(null, json);
                     });
                 });
         }))
         .on('end', function() {
             log.info('Saved JSON for', modules, 'modules in', timethat(start), ', cloning tarballs now...');
             fs.writeFile(options.seqFile, update_seq, 'utf8', function() {
                 tarballs(options);
             });
         });
 });
Example #7
0
exports ['simple map applied to a stream'] = function (test) {

  var input = [1,2,3,7,5,3,1,9,0,2,4,6]
  //create event stream from

  var doubler = es.map(function (data, cb) {
    cb(null, data * 2)
  })

  readStream(doubler, function (err, output) {
    it(output).deepEqual(input.map(function (j) {
      return j * 2
    }))
    test.done()
  })

  writeArray(input, doubler)

}
Example #8
0
  confirm: function(options) {
    var prompted = false;
    return es.map(function(file, cb) {

      if (prompted === true) {
        cb(null,file);
        return;
      }

      var opts = {
        type: 'confirm',
        name: 'val',
        message: 'Are you sure?',
        default: false
      };

      if (typeof options === 'string') {
        opts.message = options;
      }

      if (typeof options !== 'object') {
        options = {};
      }

      if( typeof options.templateOptions !== 'undefined'){
        var compiled = template( options.message );
        options.message = compiled( options.templateOptions);
      }

      opts.message = options.message || opts.message;
      opts.default = options.default || opts.default;

      inq.prompt([opts]).then(function(res) {

        if (res.val) {
          cb(null, file);
        }

      });

      prompted = true;
    });
  },
 it('should cache bust asset references', function(done) {
   var file = new File({
     path: __dirname,
     contents: null
   });
   es.readArray([file])
     .pipe(buster({
       hashes: hashes,
       assetURL: 'https://example.com'
     }))
     .pipe(es.map(function(file, cb) {
       assert.ok(file.isNull());
       cb(null, file);
     }))
     .pipe(es.wait(function(err) {
       assert.isNull(err, 'Unexpected error');
       done();
     }));
 });
Example #10
0
    return new Promise((resolve, reject) => {
      var results = [];
      var expr = new RegExp(pattern);

      request
        .get(url)
        .on('error', (e) => reject)
        .pipe(es.split())
        .pipe(es.map((line, callback) => {
          var match;

          while (match = expr.exec(line)) {
            results.push(match[1]);
          }

          callback(null, line);
        }))
        .pipe(es.wait(() => resolve(results)));
    });
Example #11
0
function patchExecutable(opts) {
	return es.map(function (f, cb) {
		if (f.relative !== 'electron.exe' || process.platform !== 'win32') {
			return cb(null, f);
		}

		var patch = {
			'version-string': {
				CompanyName: opts.companyName || 'GitHub, Inc.',
				FileDescription: opts.productName,
				LegalCopyright: opts.copyright || 'Copyright (C) 2014 GitHub, Inc. All rights reserved',
				ProductName: opts.productName,
				ProductVersion: opts.productVersion
			}
		};

		if (opts.winIcon) {
			patch.icon = opts.winIcon;
		}

		var tempPath = temp.path();
		var ostream = fs.createWriteStream(tempPath);
		
		f.contents.pipe(ostream);
		ostream.on('finish', function () {
			rcedit(tempPath, patch, function (err) {
				if (err) { return cb(err); }

				fs.readFile(tempPath, function (err, data) {
					if (err) { return cb(err); }

					f.contents = data;

					fs.unlink(tempPath, function (err) {
						if (err) { return cb(err); }
						
						cb(null, f);
					})
				});
			});
		});
	});
}
Example #12
0
var cssLintPlugin = function(options) {
  if (!options) options = {};

  var ruleset = {};

  // Read CSSLint options from a specified csslintrc file.
  if (typeof options === 'string') {
    // Don't catch readFile errors, let them bubble up
    var externalOptions = fs.readFileSync('./'+options);

    try {
      options = JSON.parse(externalOptions);
    }
    catch(err) {
      throw new Error('Error parsing csslintrc: '+err);
    }
  }

  // Build a list of all available rules
  csslint.getRules().forEach(function(rule) {
    ruleset[rule.id] = 1;
  });

  for (var rule in options) {
    if (!options[rule]) {
      // Remove rules that are turned off
      delete ruleset[rule];
    }
    else {
      ruleset[rule] = options[rule];
    }
  }

  return es.map(function(file, cb) {
    var report = csslint.verify(String(file.contents), ruleset);

    // send status down-stream
    file.csslint = formatOutput(report, file, options);

    cb(null, file);
  });
};
Example #13
0
router.get('/:contractName/:contractAddress\.:extension?', function (req, res) {
  var contractName = req.params.contractName;
  var extension = req.params.extension;
  var contractAddress = req.params.contractAddress;

  console.log('extension was matched: ' + extension);

  var contractMetaAddressStream = helper.contractsMetaAddressStream(contractName,contractAddress)
      .pipe( helper.collect() )
      .pipe( es.map(function (data,cb) {
        var contractData = {};
        contractData.contractMeta = data[0];

        cb(null,contractData);
      }))
       
  var configStream = helper.configStream();
  var fusedStream = helper.fuseStream([configStream,contractMetaAddressStream])

  fusedStream
       .on('error', function (err) { 
         console.log("error, contract not found");
         res.send(err);
       })

       .on('data', function (data) {
         console.log("there's data!");
         if (typeof data.contractMeta === 'undefined') { 
           res.send("contract metadata not found");
           return;
         }

         if (extension === 'html') { 
           data.txFailedHandlerCode = "function txFailHandler(e) { $('#passwordModal').modal('show'); }";
           data.txFailedHandlerName = "txFailHandler";
           contractTemplate.render(data, res); 
         } else { 
           console.log('extension not html, assume json');
           res.send(JSON.stringify(data.contractMeta)); 
         }
       })
});
Example #14
0
gulp.task('html'), function() {
  return gulp.src('./dev/**/*.md')
    .pipe(frontmatter({
      property: 'meta'
    }))
    .pipe(marked())
    .pipe(ssg(site, {
      property: 'meta'
    }))
    .pipe(es.map(function(file, cb) {
      var html = handlebars.render(file.meta.layout, {
        page: file.meta,
        site: site,
        content: String(file.contents)
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    .pipe(gulp.dest('./build'));
}
Example #15
0
/**
 * Pipe for compiling templates, no files output
 *
 * @param {object} templateStore - reference to store templates
 * @return {stream}
 */
function templates(templateStore) {

    return es.map(function(file, cb) {

        if (file.isNull()) {
            return;
        }
        if (file.isStream()) {
            cb(new gutil.PluginError('gulp-styleguide',  'Streaming not supported'));
            return;
        }
        var templateName = path.join(
            path.dirname(file.relative),
            path.basename(file.relative, path.extname(file.relative))
        );
        templateStore[templateName] = hogan.compile(file.contents.toString('utf8'));

        cb(null, file);
    });
}
    .pipe(es.writeArray(function(err, filterFeatures) {
        process.stdin
            .pipe(JSONStream.parse())
            .pipe(es.map(function(feature, cb) {
                filterFeatures.forEach(function(filterFeature) {
                    if (intersects(feature, filterFeature)) {
                        // if intersects with one of the filter features, then filter it out
                        cb();
                    }
                });

                // we found no intersections so this feature is good to pass along
                cb(null, feature);
            }))
            .pipe(JSONStream.stringify(false))
            .pipe(process.stdout)
            .on('error', function(e) {
                console.log(e);
            });
    }));
Example #17
0
gulpEslint.format = function (formatter, writable) {
	var results = [];
	formatter = util.resolveFormatter(formatter);
	writable = util.resolveWritable(writable);

	return estream.map(function (file, output) {
		if (file.eslint) {
			results.push(file.eslint);
		}
		output(null, file);

	}).once('end', function () {
		// Only format results if files has been lint'd
		if (results.length) {
			util.writeResults(results, formatter, writable);
		}
		// reset buffered results
		results = [];
	});
};
Example #18
0
cssLintPlugin.reporter = function(customReporter) {
  var reporter = defaultReporter;

  if (typeof customReporter === 'function') {
    reporter = customReporter;
  }

  if (typeof reporter === 'undefined') {
    throw new Error('Invalid reporter');
  }

  return es.map(function(file, cb) {
    // Only report if CSSLint was ran and errors were found
    if (file.csslint && !file.csslint.success) {
      reporter(file);
    }

    return cb(null, file);
  });
};
Example #19
0
module.exports = function(folder, opt) {
  if (!opt) opt = {};
  // TODO: support opt.cwd

  folder = path.resolve(folder);

  // TODO: clean this crap up
  // createOutputStream should be a mirror of createInputStream file-wise
  function saveFile (file, cb) {
    var writePath = path.join(folder, file.relative);
    var writeFolder = path.dirname(writePath);

    mkdirp(writeFolder, function(err){
      if (err) return cb(err);
      writeFile(writePath, file, cb);
    });
  }
  var stream = es.map(saveFile);
  return stream;
};
Example #20
0
 socrata.processStream = function (dataStream, meta, callback) {
   var geojson = { type: 'FeatureCollection', features: [] }
   dataStream
     .pipe(JSONStream.parse('*'))
     .pipe(es.map(function (data, cb) {
       socrata.toGeojson([data], meta, function (err, converted) {
         if (err) {
           cb(err)
         }
         geojson.features.push(converted.features[0])
         cb()
       })
     }))
     .on('error', function (err) {
       callback(err)
     })
     .on('end', function () {
       callback(null, geojson)
     })
 }
export function releaseDest(folderName='') {
  const prefixReleaseToDestStream = map(async (file, callback) => {
    try {
      const version = getNewVersion();
      if (file.path.indexOf(`pui-v${version}`) === -1) {
        file.path = path.join(file.base, `pui-v${version}`, folderName, file.relative);
      }
      callback(null, file);
    }
    catch(e) {
      console.error(error.stack);
      callback(e);
    }
  });

  return pipeline(
    prefixReleaseToDestStream,
    gulp.dest('release/')
  );
}
Example #22
0
module.exports = function(){
	return es.map(function (file, cb){
		rimraf(file.path, function (err) {
			if (!err || !fs.existsSync(file.path)) {
				return cb(null, file);
			}
			rimraf(file.path, function (err) {
				if (!err || !fs.existsSync(file.path)) {
					return cb(null, file);
				}
				rimraf(file.path, function (err) {
					if (!err || !fs.existsSync(file.path)) {
						return cb(null, file);
					}
					return cb(err);
				});
			});
		});
	});
};
var appendVersionPlugin = function (extensions, v) {
  var version;
  if (v) {
    version = v
  } else {
    var PJ = appRoot.require('package.json')
    version = PJ && PJ.version
  }
  return map(function (file, cb) {
    if (!file) {
      throw new PluginError('gulp-rev-append', 'Missing file option for gulp-version-append.')
    }
    if (!file.contents) {
      throw new PluginError('gulp-rev-append', 'Missing file.contents required for modifying files using gulp-rev-append.')
    }

    file.contents = new Buffer(file.contents.toString().replace(versionRegex(extensions), '$1' + version + '$3'))
    cb(null, file)
  })
}
Example #24
0
var server = net.createServer(function(stream) {
  // we console log a few things to give us something to look at during a test run
  console.log("connected")
  stream.on('end', function() { console.log("disconnected") })
  es.pipeline(
      stream,
      es.split(),
      es.parse(),
      es.map(function(parsed, cb) {
        console.log(parsed)
        // We look for the registration, pass everything else on...
        if (parsed && parsed.action == 'register' && parsed.clientID) {
          master.addWorker({clientID: parsed.clientID, stream: stream})
        } else if (parsed) {
          master.recvMsg(parsed)
        }
        cb()
      })
  )
})
Example #25
0
var revPlugin = function revPlugin() {

  return map(function(file, cb) {

    var contents = file.contents.toString();
    var lines = contents.split('\n');
    var i, length = lines.length;
    var line;
    var groups;
    var dependencyPath;
    var data, hash;

    if(!file) {
      throw new PluginError('gulp-rev', 'Missing fileName option for gulp-rev.');
    }

    for(i = 0; i < length; i++) {
      line = lines[i];
      groups = FILE_DECL.exec(line);
      if(groups && groups.length > 1) {
        dependencyPath = path.join(path.dirname(file.path), groups[1]);
        try {
          data = fs.readFileSync(dependencyPath);
          hash = crypto.createHash('md5');
          hash.update(data.toString(), 'utf8');
          line = line.replace(groups[2], hash.digest('hex'));
        }
        catch(e) {
          // fail silently.
        }
      }
      lines[i] = line;
      FILE_DECL.lastIndex = 0;
    }

    file.contents = new Buffer(lines.join('\n'));
    cb(null, file);

  });

};
Example #26
0
module.exports = function(params) {
    var params = params || {};
    function htmtojson(file, callback) {

        if (file.isNull()) {
            return callback(null, file);
        }

        if (file.isStream()) {
            throw new gutil.PluginError('gulp-html-to-json', 'stream not supported');
        }

        if (file.isBuffer()) {

            var outputJson = {};

            htmltojsonController(String(file.contents), file.path, outputJson);

            params.filename || (params.filename = indName(file.path));
            params.prefix || (params.prefix = "");
            params.useAsVariable || (params.useAsVariable = false);
            params.isAngularTemplate || (params.isAngularTemplate = false);

            if(params.isAngularTemplate) {
                var output = angularTemplate(params, outputJson);
                file.path = replaceFilename(file.path, params.filename, params.useAsVariable)
                file.contents = new Buffer(output);

            } else {
                file.path = replaceFilename(file.path, params.filename, params.useAsVariable)

                var exVars = (params.useAsVariable) ? "var " + params.filename + "=" : ""
                file.contents = new Buffer(exVars + JSON.stringify(outputJson));
            }
        }

        callback(null, file);
    }

    return es.map(htmtojson)
}
Example #27
0
exports.connect = function (server) {
    var stream = es.merge(server.proc.stdout, server.proc.stderr).pipe(es.split());
    stream.setMaxListeners(20);
    stream.pipe(es.map(require("./parsers/file-logger").bind(null, server)));
    stream.pipe(es.map(require("./parsers/dropper").bind(null, server)));
    stream.pipe(es.map(require("./parsers/sessions").bind(null, server)));
    stream.pipe(es.map(require("./parsers/drivers").bind(null, server)));
    stream.pipe(es.map(require("./parsers/laptimes").bind(null, server)));
    stream.pipe(es.map(
        function(server, line, cb) {
            server.emit(acEvents.server.output, line);
            cb(null, line);
        }.bind(null, server)
    ));
};
Example #28
0
gulp.task("convert", function() {
	return gulp.src("./src/**/*.md")
		.pipe(marked({
			highlight: function(code, lang) {
				if(lang) {
					return highlight.highlight(lang, code).value.split("\n").map(function(p, i) {
						return "<span class=\"line-line\"><span class=\"line-number\">" + (i + 1) + "</span><span class=\"line-contents\">" + p + "</span></span>";
					}).join("\n");
					//return highlight.highlight(lang, code).value;
				} else {
					return code;
				}
			},
			renderer:renderer
		}))
		/*
		.pipe(ssg({
			title: "Cadmus"
		}, {
			property:"meta",
			baseUrl:"/.dist/"
		}))*/
		.pipe(es.map(function(file, cb) {
			var x = file.path.split("/");
			var contents = String(file.contents);
			dust.render("./templates/page.dust", {contents:contents, title: x[x.length -1].split(".")[0].split(":")[1]}, function(err, contents) {
				if(err) {
					console.log(err);
					cb(err);
				} else {
					file.contents = Buffer(contents);
					cb(null, file);
				}
			});
		}))
		.pipe(rename(function(path) {
			path.basename = path.basename.replace(/\s+/g, '-');
			path.extname = ".html";
		}))
		.pipe(gulp.dest("./dist"));
});
Example #29
0
function loadSourcemaps() {
    const input = es.through();
    const output = input
        .pipe(es.map((f, cb) => {
        if (f.sourceMap) {
            cb(undefined, f);
            return;
        }
        if (!f.contents) {
            cb(new Error('empty file'));
            return;
        }
        const contents = f.contents.toString('utf8');
        const reg = /\/\/# sourceMappingURL=(.*)$/g;
        let lastMatch = null;
        let match = null;
        while (match = reg.exec(contents)) {
            lastMatch = match;
        }
        if (!lastMatch) {
            f.sourceMap = {
                version: '3',
                names: [],
                mappings: '',
                sources: [f.relative.replace(/\//g, '/')],
                sourcesContent: [contents]
            };
            cb(undefined, f);
            return;
        }
        f.contents = Buffer.from(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
        fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => {
            if (err) {
                return cb(err);
            }
            f.sourceMap = JSON.parse(contents);
            cb(undefined, f);
        });
    }));
    return es.duplex(input, output);
}
Example #30
0
gulp.task('release-generate-changelog', () => {
  const newChangesStream = changelog(
    {preset: 'angular', warn: log},
    {},
    {},
    {noteKeywords: ['BREAKING CHANGE', 'DEPRECATION WARNING']},
    {transform: commitTransform}
  );

  const oldChangesStream = gulp.src('CHANGELOG.md')
    .pipe(map((file, cb) => cb(null, file.contents)));

  const latestChangesFileStream = newChangesStream
    .pipe(source('LATEST_CHANGES.md'));

  const changelogFileStream = series(newChangesStream, oldChangesStream)
    .pipe(source('CHANGELOG.md'));

  return merge(changelogFileStream, latestChangesFileStream)
    .pipe(gulp.dest('.'));
});