Exemplo n.º 1
0
 walker.on("file", function (root, fileStats, next) {
     if(fileCount >= fileCountLimit) {
         return next();
     }
     var include = true;
     var filePath = path.join(root, fileStats.name);
     if(isBinaryFile(filePath)) {
         include = false;
     }
     if(ignores.indexOf(fileStats.name) > 1) {
         include = false;
     }
     if(include) {
         if(fileCount === fileCountLimit - 1) {
             console.error('Synced files more that the maximum limit: ' + fileCountLimit + '. Ignore some files inside .ccignore');
         }
         fileCount++;
         var content = fs.readFileSync(filePath).toString();
         var absFilePath = filePath.substring(dir.length + 1);
         cache[absFilePath] = {
             path: absFilePath,
             deleted: false,
             hash: md5(content),
             content: content
         };
     }
     next();
 });
Exemplo n.º 2
0
conflicter.collision = function collision(filepath, content, cb) {
  var self = this;

  if (!fs.existsSync(filepath)) {
    log.create(filepath);
    return cb('create');
  }

  var encoding = null;
  if (!isBinaryFile(path.resolve(filepath))) {
    encoding = 'utf8';
  }

  var actual = fs.readFileSync(path.resolve(filepath), encoding);

  // In case of binary content, `actual` and `content` are `Buffer` objects,
  // we just can't compare those 2 objects with standard `===`,
  // so we convert each binary content to an hexadecimal string first, and then compare them with standard `===`
  //
  // For not binary content, we can directly compare the 2 strings this way
  if ((!encoding && (actual.toString('hex') === content.toString('hex'))) ||
      (actual === content)) {
    log.identical(filepath);
    return cb('identical');
  }

  if (self.force) {
    log.force(filepath);
    return cb('force');
  }

  log.conflict(filepath);
  conflicter._ask(filepath, content, cb);
};
Exemplo n.º 3
0
Conflicter.prototype.collision = function collision(filepath, content, cb) {
  var rfilepath = path.relative(process.cwd(), path.resolve(filepath));
  if (!fs.existsSync(filepath)) {
    this.adapter.log.create(rfilepath);
    return cb('create');
  }

  if (!fs.statSync(path.resolve(filepath)).isDirectory()) {
    var encoding = null;
    if (!isBinaryFile(path.resolve(filepath))) {
      encoding = 'utf8';
    }

    var actual = fs.readFileSync(path.resolve(filepath), encoding);

    // In case of binary content, `actual` and `content` are `Buffer` objects,
    // we just can't compare those 2 objects with standard `===`,
    // so we convert each binary content to an hexadecimal string first, and then compare them with standard `===`
    //
    // For not binary content, we can directly compare the 2 strings this way
    if ((!encoding && (actual.toString('hex') === content.toString('hex'))) ||
      (actual === content)) {
      this.adapter.log.identical(rfilepath);
      return cb('identical');
    }
  }

  if (this.force) {
    this.adapter.log.force(rfilepath);
    return cb('force');
  }

  this.adapter.log.conflict(rfilepath);
  this._ask(filepath, content, cb);
};
Exemplo n.º 4
0
File.prototype.copy = function(srcpath, destpath, options) {
  if (!options) { options = {}; }
  // If a process function was specified, and noProcess isn't true or doesn't
  // match the srcpath, process the file's source.
  var process = options.process && options.noProcess !== true &&
    !(options.noProcess && this.isMatch(options.noProcess, srcpath));
  // If the file will be processed, use the encoding as-specified. Otherwise,
  // use an encoding of null to force the file to be read/written as a Buffer.
  if (options.encoding === undefined && !isBinaryFile(srcpath)) {
    options.encoding = this.option('encoding');
  }
  var readWriteOptions = process ? options : _.extend({
    encoding: null,
    mode: fs.statSync(srcpath).mode
  }, options);
  // Actually read the file.
  var contents = this.read(srcpath, readWriteOptions);
  if (process) {
    this.log.write('Processing source...');
    try {
      contents = options.process(contents, srcpath);
    } catch(e) {
      throw new Error('Error while processing "' + srcpath + '" file.', e);
    }
  }

  // Abort copy if the process function returns false.
  if (contents === false) {
    this.log.write('Write aborted.');
  } else {
    this.write(destpath, contents, readWriteOptions);
  }
};
Exemplo n.º 5
0
function readPath(options, path, size) {
  var text = null;
  if (options.onFilepathSearchFn && (text = options.onFilepathSearchFn(path)))
    return text;

  var fd = fs.openSync(path, "r");
  try {
    var binaryBuffer = new Buffer(512);
    var bytesRead = fs.readSync(fd, binaryBuffer, 0, 512);

    if (!isBinaryFile(binaryBuffer, bytesRead)) {
      var remainingBytes = size - bytesRead;
      if (remainingBytes > 0) {
        var textBuffer = new Buffer(size);
        binaryBuffer.copy(textBuffer, 0, 0, bytesRead);
        bytesRead += fs.readSync(fd, textBuffer, bytesRead, remainingBytes);
        text = textBuffer.toString("utf8", 0, bytesRead);
      }
      else {
        text = binaryBuffer.toString("utf8", 0, bytesRead);
      }
    }
    return text;
  } finally {
    fs.closeSync(fd);
  }
}
Exemplo n.º 6
0
actions._prepCopy = function _prepCopy(source, destination, process) {
  var body;
  destination = destination || source;

  if (typeof destination === 'function') {
    process = destination;
    destination = source;
  }

  source = this.isPathAbsolute(source) ? source : path.join(this.sourceRoot(), source);
  destination = this.isPathAbsolute(destination) ? destination : path.join(this.destinationRoot(), destination);

  var encoding = null;
  var binary = isBinaryFile(source);
  if (!binary) {
    encoding = 'utf8';
  }

  body = fs.readFileSync(source, encoding);

  if (typeof process === 'function' && !binary) {
    body = process(body, source, destination, {
      encoding: encoding
    });
  }

  return {
    body: body,
    encoding: encoding,
    destination: destination,
    source: source
  };
};
Exemplo n.º 7
0
	function iteratorFn( file, finishedCB ) {

		// Make sure this file has a file extension we care about
		//
		// NOTE: extension filtering is optional, so if extensions is an
		// empty array, any file extension will be let through
		var hasValidExtension = extensions.length > 0 ? false : true;
		for( var iExtension = 0; iExtension < extensions.length; ++iExtension ) {
			var extensionFilter = extensions[iExtension];

			// Figure out whether we're trying to include or exclude this extension
			var isExclude = false;
			if( extensionFilter.charCodeAt(0) == 45 ) {
				isExclude = true;
				extensionFilter = extensionFilter.substring(1);
			}

			if( isExclude ) {
				if( pathModule.extname(file) != extensionFilter )
					hasValidExtension = true;
			} else {
				if( pathModule.extname(file) == extensionFilter )
					hasValidExtension = true;
			}
		}

		// Give up on this round if this file has an invalid extension
		if( !hasValidExtension )
			return finishedCB();

		var path = source + "/" + file;

		// If this path has a valid extension, but is actually a folder, skip it
		if( fs.lstatSync(path).isDirectory() )
			return finishedCB();

		// If this is a binary file, we're not going to be able to do
		// anything anyway, so just get out
		if( isBinary(path) )
			return finishedCB();

		var templateObj = _this.makeTemplate( path, replacementMap );

		// Copy over the parameters we're trying to fill in
		for( var property in contents ) {
			if( contents.hasOwnProperty(property) ) {
				templateObj[property] = contents[property] || undefined;
			}
		}

		// Use the path replacement map to modify output locations
		var outputPath = dest + file;
		for( var iItem in pathReplacementMap ) {
			outputPath = outputPath.replace( new RegExp(iItem, "g"), pathReplacementMap[iItem] );
		}

		_this.makeFile( outputPath, [templateObj], finishedCB );
	}
