gulp.task('jshint', function() {
  return gulp.src('./{controllers,decorators,directives,filters,services,routes}/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish))
    .pipe(map(function (file, cb) {
      if (!file.jshint.success) {
        totalLintErrors += file.jshint.results.length;
        exitCode = 1;
      }
      cb(null, file);
    }))
    .on('end', function () {
      lintOnEnd();
      if (exitCode) {
        process.emit('exit');
      }
    });
});
示例#2
0
module.exports = function(options) {
   var ops = {
      execute: options && options.execute ? options.execute : false
   };

   return map(function(file, cb) {
      var error = null, transpiled;

      // execute to css
      if (ops.execute) {        
        var b = browserify(intoStream(file.contents), {
          transform: [ cssxTransform ],
          basedir: path.dirname(file.path)
        });        
        b.bundle(function (err, buff) {          
          var codeToRun = buff.toString('utf8'), func, generatedCSS, css;

          try {
            func = new Function('cssx', codeToRun);
            func(cssx);
            generatedCSS = cssx.getStylesheets().map(function (stylesheet) {
              return stylesheet.compileImmediate().getCSS();
            });
            css = generatedCSS.join('');
          } catch (err) {
            cb(err); return;
          }
          file.contents = new Buffer(css);
          cb(error, file);
        });  
      // transpile
      } else {
         try {
            transpiled = cssxTranspiler(file.contents.toString('utf8'))
         } catch (err) {
            cb(err);
            return;
         }
         file.contents = new Buffer(transpiled);
         cb(error, file);
      }

   });
};
示例#3
0
gulp.task('concat:bower', function () {
	console.log('-------------------------------------------------- CONCAT :bower');

	var jsFilter = gulpPlugins.filter('**/*.js'),
		cssFilter = gulpPlugins.filter('**/*.css'),
		assetsFilter = gulpPlugins.filter(['!**/*.js', '!**/*.css', '!**/*.scss']);

	var stream = gulp.src(bowerFiles(bowerConfig), {base: SETTINGS.src.bower})
		.pipe(jsFilter)
		.pipe(gulpPlugins.concat('_bower.js'))
		.pipe(gulpPlugins.if(isProduction, gulpPlugins.uglify()))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe(gulpPlugins.sass())
		.pipe(map(function (file, callback) {
			var relativePath = path.dirname(path.relative(path.resolve(SETTINGS.src.bower), file.path));

			// CSS path resolving
			// Taken from https://github.com/enyojs/enyo/blob/master/tools/minifier/minify.js
			var contents = file.contents.toString().replace(/url\([^)]*\)/g, function (match) {
				// find the url path, ignore quotes in url string
				var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(match),
					url = matches[3] || matches[5] || matches[6];

				// Don't modify data and http(s) urls
				if (/^data:/.test(url) || /^http(:?s)?:/.test(url)) {
					return 'url(' + url + ')';
				}
				return 'url(' + path.join(path.relative(SETTINGS.build.bower, SETTINGS.build.app), SETTINGS.build.bower, relativePath, url) + ')';
			});
			file.contents = new Buffer(contents);

			callback(null, file);
		}))
		.pipe(gulpPlugins.concat('_bower.css'))
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(cssFilter.restore())
		.pipe(assetsFilter)
		.pipe(gulp.dest(SETTINGS.build.bower))
		.pipe(assetsFilter.restore())
		.pipe(gulpPlugins.connect.reload());
	return stream;
});
示例#4
0
 function testVinylFileStream(filestream, action, runningLog, loggingOptions, getActionOptions, callback) {
     var actionComment = 'from vinyl file',
         testStartTimestamp = (new Date()).toISOString();
     loggingOptions = loggingOptions || {
         supressOutputs: false
     };
     getActionOptions = (typeof getActionOptions === 'function') ? getActionOptions : defaultActionOptions;
     filestream
         .pipe(mapStream(function (vinylFile, cb) {
             var file = { //just to be explicit about what uglyfly actually looks at
                     path: vinylFile.path,
                     contents: vinylFile.contents
                 },
                 options = getActionOptions(file.path, action);
             runAndLog(action, file, options, testStartTimestamp, actionComment, runningLog, loggingOptions, cb);
         })).on('end', function (err) {
             callback(err, runningLog)
         });
 }
