コード例 #1
0
ファイル: cli.js プロジェクト: DavidCai1993/node
/**
 * Outputs the results of the linting.
 * @param {CLIEngine} engine The CLIEngine to use.
 * @param {LintResult[]} results The results to print.
 * @param {string} format The name of the formatter to use or the path to the formatter.
 * @param {string} outputFile The path for the output file.
 * @returns {boolean} True if the printing succeeds, false if not.
 * @private
 */
function printResults(engine, results, format, outputFile) {
    let formatter;

    try {
        formatter = engine.getFormatter(format);
    } catch (e) {
        log.error(e.message);
        return false;
    }

    const output = formatter(results);

    if (output) {
        if (outputFile) {
            const filePath = path.resolve(process.cwd(), outputFile);

            if (shell.test("-d", filePath)) {
                log.error("Cannot write to output file path, it is a directory: %s", outputFile);
                return false;
            }

            try {
                mkdirp.sync(path.dirname(filePath));
                fs.writeFileSync(filePath, output);
            } catch (ex) {
                log.error("There was a problem writing the output file:\n%s", ex);
                return false;
            }
        } else {
            log.info(output);
        }
    }

    return true;

}
コード例 #2
0
/**
 *
 * @param key i18n key
 * @param {object} generator reference to the generator
 * @returns parsed json file
 */