Exemplo n.º 8
0
shopify.upload = function(filepath, file, host, base, themeid) {

  var api = shopifyAPI,
    themeId = themeid,
    key = shopify._makeAssetKey(filepath, base),
    isBinary = isBinaryFile(filepath),
    props = {
      asset: {
        key: key
      }
    },
    contents;

  contents = file.contents;

  if (isBinary) {
    props.asset.attachment = contents.toString('base64');
  } else {
    props.asset.value = contents.toString();
  }

  function onUpdate(err, resp) {
    if (err && err.type === 'ShopifyInvalidRequestError') {
      var errMsg = err.detail.asset[0].split('\n')[0];
      gutil.log(gutil.colors.red('ERROR: "' + errMsg + '" in ' + key));
      notifier.notify({
        title:  "Upload Failed",
        message:  err.detail.asset[0],
        icon: __dirname + '/shopify-logo.png',
        sound:  "Sosumi"
      });
    } else if (!err) {
      var filename = filepath.replace(/^.*[\\\/]/, '');
      gutil.log(gutil.colors.green('Upload Complete: ' + filename));
      notifier.notify({
        title:  "Upload Complete",
        message: key,
        icon: __dirname + '/shopify-logo.png',
        sound:  "Pop"
      });
    } else {
      gutil.log(gutil.colors.red('Error undefined! ' + err.type));
      notifier.notify({
        title:  "Gulp Shopify Upload",
        subtitle: "Unknown Error",
        message:  err,
        icon: __dirname + '/shopify-logo.png',
        sound:  "Blow"
      });
    }
  }

  if (themeId) {
    api.asset.update(themeId, props, onUpdate);
  } else {
    api.assetLegacy.update(props, onUpdate);
  }
};
Exemplo n.º 9
0
 watch.watchTree(dir, function (f, curr, prev) {
     if (typeof f == "object" && prev === null && curr === null) {
     } else if (prev === null) {
         if(!isBinaryFile(f)) {
             var include = true;
             if(fs.lstatSync(f).isDirectory()) {
                 include = false;
             }
             ignores.forEach(function(ignored){
                 if(f.indexOf(ignored) > -1) {
                     include = false;
                 }
             });
             if(cache[absFilePath]) {
                 include = false;
             }
             if(include) {
                 var content = fs.readFileSync(f).toString();
                 var absFilePath = f.substring(dir.length + 1);
                 cache[absFilePath] = {
                     path: absFilePath,
                     deleted: false,
                     hash: md5(content),
                     content: content
                 };
                 api.queue('POST', 'add-file/' + endpoint, {
                     file: cache[absFilePath]
                 });
                 console.log('File ' + absFilePath + ' added');
             }
         }
     } else if (curr.nlink === 0) {
         var absFilePath = f.substring(dir.length + 1);
         if(cache[absFilePath]) {
             cache[absFilePath].deleted = true;
             api.queue('POST', 'remove-file/' + endpoint, {
                 file: cache[absFilePath]
             });
             console.log('File ' + absFilePath + ' deleted');
         }
     } else {
         var absFilePath = f.substring(dir.length + 1);
         if(cache[absFilePath]) {
             var newContent = fs.readFileSync(f).toString();
             var hash = md5(newContent);
             if(hash != cache[absFilePath].hash) {
                 cache[absFilePath].content = newContent;
                 cache[absFilePath].hash = hash;
                 api.queue('POST', 'update-file/' + endpoint, {
                     path: absFilePath,
                     hash: hash,
                     content: newContent
                 });
                 console.log('File ' + absFilePath + ' updated');
             }
         }
     }
 });
