示例#1
0
文件: docker.js 项目: drinimar/docker
Docker.prototype.addFileToTree = function(filename) {
  // Split the file's path into the individual directories
  filename = filename.replace(new RegExp('^' + path.sep.replace(/([\/\\])/g, '\\$1')), '');
  var bits = filename.split(path.sep);

  // Loop through all the directories and process the folder structure into `this.tree`.
  //
  // `this.tree` takes the format:
  // ```js
  //  {
  //    dirs: {
  //      'child_dir_name': { /* same format as tree */ },
  //      'other_child_name': // etc...
  //    },
  //    files: [
  //      'filename.js',
  //      'filename2.js',
  //      // etc...
  //    ]
  //  }
  // ```
  var currDir = this.tree;
  var lastBit = bits.pop();

  bits.forEach(function(bit) {
    if (!currDir.dirs) currDir.dirs = {};
    if (!currDir.dirs[bit]) currDir.dirs[bit] = {};
    currDir = currDir.dirs[bit];
  });
  if (!currDir.files) currDir.files = [];

  if (currDir.files.indexOf(lastBit) === -1) currDir.files.push(lastBit);
};
示例#2
0
 templatesNamesGenerator: function(dustInfo, outputName){
     var sepReg = new RegExp(path.sep.replace(/\\/g, '\\\\'), 'g');
     var realPath = path.relative(dustInfo.relative, outputName);
     var baseName = path.basename(realPath, path.extname(realPath));
     var amdId = path.join(path.dirname(realPath), baseName).replace(sepReg, '/');
     
     return amdId;
 }
示例#3
0
	grunt.registerTask('data-zdump', '3. Dump data with zdump(8).', function (version) {
		version = version || 'latest';

		console.log(path.resolve('zdump'));

		var done      = this.async(),
			zicBase   = path.resolve('temp/zic', version),
			zdumpBase = path.resolve('temp/zdump', version),
			files     = grunt.file.expand({ filter : 'isFile', cwd : 'temp/zic/' + version }, '**/*');

		var zicBaseRegex = new RegExp((zicBase + path.sep).replace(/\\/g,'\\\\'), 'g');
		var pathSepRegex = new RegExp(path.sep.replace('\\','\\\\'), 'g');
		function normalizePaths(output) {
			var result = output.replace(zicBaseRegex, '');
			if (path.sep !== '/') {
				result = result.replace(pathSepRegex, '/')	
			}
			return result;
		}

		function next () {
			if (!files.length) {
				grunt.log.ok('Dumped data for ' + version);
				return done();
			}

			var file = files.pop(),
				src  = path.join(zicBase, file),
				dest = path.join(zdumpBase, file);

			exec('zdump -V ' + src, { maxBuffer: 20*1024*1024 }, function (err, stdout) {
				if (err) { throw err; }

				grunt.file.mkdir(path.dirname(dest));

				if (stdout.length === 0) {
					// on some systems, when there are no transitions then we have
					// to get creative to learn the offset and abbreviation
					exec('zdump UTC ' + src, { maxBuffer: 20*1024*1024 }, function (_err, _stdout) {
						if (_err) { throw _err; }

						grunt.file.write(dest + '.zdump', normalizePaths(_stdout));
						grunt.verbose.ok('Dumped data for ' + version + ':' + file);
		
						next();
					});
					return;
				}

				grunt.file.write(dest + '.zdump', normalizePaths(stdout));
				grunt.verbose.ok('Dumped data for ' + version + ':' + file);

				next();
			});
		}

		next();
	});
示例#4
0
 var filenameToMid = (function () {
     if (pathUtil.sep === '/') {
         return function (filename) {
             return filename;
         };
     }
     else {
         var separatorExpression_1 = new RegExp(pathUtil.sep.replace('\\', '\\\\'), 'g');
         return function (filename) {
             return filename.replace(separatorExpression_1, '/');
         };
     }
 })();