示例#5
0
文件: build.js 项目: imweb/tryjs
module.exports = function () {
  return map(function (file, cb) {
    if (file.isNull()) {
      cb(null, file);
    }

    if (file.isBuffer()) {
      var self = this;
      build(file, function (file) {
        cb(null, file);
      });
      return;
    }

    if (file.isStream()) {
      return cb(new Error('Streams are not supported!'));
    }
  })
}
示例#6
0
文件: gulpfile.js 项目: DariusX/camel
function createSymlinks() {
    return src('../components/*/src/main/docs/*.adoc')
        .pipe(map((file, done) => {
            // this flattens the output to just .../pages/....adoc
            // instead of .../pages/camel-.../src/main/docs/....adoc
            file.base = path.dirname(file.path);
            done(null, file);
        }))
        // Antora disabled symlinks, there is an issue open
        // https://gitlab.com/antora/antora/issues/188
        // to reinstate symlink support, until that's resolved
        // we'll simply copy over instead of creating symlinks
        // .pipe(symlink('components/modules/ROOT/pages/', {
        //     relativeSymlinks: true
        // }));
        // uncomment above .pipe() and remove the .pipe() below
        // when antora#188 is resolved
        .pipe(dest('components/modules/ROOT/pages/'));
}
示例#7
0
文件: index.js 项目: 124378/Blitz
module.exports = function (options) {
	return map(function (file, cb) {
		if (file.isNull()) {
			return cb(null, file);
		}

		if (file.isStream()) {
			return cb(new gutil.PluginError('gulp-cssmin', 'Streaming not supported'));
		}

		if (['.css'].indexOf(path.extname(file.path)) === -1) {
			gutil.log('gulp-cssmin: Skipping unsupported css ' + gutil.colors.blue(file.relative));
			return cb(null, file);
		}

		tempWrite(file.contents, path.extname(file.path), function (err, tempFile) {
			if (err) {
				return cb(new gutil.PluginError('gulp-cssmin', err));
			}

			fs.stat(tempFile, function (err, stats) {
				if (err) {
					return cb(new gutil.PluginError('gulp-cssmin', err));
				}

				options = options || {};

				fs.readFile(tempFile, { encoding : 'UTF-8'}, function(err, data) {
					if (err) {
						return cb(new gutil.PluginError('gulp-cssmin', err));
					}
					var minimized = new CleanCSS(options).minify(data).styles;
					if (options.showLog) {
						gutil.log('gulp-cssmin:', gutil.colors.green('✔ ') + file.relative);
					}
					file.contents = new Buffer(minimized);
					cb(null, file);
				});

			});
		});
	});
};
示例#8
0
gulp.task('p_replace', ['p_copy_img'], function(){
    var assets = require('./dist/static/assets.json'); //要替换的文件路径
    var findContent = function(text){
        for(var key in assets){
            var val = assets[key];
            var oriPath = key.replace('.min', '');
            text = text.replace(new RegExp('/?'+ oriPath, 'gmi'), setting.staticHosts + val);
        }
        return text;
    };
    return gulp.src('dist/**/*.{html,js,css}', { base: 'dist' })
        .pipe(map(function(file, cb){
            var contents = String(file.contents);
            var newContent = findContent(contents);
            file.contents = new Buffer(newContent);
            cb(null, file);
        }))
        .pipe(gulp.dest('dist'));
});
示例#9
0
module.exports = function(){
  'use strict';

  return map(function(file,callback){
    var filenameLong = file.path.replace(process.cwd(), '');
    var filenameShort = file.path.split(/\/|\\/).pop();


    //Check if file.stat exists (gulp.concat removes it for example)
    var filesize = file.stat ? getFileSize(file.stat.size) : getFileSize(Buffer.byteLength(String(file.contents)));

    // gutil.log(process.cwd());

    gutil.log(gutil.colors.yellow("  >>> piping asset file"), filenameLong, ":",gutil.colors.blue(filesize));

    callback(null,file)
  });

};
示例#10
0
 tasks = folders.map(function(folder) {
     var src = [path.join(fileFolder, folder, '/**/*.svg')];
     var dist = path.join(targetFolder);
     return gulp.src(src)
         .pipe($.changed(dist, {
             extension: '.svg',
             hasChanged: $.changed.compareSha1Digest
         }))
         .pipe($.svgSymbols({
             id: opt.id +'-%f',
             templates: ['default-svg']
         }))
         .pipe(map(function(file, cb){
             file.path = opt.name +'_'+ folder +'.svg';
             cb(null, file);
         }))
         .pipe(gulp.dest(dist))
         .pipe(reload({ stream: true }));
 });