function geti18nJson(key, generator) {
    const i18nDirectory = `${LANGUAGES_MAIN_SRC_DIR}i18n/en/`;
    let name = _.kebabCase(key.split('.')[0]);
    if (['entity', 'error', 'footer'].includes(name)) {
        name = 'global';
    }
    let filename = `${i18nDirectory + name}.json`;
    let render;
    if (!shelljs.test('-f', path.join(generator.sourceRoot(), filename))) {
        filename = `${i18nDirectory}${name}.json.ejs`;
        render = true;
    }
    try {
        let file = generator.fs.read(path.join(generator.sourceRoot(), filename));
        file = render ? ejs.render(file, generator, {}) : file;
        file = JSON.parse(file);
        return file;
    } catch (err) {
        generator.log(err);
        generator.log(`Error in file: ${filename}`);
        // 'Error reading translation file!'
        return undefined;
    }
}
コード例 #3
0
/// returns an array of available UAP Versions
function getAvailableUAPVersions() {
    /*jshint -W069 */
    var programFilesFolder = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
    // No Program Files folder found, so we won't be able to find UAP SDK
    if (!programFilesFolder) return [];

    var uapFolderPath = path.join(programFilesFolder, 'Windows Kits', '10', 'Platforms', 'UAP');
    if (!shell.test('-e', uapFolderPath)) {
        return []; // No UAP SDK exists on this machine
    }

    var result = [];
    shell.ls(uapFolderPath).filter(function(uapDir) {
        return shell.test('-d', path.join(uapFolderPath, uapDir));
    }).map(function(folder) {
        return Version.tryParse(folder);
    }).forEach(function(version, index) {
        if (version) {
            result.push(version);
        }
    });

    return result;
}
コード例 #4
0
Generator.prototype.registerModule = function(npmPackageName, hookFor, hookType, callbackSubGenerator, description) {
    try {
        var modules;
        var error, duplicate;
        var moduleName = _s.humanize(npmPackageName.replace('generator-jhipster-',''));
        var generatorName = npmPackageName.replace('generator-','');
        var generatorCallback = generatorName + ':' + (callbackSubGenerator ? callbackSubGenerator : 'app') ;
        var moduleConfig = {
            name : moduleName + ' generator',
            npmPackageName : npmPackageName,
            description : description ? description : 'A JHipster module to generate ' + moduleName,
            hookFor : hookFor,
            hookType : hookType,
            generatorCallback : generatorCallback
        }
        if (shelljs.test('-f', MODULES_HOOK_FILE)) {
            // file is present append to it
            try {
                modules = this.fs.readJSON(MODULES_HOOK_FILE);
                duplicate = _.findIndex(modules, moduleConfig) !== -1;
            } catch (err) {
                error = true;
                this.log(chalk.red('The Jhipster module configuration file could not be read!'));
            }
        } else {
            // file not present create it and add config to it
            modules = [];
        }
        if(!error && !duplicate) {
            modules.push(moduleConfig);
            this.fs.writeJSON(MODULES_HOOK_FILE, modules, null, 4);
        }
    } catch (err) {
        this.log('\n' + chalk.bold.red('Could not add jhipster module configuration'));
    }
};
コード例 #5
0
Generator.prototype.getExistingEntities = function(warn) {
    var entities = [];
    var unique_dates = new Set();

    function isBefore(e1, e2) {
      return e1.definition.changelogDate - e2.definition.changelogDate;
    }

    if (shelljs.test('-d', JHIPSTER_CONFIG_DIR)) {
        shelljs.ls(path.join(JHIPSTER_CONFIG_DIR, '*.json')).forEach( function(file) {
            var definition = this.fs.readJSON(file);
            unique_dates.add(definition.changelogDate);
            entities.push({name: path.basename(file, '.json'), definition: definition});
        }, this);
    }
    if(entities.length != unique_dates.size) {
        this.log(chalk.yellow('WARNING some of your entities have the same changelog dates so JHipster couldn\'t\n' +
        ' determine the order in which they should be generated. It is recommended to\n' +
        ' edit the changelog dates in the '+ JHIPSTER_CONFIG_DIR + 'folder and to relaunch this\n' +
        ' generator.' ));
    }

    return entities.sort(isBefore);
}
コード例 #6
0
ファイル: index.js プロジェクト: rlei/generator-jhipster
        getConfig: function (args) {
            this.useConfigurationFile = false;
            this.env.options.appPath = this.config.get('appPath') || constants.CLIENT_MAIN_SRC_DIR;
            this.baseName = this.config.get('baseName');
            this.packageName = this.config.get('packageName');
            this.applicationType = this.config.get('applicationType');
            this.packageFolder = this.config.get('packageFolder');
            this.authenticationType = this.config.get('authenticationType');
            this.hibernateCache = this.config.get('hibernateCache');
            this.databaseType = this.config.get('databaseType');
            this.prodDatabaseType = this.config.get('prodDatabaseType');
            this.searchEngine = this.config.get('searchEngine') === 'no' ? false : this.config.get('searchEngine');
            this.messageBroker = this.config.get('messageBroker') === 'no' ? false : this.config.get('messageBroker');
            this.enableTranslation = this.config.get('enableTranslation');
            this.nativeLanguage = this.config.get('nativeLanguage');
            this.languages = this.config.get('languages');
            this.buildTool = this.config.get('buildTool');
            this.testFrameworks = this.config.get('testFrameworks');
            // backward compatibility on testing frameworks
            if (this.testFrameworks === undefined) {
                this.testFrameworks = ['gatling'];
            }

            this.skipClient = this.applicationType === 'microservice' || this.config.get('skipClient') || this.options['skip-client'];

            this.angularAppName = this.getAngularAppName();
            this.jhipsterConfigDirectory = '.jhipster';
            this.mainClass = this.getMainClassName();

            this.filename = this.jhipsterConfigDirectory + '/' + this.entityNameCapitalized + '.json';
            if (shelljs.test('-f', this.filename)) {
                this.log(chalk.green(`\nFound the ${ this.filename } configuration file, entity can be automatically generated!\n`));
                this.useConfigurationFile = true;
                this.fromPath = this.filename;
            }
        },
コード例 #7
0
ファイル: sync-icons.js プロジェクト: leungwensen/svg-icon
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const lang = require('zero-lang');
const shelljs = require('shelljs');
const iconsMetaByName = require('../lib/const/icons-meta-by-name');

const workingDir = './temp';
const dist = './dist/svg';

if (!shelljs.test('-d', workingDir)) {
  shelljs.mkdir(workingDir);
}