Exemplo n.º 10
0
    function readFileCallback (err, buffer) {
      if (err) {
        log.warn(err)
        if (retryCount < maxRetries) {
          retryCount++
          log.warn('retrying ' + retryCount)
          fs.readFile(file.originalPath, readFileCallback)
          return
        } else {
          throw err
        }
      }

      isBinaryFile(buffer, buffer.length, function (err, thisFileIsBinary) {
        if (err) {
          throw err
        }

        var preprocessorNames = []
        for (var i = 0; i < patterns.length; i++) {
          if (mm(file.originalPath, patterns[i], {dot: true})) {
            if (thisFileIsBinary) {
              log.warn('Ignoring preprocessing (%s) %s because it is a binary file.',
                config[patterns[i]].join(', '), file.originalPath)
            } else {
              preprocessorNames = combineLists(preprocessorNames, config[patterns[i]])
            }
          }
        }

        var preprocessors = []
        var nextPreprocessor = createNextProcessor(preprocessors, file, done)
        preprocessorNames.forEach(function (name) {
          var p = instances[name]
          if (p == null) {
            p = instantiatePreprocessor(name)
          }

          if (p == null) {
            if (!alreadyDisplayedErrors[name]) {
              alreadyDisplayedErrors[name] = true
              log.error('Failed to instantiate preprocessor %s', name)
              emitter.emit('load_error', 'preprocessor', name)
            }
            return
          }

          instances[name] = p
          preprocessors.push(p)
        })

        nextPreprocessor(null, thisFileIsBinary ? buffer : buffer.toString())
      })
    }
