Example #1
0
 return new Promise((resolve, reject) => {
   if (this.basePathExists) {
     resolve();
   } else {
     fs.ensureDir(this.basePath, (err) => {
       if (err) {
         reject(err);
       } else {
         this.basePathExists = true;
         resolve();
       }
     });
   }
 });
	.action(function(type, name){
		var dir = path.join(process.env.HOME, '.smelter', 'template');
		fs.ensureDir(dir, function(err){
			if (err) {
				console.error(chalk.red('[ERROR]') + ' Does not created a .smelter/template directory ' + chalk.cyan(dir));
			} else {
				require('../lib/generate')({
						type: type,
						name: name,
						program: program
					});
			}
		});
	});
  group.before(async () => {
    ioc.singleton('Adonis/Src/Database', function () {
      const config = new Config()
      config.set('database', {
        connection: 'testing',
        testing: helpers.getConfig()
      })
      return new DatabaseManager(config)
    })
    ioc.alias('Adonis/Src/Database', 'Database')

    await fs.ensureDir(path.join(__dirname, './tmp'))
    await helpers.createTables(ioc.use('Adonis/Src/Database'))
  })
Example #4
0
 .then((result) =>
   fse.ensureDir(path.dirname('./public/styles/delft.css'), (err) => {
     if (err) {
       reject(err);
     } else {
       fs.writeFile('./public/styles/delft.css', result, (err) => {
         if (err) {
           reject(err);
         } else {
           resolve();
         }
       });
     }
   })
Example #5
0
  fs.exists(to, function (exists) {
    if (exists) {
      return ln.link(from, to, cb);
    }

    self.logger.warn('The destination folder ' + to + ' does not exists, just mkdir -p');
    fse.ensureDir(to, function (err) {
      if (err) {
        return cb(err);
      }

      ln.link(from, to, cb);
    });
  });
  var _ref = (0, _asyncToGenerator2.default)(function* (destDirectory) {
    const thisPkg = require('../../package.json'); // Use the version string from workbox-build in the name of the parent
    // directory. This should be safe, because lerna will bump workbox-build's
    // pkg.version whenever one of the dependent libraries gets bumped, and we
    // care about versioning the dependent libraries.


    const workboxDirectoryName = `workbox-v${thisPkg.version}`;
    const workboxDirectoryPath = path.join(destDirectory, workboxDirectoryName);
    yield fse.ensureDir(workboxDirectoryPath);
    const copyPromises = [];
    const librariesToCopy = Object.keys(thisPkg.dependencies).filter(dependency => dependency.startsWith(WORKBOX_PREFIX));
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = librariesToCopy[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        const library = _step.value;

        const mainFilePath = require.resolve(library);

        const srcPath = path.dirname(mainFilePath); // fse.copy() copies all the files in a directory, not the directory itself.
        // See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback

        copyPromises.push(fse.copy(srcPath, workboxDirectoryPath));
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return != null) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }

    try {
      yield Promise.all(copyPromises);
      return workboxDirectoryName;
    } catch (error) {
      throw Error(`${errors['unable-to-copy-workbox-libraries']} ${error}`);
    }
  });