示例#11
0
module.exports = function (opts) {
  config.set(opts);

  var stream = map(function (file, fn) {
    if (file.isNull()) {
      return fn(file);
    }

    if (file.isBuffer()) {
      return make(file, fn);
    }

    if (file.isStream()) {
      this.emit('error', new Error('Streams are not supported!'));
      return fn(file);
    }
  });
  return stream;
}
示例#12
0
文件: model.js 项目: aantthony/mong
  return function () {
    var prototype = this.prototype
    var output = mapStream(function (data, callback) {
      data[PROTO] = prototype
      callback(null, data)
    })

    var args = arguments

    get(this)
    .then(function (c) {
      var input = c[name].apply(c, args)
      input.pipe(output)
    })
    .then(null, function (err) {
      output.emit('error', err)
    })
    return output
  }
示例#13
0
function html2js(template) {
  return map(escape);

  function escape(file, cb) {
    const path = $.util.replaceExtension(file.path, '.js');
    const content = file.contents.toString();
    /* eslint-disable quotes */
    const escaped = content
      .replace(/\\/g, '\\\\')
      .replace(/'/g, "\\'")
      .replace(/\r?\n/g, "\\n' +\n    '");
    /* eslint-enable */
    const body = template.replace('$$', escaped);

    file.path = path;
    file.contents = new Buffer(body);
    cb(null, file);
  }
}
示例#14
0
gulp.task('dox', function () {
  return gulp.src(['./src/**/mermaidAPI.js'])
    .pipe(filelog())
    .pipe(dox({
      'raw': true
    }))
    .pipe(map(function (file, done) {
      var json = JSON.parse(file.contents.toString())
      var i
      var str = ''
      for (i = 0; i < json.length; i++) {
        str = str + json[i].description.full + '\n'
      }
      file.contents = Buffer.from(str)
      done(null, file)
    }))
    .pipe(extReplace('.md'))
    .pipe(gulp.dest('./build/content'))
})
示例#15
0
文件: index.js 项目: Darren-H/tpcalc
var jshintPlugin = function(opt){
  var lint = require('./lint')(opt);
  var fileIgnored = require('./file-ignored');

  return map(function (file, cb) {
    if (file.isNull()) return cb(null, file); // pass along
    if (file.isStream()) return cb(new PluginError('gulp-jshint', 'Streaming not supported'));

    fileIgnored(file, function (err, ignored) {
      if (err || ignored) return cb(err, file);
      lint(file, function (err, output) {
        if (err) return cb(err);

        file.jshint = output;
        cb(null, file);
      });
    });
  });
};
示例#16
0
module.exports = function(options){
	if (!options) {
		options = {};
	}

	if (options.force && typeof options.force !== 'boolean') {
		options.force = false;
	}

	return map(function (file, cb){
		var cwd = file.cwd || process.cwd();
		// For safety always resolve paths
		var filepath = path.resolve(cwd, file.path);
		var relativeFromCwd = path.relative(cwd, filepath);

		if (relativeFromCwd === '') {
			gutil.log('gulp-rimraf: Cannot delete the current working directory. (' + filepath + ')');
			return cb(null, file);
		}

		if (!options.force && relativeFromCwd.substr(0, 2) === '..') {
			gutil.log('gulp-rimraf: Cannot delete files or folders outside the current working directory. (' + filepath + ')');
			return cb(null, file);
		}

		rimraf(filepath, function (err) {
			if (!err || !fs.existsSync(filepath)) {
				return cb(null, file);
			}
			rimraf(filepath, function (err) {
				if (!err || !fs.existsSync(filepath)) {
					return cb(null, file);
				}
				rimraf(filepath, function (err) {
					if (!err || !fs.existsSync(filepath)) {
						return cb(null, file);
					}
					return cb(err);
				});
			});
		});
	});
};
示例#17
0
module.exports = function (options) {
	return map(function (file, cb) {
		if (file.isNull()) {
			return cb(null, file);
		}

		if (file.isStream()) {
			return cb(new gutil.PluginError('gulp-combine-mq', 'Streaming not supported'));
		}

		tempWrite(file.contents, path.extname(file.path), function (err, tempFile) {
			if (err) {
				return cb(new gutil.PluginError('gulp-combine-mq', err));
			}

			fs.stat(tempFile, function (err, stats) {
				if (err) {
					return cb(new gutil.PluginError('gulp-combine-mq', err));
				}

				options = options || {};

				fs.readFile(tempFile, { encoding : 'UTF-8'}, function(err, data) {
					if (err) {
						return cb(new gutil.PluginError('gulp-combine-mq', err));
					}

					var processed = combineMq.parseCssString(data, {});

					if (options.showLog) {
						gutil.log('gulp-combine-mq:', gutil.colors.green('✔ ') + file.relative);
					}

					file.contents = new Buffer(processed);

					cb(null, file);
				});

			});
		});
	});
};
示例#18
0
    module.exports = function(spaces) {
        return streamMap(function(file, cb) {
            var replacer = through(function(data) {
                var formatted = JSON.stringify(JSON.parse(data.toString()), null, spaces);

                if (true || file.isBuffer()) {
                    file.contents = new Buffer(formatted);
                    cb(null, file);
                } else {
                    file.contents = through();
                    cb(null, file);

                    file.contents.write(new Buffer(formatted));
                    file.contents.end();
                }
            });

            file.pipe(replacer);
        });
    };
示例#19
0
jshintPlugin.reporter = function (reporter) {
  if (!reporter) reporter = 'default';
  if (reporter === 'fail') {
    return jshintPlugin.failReporter();
  }
  var rpt = jshintPlugin.loadReporter(reporter);

  if (typeof rpt !== 'function') {
    throw new Error('Invalid reporter');
  }

  // return stream that reports stuff
  return map(function (file, cb) {
    // nothing to report or no errors
    if (!file.jshint || file.jshint.success) return cb(null, file);

    rpt(file.jshint.results, file.jshint.data, file.jshint.opt);
    return cb(null, file);
  });
};
示例#20
0
gulp.task('css', function () {
    gulp.src('./src/css/main.scss')
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer({
            browsers: options.browsers,
            remove: true // removes unneeded prefixes from source
        }))
        .pipe(plugins.cssmin())
        .pipe(plugins.header(options.header.join('\n') + '\n'))
        .pipe(plugins.sourcemaps.write('.'))
        .pipe(map(function (file, cb) {
            notifier.notify({
                title: 'Gulp',
                message: 'SASS compiled.'
            });
            cb(null, file);
        }))
        .pipe(gulp.dest('./dist/css'));
});
示例#21
0
tokenlintPlugin.report = (reporter) =>
  map(function (file, cb) {
    let error = null;

    if (file.tokenlint.errors) {
      if (file.tokenlint.errors.length) {
        error = new gutil.PluginError('tokenlint', `Found ${file.tokenlint.errors.length} linting error(s)`);
      }
      if (reporter === 'json') {
        tokenReporter(file.tokenlint);
      } else if (reporter === 'verbose') {
        verboseReporter(file.tokenlint, file);
      } else if (_.isFunction(reporter)) {
        reporter(file.tokenlint, file);
      }
    }

    // Pass file
    cb(error, file);
  });