Exemplo n.º 11
0
 return lstat(path).then(function(fileStat) {
   if (isBinaryFile(content, fileStat.size)) {
     return content;
   } else {
     try {
       return processTemplate(content.toString(), context);
     } catch (err) {
       err.message += ' (Error in blueprint template: ' + path + ')';
       throw err;
     }
   }
 });
Exemplo n.º 12
0
actions.copy = function copy(source, destination) {
  var body;
  destination = destination || source;
  source = this.isPathAbsolute(source) ? source : path.join(this.sourceRoot(), source);

  var encoding = null;
  if (!isBinaryFile(source)) {
    encoding = 'utf-8';
  }

  try {
    body = this.engine(fs.readFileSync(source, encoding), this);
  } catch (err) {
    // This happens on some cases trying to copy a JS file like lodash/underscore
    // (conflicting the templating engine)
    body = fs.readFileSync(source, encoding);
  }

  this.checkForCollision(destination, body, function (err, status) {
    var stats;

    if (err) {
      return this.emit('error', err);
    }

    // Create or force means file write, identical or skip prevent the
    // actual write
    if (!(/force|create/.test(status))) {
      return;
    }

    mkdirp.sync(path.dirname(destination));
    fs.writeFileSync(destination, body);

    // Synchronize stats and modification times from the original file.
    stats = fs.statSync(source);
    try {
      fs.chmodSync(destination, stats.mode);
      fs.utimesSync(destination, stats.atime, stats.mtime);
    } catch (err) {
      this.log.error('Error setting permissions of "' + destination.bold + '" file: ' + err);
    }
  }.bind(this));

  return this;
};
Exemplo n.º 13
0
  finalizer = function() {
    if (options.list) {
      cb(mergesort(allPaths).join("\n"));
    }
    else {
      var matchedFiles = mergesort(Object.keys(allFiles));
      for (var m = 0, allFilesLength = matchedFiles.length; m < allFilesLength; m++) {
        var path = matchedFiles[m];
        var fileBuffer = fs.readFileSync(path);

        if (!isBinaryFile(fileBuffer, allFiles[path].stat.size)) {
          var contents = decoder.write(fileBuffer);

          options.query.lastIndex = 0;
          // don't bother working if there's not even a match
          if ( options.query.test(contents) ) {
            var oMatchCount = contents.match(options.query).length, 
                matchCount = oMatchCount, 
                lines = "";

            if (options.replacement) {
              var replacedContents = contents.replace(options.query, options.replacement);
              fs.writeFile(path, replacedContents, "utf8");
            }

            var contents = contents.split("\n");

            for (var i = 0, strLength = contents.length; matchCount && i < strLength; i++) {
              options.query.lastIndex = 0; // query is set with "g" so this resets the position
              if (options.query.test(contents[i])) {
                lines += (i+1) + ":" + (options.replacement ? contents[i].replace(options.query, options.replacement) : contents[i]) + "\n"; 
                matchCount--;            
              }
            }

            cb(path, lines, oMatchCount);
          }
        }
      }
    }
  }
Exemplo n.º 14
0
    shopify.upload = function(filepath, done) {
        if (!shopify._isValidPath(filepath)) {
            return done();
        }

        var api = shopify._getApi(),
            themeId = shopify._getThemeId(),
            key = shopify._makeAssetKey(filepath),
            isBinary = isBinaryFile(filepath),
            props = {
                asset: {
                    key: key
                }
            },
            contents;

        contents = grunt.file.read(filepath, { encoding: isBinary ? null : 'utf8' });
        shopify.notify('Uploading "'+ key +'"');

        if (isBinary) {
            props.asset.attachment = contents.toString('base64');
        } else {
            props.asset.value = contents.toString();
        }

        function onUpdate(err, resp) {
            if (err && err.type === 'ShopifyInvalidRequestError') {
                shopify.notify('Error uploading file ' + JSON.stringify(err.detail), true);
            } else if (!err) {
                shopify.notify('File "' + key + '" uploaded.');
            }

            done(err);
        }

        if (themeId) {
            api.asset.update(themeId, props, onUpdate);
        } else {
            api.assetLegacy.update(props, onUpdate);
        }
    };