function syncIcons(meta) {
  const name = meta.name;
  const prefix = meta.prefix.replace(/\-$/, '');
  const cwd = `${workingDir}/${name}`;
  console.log(`[syncing...] ${name}`);
  if (meta.download) {
    // console.log(`[downloading...] ${name}`);
    // const urlParts = meta.download.split('/');
    // const filename = urlParts[urlParts.length - 1];
    // shelljs.exec(`curl -o ${workingDir}/${filename} ${meta.download} `);
  } else if (!shelljs.test('-d', cwd)) {
    console.log(`[cloning...] ${name}`);
    shelljs.exec(`git clone ${meta.repo} ${cwd}`);
  } else {
    console.log(`[pulling...] ${name}`);
    shelljs.exec(`cd ${cwd} && git pull && cd ../../`)
  }
コード例 #8
0
ファイル: cli-engine.js プロジェクト: davimack/simple-grid
 patterns.forEach(function(file) {
     var fullPath = path.resolve(file);
     if (shell.test("-f", fullPath) && !processed[fullPath]) {
         results.push(createIgnoreResult(file));
     }
 });
コード例 #9
0
function IsPathExists(path) {
    return shell.test('-d', path);
}
コード例 #10
0
ファイル: mv.js プロジェクト: KbaHaxor/cash
 it('should move multiple files', function () {
   cash.mv('mv-a mv-b mvtemp');
   $.test('-e', './mvtemp/mv-a').should.equal(true);
   $.test('-e', './mvtemp/mv-b').should.equal(true);
 });
コード例 #11
0
ファイル: mv.js プロジェクト: KbaHaxor/cash
 it('should print verbose messages', function () {
   cash.mv('mv-a mv-b mvtemp', {verbose: true}).should
     .equal('mv-a -> mvtemp/mv-a\nmv-b -> mvtemp/mv-b\n');
   $.test('-e', './mvtemp/mv-a').should.equal(true);
   $.test('-e', './mvtemp/mv-b').should.equal(true);
 });
コード例 #12
0
ファイル: cli.js プロジェクト: CMRahman/jshint
		config.prereq.forEach(function (fp) {
			fp = path.join(config.dirname, fp);
			if (shjs.test("-e", fp))
				buffer.push(shjs.cat(fp));
		});
コード例 #13
0
function removefolder(folder) {
    if (shelljs.test('-d', folder)) {
        shelljs.rm("-rf", folder);
    }
}
コード例 #14
0
function removefile(file) {
    if (shelljs.test('-f', file)) {
        shelljs.rm(file);
    }
}
コード例 #15
0
ファイル: mkdir.js プロジェクト: panxuepeng/expressgo
function mkdir(path) {
	if( !shell.test('-d', path) ){
		shell.mkdir('-p', path)
		console.log('mkdir '+ path)
	}
}
コード例 #16
0
let featureName = _.kebabCase(arr[0]);
let componentName = arr[1];

if (!componentName) {
  componentName = featureName;
  featureName = '';
}

if (!componentName) {
  throw new Error('Please specify the component name');
}

const context = {
  KEBAB_FEATURE_NAME: _.kebabCase(featureName || 'components'),
  CAMEL_FEATURE_NAME: _.camelCase(featureName),
  COMPONENT_NAME: helpers.pascalCase(componentName),
  KEBAB_COMPONENT_NAME: _.kebabCase(componentName),
  FOLDER_PATH: featureName ? `features/${_.kebabCase(featureName)}` : 'components',
  CLASS_PREFIX: featureName ? _.kebabCase(featureName) : 'component',
};

const targetPath = path.join(testPath, featureName ? `features/${featureName}/${context.COMPONENT_NAME}.test.js`
  : `components/${context.COMPONENT_NAME}.test.js`);
helpers.ensurePathDir(targetPath);
if (!shell.test('-e', targetPath)) {
  const res = helpers.handleTemplate('component_test.js', context);
  shell.ShellString(res).to(targetPath);
}

console.log('Add component test success: ', process.argv[2]);
コード例 #17
0
ファイル: cli.js プロジェクト: CMRahman/jshint
		shjs.ls(fp).forEach(function (item) {
			var itempath = path.join(fp, item);
			if (shjs.test("-d", itempath) || item.match(ext)) {
				collect(itempath, files, ignores, ext);
			}
		});
コード例 #18
0
/**
 * Create Application object.
 * If packageId is not passed, the current working directory needs to be right
 * inside the project, so that the directory name is the packageId.
 * @constructor
 * @param {String} cwd Current working directory
 * @param {String} [packageId] Package ID in com.example.foo format, or null
 * @throws {Error} If packageId not passed and current working dir not a project.
 * @protected
 */
function Application(cwd, packageId) {

    var output = TerminalOutput.getInstance();

    // cwd must be absolute and exist.
    if (!cwd ||
        Path.resolve(cwd) != Path.normalize(cwd)) {
        output.error("Path not absolute: " + cwd);
        throw new Error("Path not absolute: " + cwd);
    }
    if (!ShellJS.test("-d", cwd)) {
        output.error("Path does not exist: " + cwd);
        throw new Error("Path does not exist: " + cwd);
    }

    // PackageId is only passed when a new project is created.
    if (packageId) {

        this._packageId = CommandParser.validatePackageId(packageId, this.output);

        // Check that project dir not already exists
        var rootPath = Path.join(cwd, this._packageId);
        if (ShellJS.test("-d", rootPath)) {
            output.error("Failed to create project, path already exists: " + rootPath);
            throw new Error("Failed to create project, path already exists: " + rootPath);
        }

        initMembers.call(this, rootPath);

        // Create Manifest
        Manifest.create(Path.join(this._appPath, "manifest.json"), packageId);

    } else {

        // Get packageId from manifest
        var manifest = new Manifest(TerminalOutput.getInstance(), Path.join(cwd, "app", "manifest.json"));
        this._packageId = manifest.packageId;
        if (!this._packageId) {
            output.error("Path does not seem to be a project toplevel: " + cwd);
            throw new Error("Path does not seem to be a project toplevel: " + cwd);
        }

        initMembers.call(this, cwd);
    }

    // Check all paths exist.
    if (!ShellJS.test("-d", this._rootPath)) {
        output.error("Failed to load, invalid path: " + this._rootPath);
        throw new Error("Failed to load, invalid path: " + this._rootPath);
    }
    if (!ShellJS.test("-d", this._appPath)) {
        output.error("Failed to load, invalid path: " + this._appPath);
        throw new Error("Failed to load, invalid path: " + this._appPath);
    }
    if (!ShellJS.test("-d", this._logPath)) {
        output.error("Failed to load, invalid path: " + this._logPath);
        throw new Error("Failed to load, invalid path: " + this._logPath);
    }
    if (!ShellJS.test("-d", this._pkgPath)) {
        output.error("Failed to load, invalid path: " + this._pkgPath);
        throw new Error("Failed to load, invalid path: " + this._pkgPath);
    }
    if (!ShellJS.test("-d", this._prjPath)) {
        output.error("Failed to load, invalid path: " + this._prjPath);
        throw new Error("Failed to load, invalid path: " + this._prjPath);
    }

    // Set up logging, always start a new file for each time the app is run.
    var logfilePath = Path.join(this._logPath, "common.log");
    ShellJS.rm("-f", logfilePath);
    this._logfileOutput = new LogfileOutput(logfilePath);

    this._platformLogfileOutput = null;

    this._output = new OutputTee(this._logfileOutput, TerminalOutput.getInstance());

    this.loadManifest(Path.join(this._appPath, "manifest.json"));
    this._generatedPackage = null;
}
コード例 #19
0
 shell.ls(uapFolderPath).filter(function(uapDir) {
     return shell.test('-d', path.join(uapFolderPath, uapDir));
 }).map(function(folder) {
コード例 #20
0
ファイル: index.js プロジェクト: aminbh111/generator-gc
 validate: function () {
     if (!shelljs.test('-f', this.jdlFile)) {
         this.env.error(chalk.red('\nCould not find ' + this.jdlFile + ', make sure the path is correct!\n'));
     }
 },
コード例 #21
0
ファイル: mv.js プロジェクト: KbaHaxor/cash
 it('should move a file', function () {
   cash.mv('mv-a mvtemp/mv-a');
   $.test('-e', './mvtemp/mv-a').should.equal(true);
 });
コード例 #22
0
ファイル: _base.js プロジェクト: PEPE-net/mist
exports.mocha = (_module, options) => {
  const tests = {};

  options = _.extend(
    {
      app: 'mist'
    },
    options
  );

  _module.exports[options.name || path.basename(_module.filename)] = {
    *before() {
      this.timeout(1e7);

      this.assert = chai.assert;
      this.expect = chai.expect;

      const mistLogFile = path.join(__dirname, 'mist.log');
      const chromeLogFile = path.join(__dirname, 'chrome.log');
      const webdriverLogDir = path.join(__dirname, 'webdriver');

      _.each([mistLogFile, webdriverLogDir, chromeLogFile], e => {
        console.info('Removing log files', e);
        shell.rm('-rf', e);
      });

      this.geth = yield startGeth();

      const appFileName = options.app === 'wallet' ? 'Ethereum Wallet' : 'Mist';
      const platformArch = `${process.platform}-${process.arch}`;
      console.info(`${appFileName} :: ${platformArch}`);

      let appPath;
      const ipcProviderPath = path.join(this.geth.dataDir, 'geth.ipc');

      switch (platformArch) {
        case 'darwin-x64':
          appPath = path.join(
            process.cwd(),
            `dist_${options.app}`,
            'dist',
            'mac',
            `${appFileName}.app`,
            'Contents',
            'MacOS',
            appFileName
          );
          break;
        case 'linux-x64':
          appPath = path.join(
            process.cwd(),
            `dist_${options.app}`,
            'dist',
            'linux-unpacked',
            appFileName.toLowerCase()
          );
          break;
        default:
          throw new Error(
            `Cannot run tests on ${platformArch}, please run on: darwin-x64, linux-x64`
          );
      }
      console.info(`appPath: ${appPath}`);

      // check that appPath exists
      if (!shell.test('-f', appPath)) {
        throw new Error(`Cannot find binary: ${appPath}`);
      }

      this.web3 = new Web3(
        new Web3.providers.HttpProvider('http://localhost:58545')
      );
      this.app = new Application({
        requireName: 'electronRequire',
        startTimeout: 10000,
        waitTimeout: 10000,
        quitTimeout: 10000,
        path: appPath,
        args: [
          '--loglevel',
          'debug',
          '--logfile',
          mistLogFile,
          '--node-datadir',
          this.geth.dataDir,
          '--rpc',
          ipcProviderPath
        ],
        webdriverOptions: {
          deprecationWarnings: false
        },
        webdriverLogPath: webdriverLogDir,
        chromeDriverLogPath: chromeLogFile
      });

      console.info('Starting app...');
      yield this.app.start();
      console.info('App started');

      this.client = this.app.client;

      /*
                Starting HTTP server for HTML fixtures
            */
      const serverPort = 8080;
      this.httpServer = startFixtureServer(serverPort);
      this.fixtureBaseUrl = `http://localhost:${serverPort}/`;

      /*
                Utility methods
            */
      for (const key in Utils) {
        this[key] = genomatic.bind(Utils[key], this);
      }

      // Loop over windows trying to select Main Window
      const app = this;
      const selectMainWindow = function*(mainWindowSearch, retries = 20) {
        console.log(`selectMainWindow retries remaining: ${retries}`);
        let windowHandles = (yield app.client.windowHandles()).value;

        for (let handle in windowHandles) {
          yield app.client.window(windowHandles[handle]);
          const windowUrl = yield app.client.getUrl();
          const isMainWindow = mainWindowSearch.test(windowUrl);
          if (isMainWindow) return true;
        }

        if (retries === 0) throw new Error('Failed to select main window');

        // not main window. try again after 2 seconds.
        yield Q.delay(2000);
        yield selectMainWindow(mainWindowSearch, --retries);
      };

      const mainWindowSearch =
        options.app === 'wallet' ? /^file:\/\/\/$/ : /interface\/index\.html$/;
      yield selectMainWindow(mainWindowSearch);
      console.log('Main window selected');

      this.mainWindowHandle = (yield this.client.windowHandle()).value;
    },

    *beforeEach() {
      yield this.app.client.window(this.mainWindowHandle);

      yield this.client.execute(() => {
        // Code executed in context of browser
        Tabs.remove({});
        LastVisitedPages.remove({});
        History.remove({});

        Tabs.insert({
          _id: 'browser',
          url: 'http://localhost:8080/',
          redirect: 'http://localhost:8080/',
          position: 0
        });
        Tabs.upsert(
          { _id: 'wallet' },
          {
            $set: {
              url: 'https://wallet.ethereum.org',
              redirect: 'https://wallet.ethereum.org',
              position: 1,
              permissions: { admin: true }
            }
          }
        );

        LocalStore.set('selectedTab', 'browser');
      });
      yield Q.delay(1000);
    },

    // * afterEach() { },

    *after() {
      if (this.app && this.app.isRunning()) {
        console.log('Stopping app...');
        yield this.app.stop();
      }

      if (this.geth && this.geth.isRunning) {
        console.log('Stopping geth...');
        yield this.geth.stop();
      }

      if (this.httpServer && this.httpServer.isListening) {
        console.log('Stopping http server...');
        yield this.httpServer.close();
      }
    },

    tests
  };

  return tests;
};
コード例 #23
0
ファイル: mv.js プロジェクト: KbaHaxor/cash
 it('should rename a file', function () {
   cash.mv('mv-a mv-d');
   $.test('-e', 'mv-d').should.equal(true);
   $.test('-e', 'mv-a').should.equal(false);
 });
コード例 #24
0
ファイル: clean.js プロジェクト: intoday87/status-recovery
var sh = require('shelljs');
var webpackConfig = require('../webpack.config.js');

sh.config.fatal = true;
sh.config.verbose = true;

if (sh.test('-d', webpackConfig.output.path)) {
  sh.rm('-r', webpackConfig.output.path);
}
コード例 #25
0
function ensurePathExist(path) {
    if (!shell.test('-d', path)) {
        shell.mkdir("-p", path);
        console.log("Successfully created directory: " + path);
    }
};
コード例 #26
0
ファイル: index.js プロジェクト: AlexMinsk/generator-jhipster
 this.jdlFiles.forEach((key) => {
     if (!shelljs.test('-f', key)) {
         this.env.error(chalk.red(`\nCould not find ${key}, make sure the path is correct.\n`));
     }
 });
コード例 #27
0
ファイル: clean.js プロジェクト: Johnwjl/test
const shell = require('shelljs');
const addCheckMark = require('./helpers/checkmark.js');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

if (!shell.test('-e', 'internals/templates')) {
  shell.echo('The example is deleted already.');
  shell.exit(1);
}

process.stdout.write('Cleanup started...');

// Reuse existing LanguageProvider and i18n tests
shell.mv('app/containers/LanguageProvider/tests', 'internals/templates/containers/LanguageProvider');
shell.cp('app/tests/i18n.test.js', 'internals/templates/tests/i18n.test.js');

// Cleanup components/
shell.rm('-rf', 'app/components/*');

// Handle containers/
shell.rm('-rf', 'app/containers');
shell.mv('internals/templates/containers', 'app');

// Handle tests/
shell.mv('internals/templates/tests', 'app');

// Handle translations/
shell.rm('-rf', 'app/translations');
コード例 #28
0
ファイル: test.js プロジェクト: g-vidal/upm
 it(imageLink + ' should exists in docs/images', function () {
   var globalImagePath = path.join(imagesPath, imageLink);
   var exists = shell.test('-e', globalImagePath);
   var errorMsg = 'docs/images/' + imageLink + ' should exist, but was not found.';
   expect(exists).to.be.equal(true, errorMsg);
 });
コード例 #29
0
ファイル: index.js プロジェクト: abhub/generator-jhipster
 when: function(response) {
     return (response.relationshipAdd == true && response.ownerSide == true && !shelljs.test('-f', 'src/main/java/' + packageFolder + '/domain/' + _s.capitalize(response.otherEntityName) + '.java'))
 },
コード例 #30
0
ファイル: test.js プロジェクト: g-vidal/upm
 it(example + ' should exists in examples/' + examplesSubfolder, function () {
   var globalExamplePath = path.join(examplesPath, examplesSubfolder, example);
   var exists = shell.test('-e', globalExamplePath);
   var errorMsg = 'examples/' + examplesSubfolder + '/' + example + ' should exist, but was not found.';
   expect(exists).to.be.equal(true, errorMsg);
 });