示例#22
0
module.exports = function ( obj ) {
  'use strict';

  function hash( file, cb ) {
    if ( ! obj ) {
      throw new PluginError( PLUGIN_NAME, 'obj missing' );
    }

    var dir      = path.dirname( file.path );
    var ext      = path.ext( file.path );
    var filename = path.basename( file.path, ext );
    var checksum = crypto.md5( file.content );

    file.path = path.join( dir, filename + checksum + ext );

    cb( null, file );
  }

  return map( hash );
};
示例#23
0
module.exports = function(opts) {
  if(!opts) opts = {};
  if(!semver.inc('0.0.1', opts.type)) opts.type = false;
  if(!opts.indent) opts.indent = 2;
  // Map each file to this function
  function modifyContents(file, cb) {
    // Remember that contents is ALWAYS a buffer
    if(file.isNull()) return cb(null, file);
    if(file.isStream()) return cb(new Error('gulp-bump: streams not supported'));

    var json = JSON.parse(file.contents.toString());
    json.version = semver.valid(opts.version) || semver.inc(json.version, opts.type || 'patch');
    file.contents = new Buffer(JSON.stringify(json, null, opts.indent) + '\n');

    cb(null, file);
  }

  // Return a stream
  return map(modifyContents);
};
示例#24
0
gulp.task("output-to-file", function(){
    return gulp.src(["invalid.ts", "invalid2.ts"])
        .pipe(tslint())
        .pipe(map(function(file, done) {
            // Add the tslint errors in prose format
            if (file.tslint.output) {
                file.contents = new Buffer(
                    JSON.parse(file.tslint.output)
                        .map(tslint.proseErrorFormat).join("\n")
                );
            } else {
                file.contents = new Buffer("");
            }

            done(null, file);
        }))
        // Concat and save the errors
        .pipe(concat("tslint-report.txt"))
        .pipe(gulp.dest("./"));
});
示例#25
0
gulpEslint.format = function (formatter, writable) {
	var results = [];
	formatter = util.resolveFormatter(formatter);
	writable = util.resolveWritable(writable);

	return 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 = [];
	});
};
示例#26
0
文件: fix-url.js 项目: imweb/Ques
 decl.value = decl.value.replace(REG_URLS, function (all, $1, file, $3) {
   src = path.join(IMG_PATH, file);
   try {
     hex = cal(fs.readFileSync(src));
   } catch(e) {
     console.error('[Font No Exist]', e.message);
     hex = '';
   }
   hexFile = file.replace(REG_PREFIX, '.' + hex + '.$1');
   var _file = file.match(REG_FILE)[1]
     , _hexFile = hexFile.match(REG_FILE)[1];
   // console.log(src);
   gulp.src([src])
     .pipe(map(function (f, fn) {
       f.path = f.path.replace(_file, _hexFile);
       fn(null, f);
     }))
     .pipe(gulp.dest('./dist/img'))
   return 'url(' + URL.resolve(opts.cdn || '../', 'img/' + _hexFile + ($3 || '')) + ')';
 });