Exemplo n.º 15
0
    blok.upload = function(filepath, done) {
        /*if (!blok._isValidPath(filepath)) {
            return done();
        }*/

        var key = blok._makeAssetKey(filepath),
            isBinary = isBinaryFile(filepath),
            props = {
                filepath: key
            },
            contents;

        contents = grunt.file.read(filepath, { encoding: isBinary ? null : 'utf8' });

        if (isBinary) {
            props.attachment = contents.toString('base64');
        } else {
            props.body = contents.toString();

            var keyParts = key.split('.');
            var lastPart = keyParts[keyParts.length - 1];

            if (['js', 'css', 'svg'].indexOf(lastPart) > -1) {
                blok.notify('Found js/css/svg');
                props.type = 'asset';
            }
        }

        function onUpdate(res) {
            if (res.error) {
                blok.notify('Error uploading file ' + JSON.stringify(res.body), true);
            } else if (!res.error) {
                blok.notify('File "' + key + '" uploaded.');
            }
            done(res.error);
        }
        
        grunt.log.ok('[grunt-blok] - Starts upload of ' + key);
        blok._apiCall('PUT', props, onUpdate);
    };
Exemplo n.º 16
0
        files.forEach(function(file) {
            var key = getUploadKey(file, localPath);
            var parent = getParentUploadKey(key);
            var remoteURL = url.resolve(remote_path, path.relative(localPath, file).replace(/\\/g, '/'));
            var isDir = grunt.file.isDir(file);

            if(isDir) {
                // Remove existing dir and create a new one
                uploadTasks[key] = createTask(parent, function(callback) {
                    async.series([
                        function(taskCallback) {
                            deleteFolderOnRemote(grunt, remoteURL, taskCallback, configurationOptions);
                        },
                        function(taskCallback) {
                            createFolderOnRemote(grunt, remoteURL, taskCallback, configurationOptions);
                        }
                    ], function (err, results) {
                        if(err !== null) {
                            grunt.log.error(err.message);
                            callback(err);
                        } else {
                            callback(null, remoteURL);
                        }
                    });

                });
            } else {
                var options = {};
                //if it is a binary image file, skip encoding
                if(isBinaryFileSync(file)){
                    options.encoding = null;
                }
                var buffer = grunt.file.read(file, options);
                uploadTasks[key] = createTask(parent, function(callback) {
                    createFileOnRemote(grunt, remoteURL, buffer, callback, configurationOptions);
                });

            }
        });