示例#5
0
module.exports = function(options){
	var defaultOptions = {
		descriptionQuotes: '()',
		separator: path.sep,
		escapedSeparator: path.sep.replace('\\', '\\\\'),
		root: 'last folder', //all, last folder, number of root folders (like: 2)
		paintingStrategy: {
			coloring: 'all',// all, last node, number of nodes (like: 2)
			priority: ['green', 'yellow', 'red']
		},
		defaultColor: ''
	};

	var ignore = ['escapedSeparator', 'paintingStrategy'];
	for(optionName in options){
		if(optionName === 'separator'){
			defaultOptions['escapedSeparator'] = options[optionName].replace('\\', '\\\\');
		}

		if(optionName === 'paintingStrategy'){
			for(stategyOption in options['paintingStrategy']){
				defaultOptions['paintingStrategy'][stategyOption] = options['paintingStrategy'][stategyOption];
			}
		}

		if(ignore.indexOf(optionName) === -1){
	    	defaultOptions[optionName] = options[optionName];
		}
	}

	if(defaultOptions['root'] === 'last folder'){
		defaultOptions['root'] = 1;
	}

	if(defaultOptions['paintingStrategy']['coloring'] === 'last point'){
		defaultOptions['paintingStrategy']['coloring'] = 1;
	}

	return function(_paths){
		var paths = clone(_paths);
		if(paths && Array.isArray(paths)){
			return getGroups(paths, defaultOptions).map(function(group){
				console.log(JSON.stringify(getAST(group, defaultOptions), true, 2))
				return CAT(getAST(group, defaultOptions));
			}).join('\n');
		}else{
			return null;
		}
	}
};
示例#6
0
function isEqualOrParent(pathToCheck, candidate) {
    if (!pathToCheck || !candidate) {
        return false;
    }
    pathToCheck = path.normalize(pathToCheck).toLowerCase();
    candidate = path.normalize(candidate).toLowerCase();
    if (pathToCheck === candidate) {
        return true;
    }
    if (pathToCheck.indexOf(candidate) !== 0) {
        return false;
    }
    var idx = candidate.length;
    if (candidate.charCodeAt(idx - 1) === sepCode) {
        idx -= 1;
    }
    return pathToCheck.charCodeAt(idx) === path.sep.charCodeAt(0);
}
示例#7
0
    install: function (workingDirectory) {
        var gitPath = getClosestGitPath(workingDirectory);

        if (!gitPath) {
            throw new Error('git-hooks must be run inside a git repository');
        }

        var hooksPath = path.resolve(gitPath, HOOKS_DIRNAME);
        var hooksOldPath = path.resolve(gitPath, HOOKS_OLD_DIRNAME);

        if (fsHelpers.exists(hooksOldPath)) {
            throw new Error('git-hooks already installed');
        }

        if (fsHelpers.exists(hooksPath)) {
            fs.renameSync(hooksPath, hooksOldPath);
        }

        var hookTemplate = fs.readFileSync(__dirname + '/' + HOOKS_TEMPLATE_FILE_NAME);
        var pathToGitHooks = path.relative(hooksPath, __dirname);
        // Fix non-POSIX (Windows) separators
        pathToGitHooks = pathToGitHooks.replace(new RegExp(path.sep.replace(/\\/g, '\\$&'), 'g'), '/');
        var hook = util.format(hookTemplate.toString(), pathToGitHooks);

        fsHelpers.makeDir(hooksPath);
        HOOKS.forEach(function (hookName) {
            var hookPath = path.resolve(hooksPath, hookName);
            try {
                fs.writeFileSync(hookPath, hook, {mode: '0777'});
            } catch (e) {
                // node 0.8 fallback
                fs.writeFileSync(hookPath, hook, 'utf8');
                fs.chmodSync(hookPath, '0777');
            }
        });
    },