示例#27
0
 var translateFile = transform(function(filename) {
   return map(function(data, done) {
     var j = JSON.parse(data);
     var translateCount = 0;
     var appTranslated = traverse(j).forEach(function(x) {
       if(typeof x !== 'object') {
         var self = this;
         translateCount++;
         translate.translate(x, { to: argv.to, key: YANDEX_API_KEY }, function(err, res) {
           self.update(res.text.toString());
           translateCount--;
           if(translateCount === 0) {
             var finishedJSON = JSON.stringify(appTranslated);
             gutil.log(gutil.colors.green('Translated ' + filename));
             done(null, finishedJSON);
           }
         });
       }
     });
   });
 });
示例#28
0
module.exports = function(opts) {
  if(!opts) opts = {};
  if(!semver.inc('0.0.1', opts.type)) opts.type = false;
  if(!opts.indent) opts.indent = 2;
  if(!opts.key) opts.key = 'version';

  function modifyContents(file, cb) {

    if(file.isNull()) return cb(null, file);
    if(file.isStream()) return cb(new Error('gulp-bump: streams not supported'));

    var json = JSON.parse(file.contents.toString());
    json[opts.key] = semver.valid(opts[opts.key]) || semver.inc(json[opts.key], opts.type || 'patch');
    file.contents = new Buffer(JSON.stringify(json, null, opts.indent) + '\n');
    gutil.log('Bumped to version: '+gutil.colors.cyan(json[opts.key]));
    cb(null, file);
  }


  return map(modifyContents);
};
示例#29
0
  client.getVenues = function getVenues(params) {

    var url = [
      'https://api.foursquare.com/v2/venues/search?',
      querystring.stringify(params) + '&',
      querystring.stringify(credentials)
    ].join('')

    return hyperquest(url)
      .pipe(JSONStream.parse('response.venues.*'))
      .pipe(mapStream(function (venueRef, callback) {

        var that = this

        client.getVenue({
          venueId: venueRef.id
        }).pipe(through(function(venue) {
          callback(null, venue)
        }))
      }))
  }
示例#30
0
 gulp.task(taskName, function () {
   var FILE_SPLIT_REG = /^(.+?)(([^\/]+?)(?:\.([^.]+))?)$/;
   var fullBuildPath = path.resolve( path.normalize( buildPath +'/'+ siteConf.src +'/'+ sitePrefixTemplate ) );
   var fullSrcPath = path.resolve( siteConf.src );
   return gulp.src([
     path.normalize( siteConf.src +'/**/*.js' ),
     '!'+ path.normalize( siteConf.src +'/**/*.babel.js' ),
     '!'+ path.normalize( siteConf.src +'/**/*.jsx' ),
     '!'+ path.normalize( siteConf.src +'/**/*.server.js' ),
     '!'+ path.normalize( siteConf.src +'/server/**/*.js' ),
     '!'+ path.normalize( siteConf.src +'/vendor/**/*.js' ),
   ])
   .pipe(map(function(file, cb) {
     var targetPath = path.normalize( fullBuildPath +'/'+ file.path.slice( fullSrcPath.length ) );
     FILE_SPLIT_REG.test( targetPath );
     var targetDir = RegExp.$1;
     var fileName = RegExp.$2;
     return gulpWebpack({
         entry: file.path,
         module: {
           loaders: [
             { test: /\.html$/, loader: 'html' },
             { test: /\.js$/, exclude: /(node_modules|vendor)/, loader: 'babel-loader' },
           ]
         },
         output: {
           path: '',
           filename: fileName
         }
       })
       .on('error', notify.onError('JS Compile Error'))
       .on('error', function( e ){ gutil.log(e.stack); })
       .pipe($.sourcemaps.write())
       .pipe($.uglify())
       .on('error', notify.onError('JS Uglify Error'))
       .on('error', function( e ){ gutil.log(e.stack); })
       .pipe(gulp.dest( targetDir ))
       .on('finish', function(){ cb(null, file); });
   }));
 });