Example #7
0
var make_full_app = function () {
    // make sure the output directory exists
    fse.ensureDir(out_dir_base);

    // actually bundle the files into a browserified bundled
    var ui_file = path.join(app_path, 'ui.js');
    var b = make_browserify(ui_file, {});
    var app_file = path.join(out_dir_base, 'app.js');
    b.bundle().pipe(fs.createWriteStream(app_file));

    // copy over app-related resources (images, styles, etc)
    var src_dir_app = path.join(__dirname, '..', 'app');
    fs.readdir(src_dir_app, function (err, files) {
        if (err) { throw err; }

        files.forEach(function (src_file) {
            var src_file_path = path.resolve(src_dir_app, src_file);
            var out_file_path = path.resolve(out_dir_base, src_file);
            var ext = path.extname(src_file);
            if (ext === '.js' || ext === '.html') return;
            fse.copy(src_file_path, out_file_path, function (err) {
                if (err) { throw err; }
                console.log("Copied file(s) from " + src_file_path + " to " + out_file_path);
            });
        });
    });

    // write out the modified vnc.html file that works with the bundle
    var src_html_path = path.resolve(__dirname, '..', 'vnc.html');
    var out_html_path = path.resolve(out_dir_base, 'vnc.html');
    fs.readFile(src_html_path, function (err, contents_raw) {
        if (err) { throw err; }

        var contents = contents_raw.toString();
        contents = contents.replace(/="app\//g, '="');

        var start_marker = '<!-- begin scripts -->\n';
        var end_marker = '<!-- end scripts -->';
        var start_ind = contents.indexOf(start_marker) + start_marker.length;
        var end_ind = contents.indexOf(end_marker, start_ind);

        contents = contents.slice(0, start_ind) + '<script src="app.js"></script>\n' + contents.slice(end_ind);

        fs.writeFile(out_html_path, contents, function (err) {
            if (err) { throw err; }
            console.log("Wrote " + out_html_path);
        });
    });
};
Example #8
0
 function createPostFile(cb){
   debug('Rendering Post');
   var yaml = req.fm;
   var content = req.body.content;
   fullPost = [null,yaml,content].join(separator + '\n');
   var postDir = path.join(settings.worktree,
                                 '_posts',
                                 req.tokenData.client);
   var postPath = path.join(postDir, req.body.postFileName);
   debug('Writing Post to: '+ postPath);
   fs.ensureDir(postDir, function(err) {
     if (err) next(err);
     fs.writeFile(postPath, fullPost, cb);
   })
 }
Example #9
0
const createUBM = (layer, wbFold) => {
  return fs.ensureDir(wbFold.gmm)
    .then(() => {
      const ubmExec = [
        bin.ubm,
        `--config ${layer.cfg.ubm}`,
        `--inputFeatureFilename ${wbFold.files}/data.lst`,
        `--featureFilesPath ${wbFold.prm}/`,
        `--labelFilesPath ${layer.paths.lbl}/`,
        `--mixtureFilesPath ${wbFold.gmm}/`
      ];

      return execAsync(ubmExec.join(' '));
    });
};
Example #10
0
const ivExtractor = (layer, wbFold, ndxFile) => {
  const ivExtract = [
    bin.ivExtractor,
    `--config ${layer.cfg.ivExtractor}`,
    `--featureFilesPath ${wbFold.prm}/`,
    `--labelFilesPath ${layer.paths.lbl}/`,
    `--mixtureFilesPath ${wbFold.gmm}/`,
    `--matrixFilesPath ${wbFold.mat}/`,
    `--saveVectorFilesPath ${wbFold.ivRaw}/`,
    `--targetIdList ${wbFold.files}/${ndxFile}`
  ];

  return fs.ensureDir(wbFold.ivRaw)
    .then(() => execAsync(ivExtract.join(' ')));
};
const saveImage = (id) => {
  fse.ensureDir(`${IMAGE_DIR}/${year}`, function (err) {
    if (err !== null) console.log(err) // => null
    // dir has now been created, including the directory it is to be placed in
    const options = {
      url: `http://filmfest.by/media/screenshots/${id}.jpg`,
      dest: `${IMAGE_DIR}/${year}/`,
      done: function (err, filename, image) {
        if (err) {
          throw err
        }
      },
    }
    imageDownloader(options)
  })
}
Example #12
0
    b.on('transform', function (tr, file) {
        if (tr._is_make_module) {
            var new_path = path.join(lib_dir_base, path.relative(core_path, file));
            fse.ensureDir(path.dirname(new_path));
            console.log("Writing " + new_path)
            var fileStream = fs.createWriteStream(new_path);

            if (use_require) {
                var babelificate = babelify(file,
                                            { plugins: ["add-module-exports", "transform-es2015-modules-commonjs"] });
                tr.pipe(babelificate);
                tr = babelificate;
            }
            tr.pipe(fileStream);
        }
    });
Example #13
0
module.exports = async function buildCSS(path) {
  const cssPath = join(srcDirs.css, path);
  const outputPath = outputPathFrom(path, 'css');
  await ensureDir(dirname(outputPath));

  const css = await readFile(cssPath);
  const result = await postcss([
    cssReporter({ clearMessages: true }),
    require('postcss-nested'),
    require('postcss-simple-vars'),
    require('autoprefixer'),
    require('cssnano'),
  ]).process(css, {from: cssPath, to: outputPath});

  return writeFile(outputPath, result.css);
}
Example #14
0
const createTV = (layer, wbFold) => {
  const tvExec = [
    bin.tv,
    `--config ${layer.cfg.tv}`,
    `--featureFilesPath ${wbFold.prm}/`,
    `--labelFilesPath ${layer.paths.lbl}/`,
    `--mixtureFilesPath ${wbFold.gmm}/`,
    `--matrixFilesPath ${wbFold.mat}/`,
    `--ndxFilename ${wbFold.files}/tv.ndx`
  ];

  return fs.ensureDir(wbFold.mat)
    .then(() => {
      return execAsync(tvExec.join(' '));
    });
};
Example #15
0
      function(pathTemplates) {
        return fs.ensureDir(pathTemplates).then(function() {
          var templateDirs = fs.readdirSync(pathTemplates);
          var dataPath = path.join(pathTemplates, '_layout', 'data.yml');

          if (fs.existsSync(dataPath)) {
            _.merge(dataMain, yaml.safeLoad(fs.readFileSync(dataPath, 'utf8')));
          }

          return Promise.map(templateDirs, function(templateDir) {
            return compiler({
              pathTemplate: path.join(pathTemplates, templateDir)
            });
          });
        });
      },
Example #16
0
/**
 * Creates modules with inlined versions of the worker sources.  These modules
 * export a `create` function for creating a worker.
 */
async function main() {
  const inputDir = path.join(__dirname, '../src/ol/worker');
  const outputDir = path.join(__dirname, '../build/ol/src/worker');

  await fse.ensureDir(outputDir);

  const entries = await fse.readdir(inputDir);
  for (const entry of entries) {
    if (!entry.endsWith('.js')) {
      continue;
    }

    const chunk = await build(path.join(inputDir, entry));
    await fse.writeFile(path.join(outputDir, entry), chunk.code);
  }
}
Example #17
0
function run(options) {
  _.defaults(options, {
    'paths': ['features'],
    'tags': [],
    'requires': [],
    'cucumberPath': require.resolve("cucumber"),
    'workers': require('os').cpus().length,
    'logDir': ".tmp-logs",
    'workerEnvVars': {},
    'silentSummary': false,
    'verbose': false,
    'inlineStream': false,
    'devMode': false
  });

  if (options.devMode) {
    let cucumber = require(options.cucumberPath).Cli;
    let args = _.concat(['', ''], options.paths);
    options.tags.forEach(function(arg) {
      args.push('-t');
      args.push(arg);
    });
    options.requires.forEach(function(arg) {
      args.push('-r');
      args.push(arg);
    });

    return new Promise(function(resolve) {
      try {
        cucumber(args).run(function (isSuccessful) {
          let exitCode = (isSuccessful) ? 0 : 1;
          resolve({exitCode: exitCode});
        });
      } catch (e) {
        console.error(e.stack);
        resolve({exitCode: 1});
      }
    });
  } else {
    fs.ensureDir(options.logDir);

    let cukeRunner = new TestHandler(options);
    sigintHandler(cukeRunner);

    return cukeRunner.run();
  }
}
Example #18
0
 return __awaiter(this, void 0, void 0, function* () {
     let workspaceInformation = yield serverUtils.requestWorkspaceInformation(server);
     if (protocol.containsDotNetCoreProjects(workspaceInformation)) {
         const generator = new AssetGenerator(workspaceInformation);
         let operations = yield getOperations(generator);
         if (hasAddOperations(operations)) {
             let doGenerateAssets = yield shouldGenerateAssets(generator);
             if (doGenerateAssets) {
                 yield fs.ensureDir(generator.vscodeFolder);
                 yield addAssets(generator, operations);
             }
         }
     }
     else {
         yield vscode.window.showErrorMessage("Could not locate .NET Core project. Assets were not generated.");
     }
 });
Example #19
0
  async _sync() {
    // in case of multiple `sync`s, ensure we properly close previous keeper
    {
      const keeper = this._keeper
      if (keeper !== undefined) {
        this._keeper = undefined
        ignoreErrors.call(fs.close(keeper))
      }
    }

    const realPath = this._getRealPath()

    await fs.ensureDir(realPath)

    try {
      const { type, device, options, env } = this._params
      await this._execa(
        'mount',
        ['-t', type, device, realPath, '-o', options],
        {
          env: {
            LANG: 'C',
            ...env,
          },
        }
      )
    } catch (error) {
      try {
        // the failure may mean it's already mounted, use `findmnt` to check
        // that's the case
        await this._execa('findmnt', [realPath], {
          stdio: 'ignore',
        })
      } catch (_) {
        throw error
      }
    }

    // keep an open file on the mount to prevent it from being unmounted if used
    // by another handler/process
    const keeperPath = `${realPath}/.keeper_${Math.random()
      .toString(36)
      .slice(2)}`
    this._keeper = await fs.open(keeperPath, 'w')
    ignoreErrors.call(fs.unlink(keeperPath))
  }
Example #20
0
	/** Exports Start*/
	static async createModule(type, dir, name) {
		const candidates = ['frontend', 'backend', 'buildtask', 'plan']
		if (candidates.indexOf(type) === -1) {
			throw new Error(`module type must be ${candidates}`)
		}
		const mdName = name || path.basename(dir)
		if (!/[\w-\d]*/.test(mdName)) {
			throw new Error(`${name} is not a valid module name`)
		}
		await fse.ensureDir(dir)
		const conf = getPackageJson(mdName, type)
		const configContent = `${JSON.stringify(conf, null, 2)}\n`
		const configPath = path.join(dir, 'package.json')
		await fs.writeFileAsync(configPath, configContent)
		await fs.writeFileAsync(path.join(dir, 'index.js'), '')
		return new BrickyardModules(configPath)
	}
Example #21
0
const copyDir = async (src, dest, options = {}) => {
  const { overwrite = true } = options;
  const filePaths = await fs.readdir(src);
  await fs.ensureDir(dest);
  for (let fileName of filePaths) {
    // console.log(fileName);
    const fileStat = await fs.lstat(`${src}/${fileName}`);
    // console.log(fileStat);
    if (fileStat.isDirectory()) {
      // console.log("IS DIR");
      await copyDir(`${src}/${fileName}`, `${dest}/${fileName}`, options);
    } else {
      await copyFile(`${src}/${fileName}`, `${dest}/${fileName}`, options);
    }
  }
  // console.log("DONE COPY");
};
Example #22
0
        this.on("input",function(msg) {
            var filename = node.filename || msg.filename || "";
            if (!node.filename) { node.status({fill:"grey",shape:"dot",text:filename}); }
            if (filename === "") { node.warn(RED._("file.errors.nofilename")); }
            else if (node.overwriteFile === "delete") {
                fs.unlink(filename, function (err) {
                    if (err) { node.error(RED._("file.errors.deletefail",{error:err.toString()}),msg); }
                    else if (RED.settings.verbose) { node.log(RED._("file.status.deletedfile",{file:filename})); }
                });
            }
            else if (msg.hasOwnProperty("payload") && (typeof msg.payload !== "undefined")) {
                var dir = path.dirname(filename);
                if (node.createDir) {
                    fs.ensureDir(dir, function(err) {
                        if (err) { node.error(RED._("file.errors.createfail",{error:err.toString()}),msg); }
                    });
                }

                var data = msg.payload;
                if ((typeof data === "object") && (!Buffer.isBuffer(data))) {
                    data = JSON.stringify(data);
                }
                if (typeof data === "boolean") { data = data.toString(); }
                if (typeof data === "number") { data = data.toString(); }
                if ((this.appendNewline) && (!Buffer.isBuffer(data))) { data += os.EOL; }
                node.data.push(Buffer.from(data));

                while (node.data.length > 0) {
                    if (this.overwriteFile === "true") {
                        node.wstream = fs.createWriteStream(filename, { encoding:'binary', flags:'w' });
                        node.wstream.on("error", function(err) {
                            node.error(RED._("file.errors.writefail",{error:err.toString()}),msg);
                        });
                    }
                    else {
                        if (!node.wstream) {
                            node.wstream = fs.createWriteStream(filename, { encoding:'binary', flags:'a' });
                            node.wstream.on("error", function(err) {
                                node.error(RED._("file.errors.appendfail",{error:err.toString()}),msg);
                            });
                        }
                    }
                    node.wstream.write(node.data.shift());
                }
            }
        });
                "processSharp": ["createPath", (result, autoCallback) => {

                    const filePath = result.createPath;
                    if (!filePath) {
                        return autoCallback(new Error("File path does not exist."));
                    }

                    return Fse.ensureDir(Path.dirname(filePath), (error) => {

                        if (error) {
                            return autoCallback(error);
                        }

                        return sharp.toFile(filePath, autoCallback);
                    });

                }],
Example #24
0
function PluginManager(ccommand, server) {
	var self = this;

	self.plugins = new HashMap();

	fs.ensureDir('/data/plugins/', function (err) {
		if (err) {
			self.logger.info('ERROR: Cannot create /data/plugins directory');
		}
	})

	self.pluginPath = [__dirname + '/plugins/', '/data/plugins/'];

	self.config = new (require('v-conf'))();

	var pluginsDataFile = '/data/configuration/plugins.json';
	if (!fs.existsSync(pluginsDataFile)) {
		ccommand.logger.info("File /data/configuration/plugins.json does not exist. Copying from Volumio");
		fs.copySync(__dirname + '/plugins/plugins.json', pluginsDataFile);
	}

	self.config.loadFile(pluginsDataFile);

	self.coreCommand = ccommand;
	self.websocketServer = server;
	self.logger = ccommand.logger;

	self.configManager=new(require(__dirname+'/configManager.js'))(self.logger);

	self.configurationFolder = '/data/configuration/';

	var archraw = execSync('/usr/bin/dpkg --print-architecture', { encoding: 'utf8' });
	arch = archraw.replace(/(\r\n|\n|\r)/gm,"")

	var file = fs.readFileSync('/etc/os-release').toString().split('\n');
	for (var l in file) {
		if (file[l].match(/VOLUMIO_VARIANT/i)) {
			var str = file[l].split('=');
			variant = str[1].replace(/\"/gi, "");
		}
		if (file[l].match(/VOLUMIO_HARDWARE/i)) {
			var str = file[l].split('=');
			var device = str[1].replace(/\"/gi, "");
		}
	}
}
/**
 * [exportYAMLFile description]
 * @param  {string} module_name [description]
 * @return {[type]}             [description]
 */
function exportYAMLFile(module_name) {
	const entry = titaniumKit[module_name];
	const lines = [];
	lines.push(`name: ${module_name}`);
	lines.push('platforms: [windowsphone]');

	// dump properties
	entry.properties.length > 0 && lines.push('properties:');
	entry.properties.forEach(property => {
		lines.push(`  - name: ${property}`);
		lines.push('    platforms: [windowsphone]');
	});

	// dump methods
	entry.methods.length > 0 && lines.push('methods:');
	entry.methods.forEach(name => {
		lines.push(`  - name: ${name}`);
		lines.push('    platforms: [windowsphone]');
	});

	// dump events
	entry.events.length > 0 && lines.push('events:');
	entry.events.forEach(name => {
		lines.push(`  - name: ${name}`);
		lines.push('    platforms: [windowsphone]');
	});

	// newline at end of file
	lines.push('\n');

	// dump to file
	const modulepath = module_name.split('.');
	const classname  = modulepath[modulepath.length - 1];

	modulepath.pop();
	// everything should be go to Titanium directory
	if (modulepath[0] !== 'Titanium') {
		modulepath[0] = 'Titanium';
	}
	const outdir = path.join(__dirname, modulepath.join(path.sep));
	const outfile = path.join(outdir, classname + '.yml');
	console.log(`Generating ${path.relative(__dirname, outfile)}`);
	return fs.ensureDir(outdir)
		.then(() => fs.writeFile(outfile, lines.join('\n')));
}
Example #26
0
var moveInstalledPeriodic = function(){
	fs.copySync(path.join(originallocation,'.npmignore'),path.join(originallocation,'.gitignore'));  
	fs.ensureDir(newlocation,function(err){
		if(err){
			console.error(err);
			process.exit(0);
		}
		else{
			fs.copy(
				originallocation,
				newlocation,
				function(err){
				if(err){
					console.error(err);
					console.log(err.stack);
					process.exit(0);
				}
				else{
					fs.remove(originalnodemoduleslocation, function(err){
						if(err){
							console.error(err);
							console.log(err.stack);
							process.exit(0);
						}
						else{	
							console.log('Installed Periodicjs');
							if(upgradeinstall || upgradeinstallalias){
								console.log('Restart to upgrade Periodicjs');
								console.log('\u0007');

								CoreUtilities.restart_app({
									callback:function(err,text) { 
										console.log ('err',err);
										console.log ('moveinstalledperiodic',text);
										process.exit(0);
									}
								});
							}
						}
					});
				}
			});
		}
	});
};
Example #27
0
async function main(argv) {
  const { _: input, ...flags } = minimist(argv, {
    boolean: ['help'],
    alias: {
      help: 'h',
    },
  })

  await fs.ensureDir(paths.projects)

  const [command, ...args] = input

  if (flags.help) {
    return run('help', input, flags)
  }

  return run(command, args, flags)
}
Example #28
0
        .then(content => {
            process.stdout.write(chalk.yellow(`Generating [ ${chalk.magenta(pages)} ] blank page(s)… :`))

            bodyTemplate = content // Set bodyTemplate for next promise. Ugly :(

            // Blank manuscript structure:
            let blankPages = []

            for (let i = startAt, endAt = startAt + pages; i < endAt; i++) {
                let pageDir = path.join('.', 'manuscript', `page-${i}`)

                let thisDir = fse.ensureDir(pageDir) // promise { pending }

                blankPages.push(thisDir)
            }

            return Promise.all(blankPages)
        }).then(() => {
function FileSystemDB( dirname ){
  //TODO on "connection" callback?
  //TODO dirname => object providing both required and optional params?
  assert( dirname, 'dirname must be provided' );

  var instance = Object.create( FileSystemDB );
  instance.dirname = dirname;

  fs.ensureDir( dirname, function( err ){
    if( err ){
      // TODO this could be emited if instance is an EventEmitter
      throw err;
    }
    instance.ready = true;
  });

  return instance;
}
Example #30
0
 files.forEach(file => {
   const outputFilePath = file.replace(sourceDir, outputDir)
   if (isCopyingFiles[outputFilePath]) {
     return
   }
   isCopyingFiles[outputFilePath] = true
   let modifySrc = file.replace(appPath + path.sep, '')
   modifySrc = modifySrc.split(path.sep).join('/')
   let modifyOutput = outputFilePath.replace(appPath + path.sep, '')
   modifyOutput = modifyOutput.split(path.sep).join('/')
   Util.printLog(Util.pocessTypeEnum.COPY, '文件', modifyOutput)
   if (!fs.existsSync(file)) {
     Util.printLog(Util.pocessTypeEnum.ERROR, '文件', `${modifySrc} 不存在`)
   } else {
     fs.ensureDir(path.dirname(outputFilePath))
     fs.copySync(file, outputFilePath)
   }
 })