function replaceTokensInReportJson(reportJson) {
  return reportJson
    .replace(/\{\{workingDirectory\}\}/g, process.cwd().replace(/\\/g, '\\\\'))
    .replace(/\{\{fileSeparator\}\}/g, Path.sep.replace(/\\/g, '\\\\'));
}
示例#9
0
/*!---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/// <reference path="./declare/node.d.ts" />
/// <reference path="./declare/atom-browser.d.ts" />
'use strict';
var path = require('path');
var sepCode = path.sep.charCodeAt(0);
function isEqualOrParent(pathToCheck, candidate) {
    if (!pathToCheck || !candidate) {
        return false;
    }
    pathToCheck = path.normalize(pathToCheck).toLowerCase();
    candidate = path.normalize(candidate).toLowerCase();
    if (pathToCheck === candidate) {
        return true;
    }
    if (pathToCheck.indexOf(candidate) !== 0) {
        return false;
    }
    var idx = candidate.length;
    if (candidate.charCodeAt(idx - 1) === sepCode) {
        idx -= 1;
    }
    return pathToCheck.charCodeAt(idx) === path.sep.charCodeAt(0);
}
exports.isEqualOrParent = isEqualOrParent;
示例#10
0
        }

        var xcode_dir = path.dirname(plist_file);
        var pluginsDir = path.resolve(xcode_dir, 'Plugins');
        var resourcesDir = path.resolve(xcode_dir, 'Resources');
        var cordovaVersion = fs.readFileSync(path.join(project_dir, 'CordovaLib', 'VERSION'), 'utf8').trim();

        cachedProjectFiles[project_dir] = {
            plugins_dir:pluginsDir,
            resources_dir:resourcesDir,
            xcode:xcodeproj,
            xcode_path:xcode_dir,
            pbx: pbxPath,
            write: function () {
                fs.writeFileSync(pbxPath, xcodeproj.writeSync());
            },
            cordovaVersion: cordovaVersion
        };

        return cachedProjectFiles[project_dir];
    },
    purgeProjectFileCache:function(project_dir) {
        delete cachedProjectFiles[project_dir];
    }
};

var pathSepFix = new RegExp(path.sep.replace(/\\/,'\\\\'),'g');
function fixPathSep(file) {
    return file.replace(pathSepFix, '/');
}
示例#11
0
module.exports = function(grunt){
    'use strict';

    var sepReg = new RegExp(path.sep.replace(/\\/g, '\\\\'), 'g');
    
    grunt.registerMultiTask('wow-addrequiremap', 'add the require map to the entrance', function() {
        var options = this.options();
        var moduleName = grunt.config('name');
        var moduleDist = grunt.config('dist');
        var modulePath = grunt.config('path');
        var entrances = grunt.config('entrance');
        var deps = grunt.config('deps');
        var urlMap = grunt.config('wowUrlMap');
        var basePath = grunt.config('wowCdnBase') || '/static';
        var wowRequireMapName = 'wowRequireMap' + new Date().getTime();
        var isSetBase = options.isSetBase;
        var insertScript = ['<script>var ' + wowRequireMapName + '={};</script><script>'];

        if (!entrances || !entrances.length){
            return;
        }

        if (!deps || !deps.length){
            return;
        }

        console.log(isSetBase);
        entrances.forEach(function(ent, index){
            var entPath = path.join(
                moduleDist, 'build/tpl', modulePath, 
                path.relative(path.join(modulePath, 'src'), ent)).replace(sepReg, '/');

            var original = grunt.file.read(entPath);

            if (!isSetBase){
                deps.forEach(function(depPath){
                    var depName = depPath.replace(/\//g, '_');
                    var reMapPath = path.join('./', depPath, 'conf', 'require_map.js').replace(sepReg, '/');
                    insertScript.push([
                        '{{assign var="' + depName + 'RequireMap" ',
                        'value="`$smarty.current_dir`/' + reMapPath + '"}}',
                        '{{if is_file($' + depName + 'RequireMap)}}',
                            wowRequireMapName + '["' + depName + '"]={{include file="./' + reMapPath + '"}};',
                        '{{/if}}'
                    ].join(''));
                });

                insertScript.push([
                    'var require={paths:{}};',
                    'for(var n in ' + wowRequireMapName + '){',
                        'var pt=' + wowRequireMapName + '[n];',
                        'for(pa in pt){',
                            'require.paths[pa]="' + basePath + '/"+pt[pa]',
                        '}',
                    '}'
                ].join(''));
            } else{
                insertScript.push('var require={baseUrl:"' + basePath + '"};');
            }

            insertScript.push('</script>');

            var proFile = original.replace(
                /<script.+src=['"]?[^'"]+['"]?><\/script>/, 
                function(scr){
                    return [
                        insertScript.join(''),
                        scr
                    ].join('\n');
                });
                
            grunt.file.write(entPath, proFile);
        });
    });
};
示例#12
0
var path = require('path');
var sepReg = new RegExp(path.sep.replace(/\\/g, '\\\\'), 'g');

module.exports = function(grunt){
    'use strict';

    var sepReg = new RegExp(path.sep.replace(/\\/g, '\\\\'), 'g');
    
    grunt.registerMultiTask('wow-addrequiremap', 'add the require map to the entrance', function() {
        var options = this.options();
        var moduleName = grunt.config('name');
        var moduleDist = grunt.config('dist');
        var modulePath = grunt.config('path');
        var entrances = grunt.config('entrance');
        var deps = grunt.config('deps');
        var urlMap = grunt.config('wowUrlMap');
        var basePath = grunt.config('wowCdnBase') || '/static';
        var wowRequireMapName = 'wowRequireMap' + new Date().getTime();
        var isSetBase = options.isSetBase;
        var insertScript = ['<script>var ' + wowRequireMapName + '={};</script><script>'];

        if (!entrances || !entrances.length){
            return;
        }

        if (!deps || !deps.length){
            return;
        }

        console.log(isSetBase);
        entrances.forEach(function(ent, index){
示例#13
0
  grunt.registerMultiTask('zip', 'Zip files together', function() {
    // Localize variables
    var file = this.file,
        data = this.data,
        src = file.src,
        dest = file.dest,
        router = data.router;

    // Fallback options (e.g. base64, compression)
    _.defaults(data, {
      base64: false
    });

    // Collect our file paths
    var globOptions = {dot: data.dot},
        srcFolders = grunt.file.expandDirs(globOptions, src),
        srcFiles = grunt.file.expandFiles(globOptions, src);

    // If there is no router
    if (!router) {
      // Grab the cwd and return the relative path as our router
      var cwd = data.cwd || process.cwd(),
          separator = new RegExp(path.sep.replace('\\', '\\\\'), 'g');
      router = function routerFn (filepath) {
        // Join path via /
        // DEV: Files zipped on Windows need to use /  to have the same layout on Linux
        return path.relative(cwd, filepath).replace(separator, '/');
      };
    } else if (data.cwd) {
    // Otherwise, if a `cwd` was specified, throw a fit and leave
      grunt.fail.warn('grunt-zip does not accept `cwd` and `router` in the same config due to potential ordering complications. Please choose one.');
    }

    // Generate our zipper
    var zip = new Zip();

    // For each of the srcFolders
    srcFolders.forEach(function (folderpath) {
      // Route the folder
      var routedPath = router(folderpath);

      // If there is a folder, add it to the zip (allows for skipping)
      if (routedPath) {
        grunt.verbose.writeln('Adding folder: "' + folderpath + '" -> "' + routedPath + '"');
        zip.folder(routedPath);
      }
    });

    // For each of the srcFiles
    srcFiles.forEach(function (filepath) {
      // Read in the content and add it to the zip
      var input = fs.readFileSync(filepath, 'binary'),
          routedPath = router(filepath);

      // If it has a path, add it (allows for skipping)
      if (routedPath) {
        grunt.verbose.writeln('Adding file: "' + filepath + '" -> "' + routedPath + '"');
        zip.file(routedPath, input, {binary: true});
      }
    });

    // Create the destination directory
    var destDir = path.dirname(dest);
    grunt.file.mkdir(destDir);

    // Write out the content
    var output = zip.generate({base64: data.base64, compression: data.compression});
    fs.writeFileSync(dest, output, 'binary');

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    grunt.log.writeln('File "' + dest + '" created.');
  });
示例#14
0
/* global Opal */
const fs = require('fs')
const ospath = require('path')
const asciidoctor = require('@asciidoctor/core')()
const pkg = require('../package.json')
const stdin = require('./stdin')