Exemplo n.º 17
0
shopify.upload = function(filepath, file, host, base, themeid) {

    var api = shopifyAPI,
        themeId = themeid,
        key = shopify._makeAssetKey(filepath, base),
        isBinary = isBinaryFile(filepath),
        props = {
            asset: {
                key: key
            }
        },
        contents;

    contents = file.contents;

    if (isBinary) {
        props.asset.attachment = contents.toString('base64');
    } else {
        props.asset.value = contents.toString();
    }

    function onUpdate(err, resp) {
        if (err && err.type === 'ShopifyInvalidRequestError') {
            console.log('Error invalid upload request! ' + filepath + ' not uploaded to ' + host);
        } else if (!err) {
            var filename = filepath.replace(/^.*[\\\/]/, '');
            console.log('Upload Complete: ' + filename);
        } else {
          console.log('Error undefined! ' + err.type);
        }
    }

    if (themeId) {
      api.asset.update(themeId, props, onUpdate);
    } else {
      api.assetLegacy.update(props, onUpdate);
    }
};
shopify.upload = function (filepath, file, host, base, themeid, callback) {

  var api = shopifyAPI;
  var themeid = themeid;
  var key = shopify._makeAssetKey(filepath, base);
  var isBinary = isBinaryFile(filepath);
  var contents = file.contents;
  var props = {
    asset: {
      key: key
    }
  };

  if (isBinary) {
    props.asset.attachment = contents.toString('base64');
  } else {
    props.asset.value = contents.toString();
  }

  var prettyPath = shopify._getPrettyPath(file, base);
  log(chalk.gray.dim('Uploading: ' + prettyPath));

  function onUpdate(err, resp) {
    if (!err) {
      log(chalk.green('Upload Complete: ' + file.relative));
    } else {
      var errorMessage = (err.type === 'ShopifyInvalidRequestError') ? err.detail.asset.join(', ') + ' in ' + file.relative : 'Shopify API response error: ' + err.type;
      log(chalk.red('Error: ' + errorMessage));
    }
    callback();
  }

  if (themeid) {
    api.asset.update(themeid, props, onUpdate);
  } else {
    api.assetLegacy.update(props, onUpdate);
  }
};
Exemplo n.º 19
0
Common.prepareAppConf = function(app, cwd, outputter) {

  if (app.cron_restart) {
    try {
      outputter && outputter(cst.PREFIX_MSG + 'cron restart at ' + app.cron_restart);
      new cronJob(app.cron_restart, function() {
        outputter && outputter(cst.PREFIX_MSG + 'cron pattern for auto restart detected and valid');
      });
    } catch(ex) {
      return new Error('Cron pattern is not valid, trace: ' + ex.stack);
    }
  }

  if(!app.script) {
    return new Error('No script path - aborting');
  }

  cwd && (cwd[0] != '/') && (cwd = p.resolve(process.cwd(), cwd));
  cwd = cwd || process.cwd();

  app.pm_exec_path = p.resolve(cwd, app.script);
  delete app.script;

  if (!fs.existsSync(app.pm_exec_path)) {
    return new Error('script not found : ' + app.pm_exec_path);
  }

  // Set current env by first adding the process environment and then extending/replacing it
  // with env specified on command-line or JSON file.
  app.env = [{}, process.env, app.env || {}, {pm_cwd: cwd}].reduce(function(e1, e2){
    return util._extend(e1, e2);
  });

  app.pm_cwd = cwd;

  var noInterpreter = (!app.exec_interpreter || 'none' == app.exec_interpreter),
      extName = p.extname(app.pm_exec_path),
      betterInterpreter = extItps[extName];

  if (noInterpreter && betterInterpreter) {
    app.exec_interpreter = betterInterpreter;
    if (betterInterpreter != 'node' && extName != '.coffee') {
    }
  } else if(noInterpreter){
    app.exec_interpreter = isBinary(app.pm_exec_path) ? 'none':'node';
  }

  if(typeof app.instances == 'undefined'){
    app.instances = 1;
  }
  if(app.exec_mode){
    app.exec_mode = app.exec_mode.replace(/^(fork|cluster)$/, '$1_mode');
  }

  if (!app.exec_mode && app.instances > 0) {
    app.exec_mode = 'cluster_mode';
  } else if (!app.exec_mode) {
    app.exec_mode = 'fork_mode';
  }

  if (!app.node_args) {
    app.node_args = [];
  }

  var formated_app_name = app.name.replace(/[^a-zA-Z0-9\\.\\-]/g, '-');

  ['log', 'out', 'error', 'pid'].forEach(function(f){
    var af = app[f + '_file'], ps, ext = (f == 'pid' ? 'pid':'log'), isStd = !~['log', 'pid'].indexOf(f);
    if((f == 'log' && typeof af == 'boolean' && af) || (f != 'log' && !af)){
      ps = [cst['DEFAULT_' + ext.toUpperCase() + '_PATH'], formated_app_name + (isStd ? '-' + f : '') + '.' + ext];
    }else if(f != 'log' || (f == 'log' && af)){
      ps = [cwd, af];
    }
    // PM2 paths
    ps && (app['pm_' + (isStd ? f.substr(0, 3) + '_' : '') + ext + '_path'] = p.resolve.apply(null, ps));
    delete app[f + '_file']
  });

  //set port env variable
  if (app.port) {
    app.env.PORT = app.port;
  }

  return app;
};
Exemplo n.º 20
0
Common.prepareAppConf = function(app, cwd, outputter) {
  /**
   * Check if PM2 is runned with iojs to handle next-gen-js
   */
  if (app.next_gen_js) {
    if (!iojs) {
      return new Error('To run next generation Javascript you need to run PM2 with io.js');
    }

    // If fork mode set the right interpreter
    if ((app.exec_mode == 'fork_mode' ||
         app.exec_mode == 'fork' ||
         !app.exec_mode) &&
        app.exec_interpreter === 'node') {
      app.exec_interpreter = cst.BABEL_EXEC_PATH;
    }

    // Allow interpreter overridde
    if (app.exec_interpreter) {
      Common.printOut(cst.PREFIX_MSG + 'Overridding next-gen-js interpreter');
    }

    Common.printOut(cst.PREFIX_MSG + 'Next gen JS enabled');
  }

  if (app.cron_restart) {
    try {
      outputter && outputter(cst.PREFIX_MSG + 'cron restart at ' + app.cron_restart);
      new cronJob(app.cron_restart, function() {
        outputter && outputter(cst.PREFIX_MSG + 'cron pattern for auto restart detected and valid');
      });
    } catch(ex) {
      return new Error('Cron pattern is not valid, trace: ' + ex.stack);
    }
  }

  if (!app.script) {
    return new Error('No script path - aborting');
  }

  cwd && (cwd[0] != '/') && (cwd = p.resolve(process.cwd(), cwd));
  cwd = cwd || process.cwd();

  app.pm_exec_path = p.resolve(cwd, app.script);
  delete app.script;

  if (!fs.existsSync(app.pm_exec_path)) {
    return new Error('script not found : ' + app.pm_exec_path);
  }

  // Set current env by first adding the process environment and then extending/replacing it
  // with env specified on command-line or JSON file.
  app.env = [{}, process.env, app.env || {}, {pm_cwd: cwd}].reduce(function(e1, e2){
    return util._extend(e1, e2);
  });

  app.pm_cwd = cwd;

  var noInterpreter = (!app.exec_interpreter || 'none' == app.exec_interpreter),
      extName = p.extname(app.pm_exec_path),
      betterInterpreter = extItps[extName];

  if (noInterpreter && betterInterpreter) {
    app.exec_interpreter = betterInterpreter;
    if (betterInterpreter != 'node' && extName != '.coffee') {
    }
  } else if(noInterpreter){
    app.exec_interpreter = isBinary(app.pm_exec_path) ? 'none':'node';
  }

  if(typeof app.instances == 'undefined'){
    app.instances = 1;
  }
  if(app.exec_mode){
    app.exec_mode = app.exec_mode.replace(/^(fork|cluster)$/, '$1_mode');
  }

  /**
   * Here we put the default exec mode
   */
  if (!app.exec_mode && app.instances > 0) {
    app.exec_mode = 'cluster_mode';
  } else if (!app.exec_mode) {
    app.exec_mode = 'fork_mode';
  }

  // if (!app.exec_mode && (process.version.match(/0.11/) || process.version.match(/0.12/))) {
  //   app.exec_mode = 'fork_mode';
  // }
  // else
  //   app.exec_mode = 'fork_mode';

  if (!app.node_args) {
    app.node_args = [];
  }

  var formated_app_name = app.name.replace(/[^a-zA-Z0-9\\.\\-]/g, '-');

  ['log', 'out', 'error', 'pid'].forEach(function(f){

    var af = app[f + '_file'], ps, ext = (f == 'pid' ? 'pid':'log'), isStd = !~['log', 'pid'].indexOf(f);
    if ((f == 'log' && typeof af == 'boolean' && af) || (f != 'log' && !af)) {
      ps = [cst['DEFAULT_' + ext.toUpperCase() + '_PATH'], formated_app_name + (isStd ? '-' + f : '') + '.' + ext];
    } else if (f != 'log' || (f == 'log' && af)) {
      ps = [cwd, af];

      if (!fs.existsSync(path.dirname(af))) {
        Common.printError(cst.PREFIX_MSG_ERR + 'Folder does not exists: ' + path.dirname(af));
        throw new Error('Folder does not exists');
      }

    }
    // PM2 paths
    ps && (app['pm_' + (isStd ? f.substr(0, 3) + '_' : '') + ext + '_path'] = p.resolve.apply(null, ps));
    delete app[f + '_file']

  });

  //set port env variable
  if (app.port) {
    app.env.PORT = app.port;
  }

  return app;
};
Exemplo n.º 21
0
 else if (!await new Promise(resolve => isbinaryfile(file, (err, isBinary) => resolve(err || isBinary))))