const DOT_RELATIVE_RX = new RegExp(`^\\.{1,2}[/${ospath.sep.replace('/', '').replace('\\', '\\\\')}]`)

class Invoker {
  constructor (options) {
    this.options = options
  }

  invoke () {
    const processArgs = this.options.argv.slice(2)
    const { args } = this.options
    const { verbose, version, files } = args
    if (version || (verbose && processArgs.length === 1)) {
      Invoker.printVersion()
      process.exit(0)
    }
    Invoker.prepareProcessor(args, asciidoctor)
    const options = this.options.options
    if (this.options.stdin) {
      Invoker.convertFromStdin(options, args)
    } else if (files && files.length > 0) {
      Invoker.processFiles(files, verbose, args['timings'], options)
    } else {
      this.showHelp()
    }
function store(key,value){
    //path.replace(/\\/g,'/');
    //var path1=path.normalize(key);
   // cache[path1.replace(/\\/g, '/')]= value;
    cache[path.normalize(key)]=value;
}
示例#16
0
module.exports = function(params, callback) {
  'use strict';

  var path     = require('path');
  var async    = require('async');
  var _        = require('lodash');

  var assemble = params.assemble;
  var grunt    = params.grunt;
  var options  = assemble.options;
  var pages    = options.pages;
  var defaults = options.permalink;

  var escRegEx = function(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  };

  var PATH_SEP = path.sep.slice(-1);
  var INDEX    = 'index.html';
  var INDEX_RE = new RegExp(escRegEx(PATH_SEP + INDEX) + '$');

  // parse lodash template <%= %>
  var parseTpl = function(input, data, page) {
    try {
      return _.template(input, data);
    } catch (error) {
      grunt.fail.fatal(error.message + ' at ' + page.src);
    }
  };

  // convert {{ variable }} to <%= variable %>
  // {{{{ not_variable }}}} to {{ not_variable }}
  var unescTpl = function(input) {
    return input.replace(/\{{2,}/g, function(match) {
      return match.length > 2 ? match.substr(2) : '<%=';
    }).replace(/\}{2,}/g, function(match) {
      return match.length > 2 ? match.substr(2) : '%>';
    });
  };

  // standardize permalink output
  var standard = function(permalink) {
    permalink = permalink || '';
    if (permalink.slice(0, 1) !== PATH_SEP) {
      permalink = PATH_SEP + permalink;
    }
    permalink = permalink.replace(INDEX_RE, PATH_SEP);
    return permalink;
  };

  if (_.isString(defaults) && !_.isEmpty(defaults)) {
    defaults = unescTpl(defaults);
  }

  async.each(pages, function(page, next) {

    page.data = page.data || {};

    var yfm = page.data;
    var permalink = defaults;
    var dirname = page.dirname;
    if (page.filePair && page.filePair.dest) {
      dirname = page.filePair.destForPermalink   ||
                page.filePair.dest_for_permalink ||
                page.filePair.dest;
    }

    if (!_.isUndefined(yfm.permalink)) {
      permalink = yfm.permalink;
    }

    if (!_.isEmpty(permalink)) {

      var data = _.assign({}, options, page, yfm);
      var permalinks;

      if (_.isString(permalink)) {

        permalink = unescTpl(permalink);
        permalink = parseTpl(permalink, data, page);
        permalink = permalink.trim();
        permalinks = permalink.split('\n');

      } else if (_.isArray(permalink)) {

        permalinks = permalink;

      } else {
        grunt.fail.fatal('the permalink of ' + page.src +
          ' is neither a string nor an array');
      }

      for (var i = permalinks.length - 1; i >= 0; i--) {
        var permalink = permalinks[i];
        if (_.isEmpty(permalink)) continue;

        permalink = unescTpl(permalink);
        permalink = parseTpl(permalink, data, page);
        permalink = permalink.trim();
        if (_.isEmpty(permalink)) continue;

        page.dest = path.join(dirname, permalink);

        if (page.dest.slice(-1) === PATH_SEP) {
          page.dest = path.join(page.dest, 'index.html');
        }

        page.data.permalink = standard(permalink);

        if (i > 0) {
          page = _.cloneDeep(page);
          pages.push(page);
        }
      }
    }

    if (!page.data.permalink) {
      page.data.permalink = page.dest.substr(dirname.length);
    }

    page.data.permalink = standard(page.data.permalink);

    if (typeof options.permalinkCallback === 'function') {
      options.permalinkCallback.call(page);
    }

    next();

  });

  callback();
};
import {sep, basename} from 'path'

const escapedSep = sep.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')

const IS_RELATIVE = new RegExp('\\.' + escapedSep)

export default function createGetUniqueTypeName(strategy: 'fullPath' | 'typeName') {
    function getUniqueTypeName(pathValue, name) {
        const suffix = IS_RELATIVE.test(pathValue)
            ? basename(pathValue)
            : pathValue

        return name + (suffix ? ('.' + suffix) : '')
    }

    function getDefaultUniqueTypeName(pathValue, name) {
        return name
    }

    switch (strategy) {
        case 'fullPath':
            return getUniqueTypeName
        case 'typeName':
            return getDefaultUniqueTypeName
        default:
            return getDefaultUniqueTypeName
    }
}
示例#18
0
文件: bom.js 项目: hero76/modulelint
var walk = require("walkdo");
var fs = require("fs");
var path = require("path");
var checkBOM = function (source) {
  var file = fs.openSync(source, "r");
  var buffer = new Buffer(3);
  fs.readSync(file, buffer, 0, 3);
  //读取buffer的前三位,读不到会跳出try,读到BOM则返回true,其他情况都会返回false
  if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf) {
    return true;
  }
  return false;
};
//黑名单
var sep = path.sep.replace('\\', '\\\\').replace('/', '\/');//跨平台
var blackList = [
  sep + "doc" + sep,
  sep + ".git" + sep,
  sep + ".svn" + sep,
  sep + "node_modules" + sep
];
var blackListReg = new RegExp(blackList.join("|"));

exports.rule = "文件utf-8 without BOM检测。查出非utf8 without BOM,每个文件扣5分";
exports.check = function (source, callback) {
  var score = 0;
  var info = [];
  //遍历源目录,忽略黑名单,挨个检测BOM。
  try {
    walk(source, function (file, next, context) {
      if (!blackListReg.test(file)) {
示例#19
0
// utility for generating a uid for each component file
// used in scoped CSS rewriting
var path = require('path')
var hash = require('hash-sum')
var cache = Object.create(null)
var sepRE = new RegExp(path.sep.replace('\\', '\\\\'), 'g')

module.exports = function genId (file, context) {
  var contextPath = context.split(path.sep)
  var rootId = contextPath[contextPath.length - 1]
  file = rootId + '/' + path.relative(context, file).replace(sepRE, '/')
  return cache[file] || (cache[file] = hash(file))
}