示例#1
0
	listpaths.forEach(function(temppath){
		fsextra.ensureDirSync(temppath);
	});
示例#2
0
module.exports = async function load(siteDir) {
  const generatedFilesDir = path.resolve(
    siteDir,
    constants.GENERATED_FILES_DIR_NAME,
  );
  fs.ensureDirSync(generatedFilesDir);

  // Site Config - @tested
  const siteConfig = loadConfig.loadConfig(siteDir);
  await generate(
    generatedFilesDir,
    loadConfig.configFileName,
    `export default ${JSON.stringify(siteConfig, null, 2)};`,
  );

  // Env - @tested
  const env = loadEnv({siteDir, siteConfig});
  await generate(
    generatedFilesDir,
    'env.js',
    `export default ${JSON.stringify(env, null, 2)};`,
  );

  // Docs
  const docsDir = path.resolve(siteDir, '..', siteConfig.customDocsPath);
  const {docsMetadatas, docsSidebars} = await loadDocs({
    siteDir,
    docsDir,
    env,
    siteConfig,
  });
  await generate(
    generatedFilesDir,
    'docsMetadatas.js',
    `export default ${JSON.stringify(docsMetadatas, null, 2)};`,
  );
  await generate(
    generatedFilesDir,
    'docsSidebars.js',
    `export default ${JSON.stringify(docsSidebars, null, 2)};`,
  );

  // Create source to metadata mapping.
  const sourceToMetadata = {};
  Object.values(docsMetadatas).forEach(
    ({source, version, permalink, language}) => {
      sourceToMetadata[source] = {
        version,
        permalink,
        language,
      };
    },
  );

  // Pages.
  const pagesDir = path.resolve(siteDir, 'pages');
  const pagesMetadatas = await loadPages({pagesDir, env, siteConfig});
  await generate(
    generatedFilesDir,
    'pagesMetadatas.js',
    `export default ${JSON.stringify(pagesMetadatas, null, 2)};`,
  );

  // Process plugins.
  const pluginConfigs = siteConfig.plugins || [];
  const context = {env, siteDir, siteConfig};

  // Initialize plugins.
  const plugins = pluginConfigs.map(({name, options: opts}) => {
    // TODO: Resolve using node_modules as well.
    // eslint-disable-next-line
    const Plugin = require(path.resolve(__dirname, '../../plugins', name));
    return new Plugin(opts, context);
  });

  // Plugin lifecycle - loadContents().
  // TODO: consider whether we still need contentsStore since it is not being used elsewhere now
  const contentsStore = {};
  // Currently plugins run lifecycle in parallel and are not order-dependent. We could change
  // this in future if there are plugins which need to run in certain order or depend on
  // others for data.
  const pluginsLoadedContents = await Promise.all(
    plugins.map(async plugin => {
      if (!plugin.loadContents) {
        return null;
      }

      const name = plugin.getName();
      const {options} = plugin;
      const contents = await plugin.loadContents();
      const pluginContents = {
        options,
        contents,
      };
      contentsStore[options.contentKey] = pluginContents;
      const pluginCacheDir = path.join(generatedFilesDir, name);
      fs.ensureDirSync(pluginCacheDir);
      await generate(
        pluginCacheDir,
        options.cacheFileName,
        JSON.stringify(contents, null, 2),
      );

      return contents;
    }),
  );

  // Plugin lifecycle - generateRoutes().
  const pluginRouteConfigs = [];
  const actions = {
    addRoute: config => pluginRouteConfigs.push(config),
  };
  await Promise.all(
    plugins.map(async (plugin, index) => {
      if (!plugin.generateRoutes) {
        return;
      }
      const contents = pluginsLoadedContents[index];
      await plugin.generateRoutes({
        contents,
        actions,
      });
    }),
  );

  // Resolve outDir.
  const outDir = path.resolve(siteDir, 'build');

  // Resolve theme.
  const themePath = loadTheme(siteDir);

  const {baseUrl} = siteConfig;
  const versionedDir = path.join(siteDir, 'versioned_docs');
  const translatedDir = path.join(siteDir, 'translated_docs');

  // Generate React Router Config.
  const {routesConfig, routesPaths} = await loadRoutes({
    siteConfig,
    docsMetadatas,
    pagesMetadatas,
    pluginRouteConfigs,
  });
  await generate(generatedFilesDir, 'routes.js', routesConfig);

  const props = {
    siteConfig,
    siteDir,
    docsDir,
    docsMetadatas,
    docsSidebars,
    env,
    pagesDir,
    pagesMetadatas,
    outDir,
    themePath,
    baseUrl,
    sourceToMetadata,
    versionedDir,
    translatedDir,
    generatedFilesDir,
    contentsStore,
    routesPaths,
    plugins,
  };

  return props;
};
	return new Promise((resolve, reject) => {
		console.log(`Downloading ${url.cyan}`);

		const tempName = temp.path({ suffix: '.zip' });
		const tempDir = path.dirname(tempName);
		fs.ensureDirSync(tempDir);

		const tempStream = fs.createWriteStream(tempName);
		const req = request({ url: url });
		req.pipe(tempStream);

		req.on('error', function (err) {
			fs.existsSync(tempName) && fs.unlinkSync(tempName);
			reject('Failed to download URL: %s', err.toString() + '\n');
		});

		req.on('response', function (req) {
			if (req.statusCode >= 400) {  // something went wrong, abort
				return reject('Request failed with HTTP status code %s %s\n', req.statusCode, http.STATUS_CODES[req.statusCode] || '');
			}

			if (req.headers['content-length']) {
				// we know how big the file is, display the progress bar
				const total = parseInt(req.headers['content-length']);

				let bar;
				if (!process.argv.indexOf('--quiet') && !process.argv.indexOf('--no-progress-bars')) {
					bar = new appc.progress('  :paddedPercent [:bar] :etas', {
						complete: '='.cyan,
						incomplete: '.'.grey,
						width: 40,
						total: total
					});
				}

				req.on('data', function (buffer) {
					bar && bar.tick(buffer.length);
				});

				tempStream.on('close', function () {
					if (bar) {
						bar.tick(total);
						console.log('\n');
					}
					resolve(tempName);
				});
			} else {
				// we don't know how big the file is, display a spinner
				let busy;
				if (!process.argv.indexOf('--quiet') && !process.argv.indexOf('--no-progress-bars')) {
					busy = new appc.busyindicator();
					busy.start();
				}

				tempStream.on('close', function () {
					busy && busy.stop();
					busy && console.log();
					resolve(tempName);
				});
			}
		});
	});
function ensureFolder(fileName){
	dir = path.dirname(fileName);
	fse.ensureDirSync(dir,cb);
	
}
示例#5
0
module.exports=function(projectFolder,componentName,componentType,componentRelativeDir) {
	//user vars
	var user_vars=require(path.join(projectFolder,fex_vars.configFile));
	var componentTemplatePath= path.join(fex_dir.templates, user_vars.projectType?user_vars.projectType:'web');
	//fex web app conf.json
	var conf=require(path.join(componentTemplatePath,'conf.js'));

	var componentConfig=conf.components[componentType];

	if(!componentConfig){
		console.log(colors.red(" ERROR: Unsupport component."));
	}

	var componentFolderName=SupportComponentFolderNames[componentType];

	user_vars['FEXComponentName']=componentName;
	user_vars['FEXComponentType']=componentType;
	user_vars['FEXComponentFolderName']=componentFolderName;

	//has Prefix
	var rPrefix=/^\[PREFIX\]/;
	if(rPrefix.test(componentConfig.nameFormat)){
		var prefix=user_vars['componentPrefix'] ? user_vars['componentPrefix'] : '';
		var prefixFormat=componentConfig.nameFormat.replace(rPrefix,prefix);
		newComponentName=prefix ? ( componentName[0].toUpperCase()+componentName.slice(1) ) : componentName;
		user_vars['FEXComponentFormatName']=util.format(prefixFormat, newComponentName);
	}
	else{
		user_vars['FEXComponentFormatName']=util.format(componentConfig.nameFormat,componentName);
	}

	//component directory
	var componentDir=componentRelativeDir
		? path.join(fex_dir.cwd,componentRelativeDir)
		: path.join(projectFolder,'coffee',componentFolderName);

	fs.ensureDirSync(componentDir);

	//copy component coffee script
	var componentFileTemplate=path.join(componentTemplatePath,componentConfig.template);
	var componentFile=path.join(componentDir,componentName+'.coffee');
	if(fs.existsSync(componentFile)){
      console.log(colors.error(' ERROR: Component exists!'));
      return;
    }
	fs.copySync(componentFileTemplate,componentFile);

	//compile coffee script file
	compiler(componentFile,user_vars);


	//copy test files
	var unitTestFolder=path.join(projectFolder,'tests/unit',componentFolderName,componentName);
	if(fs.existsSync(unitTestFolder)){
		fs.removeSync(unitTestFolder);
	}
	fs.ensureDirSync(unitTestFolder);

	if(componentConfig.test){

		var testScriptTemplate=path.join(componentTemplatePath,componentConfig.test.script);
		var testViewTemplate=path.join(componentTemplatePath,componentConfig.test.view);

		var testScriptFile=path.join(unitTestFolder,util.format('%s_test.coffee',componentName));
		var testViewFile=path.join(unitTestFolder,'index.html');

		fs.copySync(testScriptTemplate,testScriptFile);
		compiler(testScriptFile,user_vars);

		fs.copySync(testViewTemplate,testViewFile);
		compiler(testViewFile,user_vars);
	}

	console.log(colors.green(' component [ %s:%s ] added.'),componentType,componentName);

}
示例#6
0
var rpt = require('read-package-tree');
var data = require('./package.json');
var path = require('path');
var glob = require('glob');
var fs = require('fs-extra');

var seen = {};

var schemaDir = path.resolve('./schemas');
fs.removeSync(schemaDir);
fs.ensureDirSync(schemaDir);

var themesDir = path.resolve('./themes');
fs.removeSync(themesDir);
fs.ensureDirSync(themesDir);


function extractNode(data) {
  data.children.forEach(function(child) {
    extractNode(child);
  });

  if (seen[data.package.name]) {
    return;
  }
  seen[data.package.name] = true;
  var jlab = data.package.jupyterlab
  if (!jlab) {
    return;
  }
示例#7
0
文件: log.js 项目: FisherYu-CN/webapp
export default function create(name, options = {})
{
	const console_output = new stream()
	console_output.writable = true

	// for console_output.write()
	const _print = print

	console_output.write = data =>
	{
		if (data.err)
		{
			return print_error(data.err)
		}

		const print = (level, message, time) => _print(data.name, level, message, time)

		print(levels[data.level] || '...', data.msg, data.time)

		// switch (data.level)
		// {
		// 	case 60:
		// 		print('Fatal', data.msg, data.time)
		// 		break
		//
		// 	case 50:
		// 		print('Error', data.msg, data.time)
		// 		break
		//
		// 	case 40:
		// 		print('Warning', data.msg, data.time)
		// 		break
		//
		// 	case 30:
		// 		print('Generic', data.msg, data.time)
		// 		break
		//
		// 	case 20:
		// 		print('Debug', data.msg, data.time)
		// 		break
		//
		// 	case 10:
		// 		print('Trace', data.msg, data.time)
		// 		break
		//
		// 	default:
		// 		print('...', data.msg, data.time)
		// 		break
		// }
	}

	const development_log = 
	{
		streams: 
		[{
			type   : 'raw',
			stream : console_output
		}],
		serializers: 
		{
			error    : bunyan.stdSerializers.err,
			request  : bunyan.stdSerializers.req,
			response : bunyan.stdSerializers.res,
		}
	}

	const log_path = path.resolve(Root_folder, 'log', `${name}.txt`)

	fs.ensureDirSync(path.dirname(log_path))

	const production_log =
	{
		streams:
		[{
			type   : 'rotating-file',
			path   : log_path,
			period : '1d',            // daily rotation
			count  : 3                // keep 3 back copies
		}],
		serializers: 
		{
			error    : bunyan.stdSerializers.err,
			request  : bunyan.stdSerializers.req,
			response : bunyan.stdSerializers.res,
		}
	}

	const log_configuration = (_production_ || process.env.NODE_ENV === 'production') ? production_log : development_log

	if (options.use_log_server !== false)
	{
		const log_service = tcp_client({ host: configuration.log_service.tcp.host, port: configuration.log_service.tcp.port })

		log_service.on('error', function(error)
		{
			// `log` is a global variable once the logger has been created
			console.error(`There's been an error related to sending messages to log server.`, error)
		})

		log_service.on('close', function()
		{
			// `log` is a global variable once the logger has been created
			log.info(`No more log messages will be sent to the log server.`)
		})

		log_configuration.streams.unshift
		({
			type   : 'raw',
			stream : log_service.stream
		})
	}

	return bunyan.createLogger(extend({ name }, log_configuration))
}
示例#8
0
文件: index.js 项目: ubenzer/fil
console.info('=== Fil ===')
console.info(`Running using node ${process.version}`)

const argv = parseArgs(process.argv, {boolean: ['dynamic', 'force', 'nocache']})

const projectRootFile = require(path.join(process.cwd(), 'index.js'))

const project = new Project({
  listenToChanges: argv.dynamic,
  project: projectRootFile,
  useCache: !argv.nocache
})

const pidFolder = path.join(process.cwd(), projectRootFile.cachePath)

fs.ensureDirSync(pidFolder) // eslint-disable-line no-sync

const pid = npid.create(path.join(pidFolder, 'running.pid'), argv.force)
process.exitCode = 0

if (process.platform === 'win32') {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })

  rl.on('SIGINT', () => {
    process.emit('SIGINT')
  })
}
async function translateChallenge(file) {
  const { name, fullPath, fullParentDir, stat } = file;
  if (stat.isDirectory() || name === '.DS_Store' || file.depth === 1) {
    return null;
  }

  const pathIndex = fullPath.indexOf('guide') + 6;
  const outputDir =
    fullParentDir.substring(0, pathIndex) +
    `${langFull}/` +
    fullParentDir.substring(pathIndex + 8);
  const outputPath =
    fullPath.substring(0, pathIndex) +
    `${langFull}/` +
    fullPath.substring(pathIndex + 8);
  if (fs.existsSync(outputPath)) {
    return null;
  }
  fs.ensureDirSync(outputDir);

  const fileString = fs.readFileSync(fullPath).toString();
  var i = fileString.indexOf('---', 4);
  const meta = fileString.substring(0, i + 4);
  const title = fileString.split('\n')[1].split(': ')[1];
  var article = fileString.substring(i + 4);

  var htmlArticle = converter.makeHtml(article);
  htmlArticle = htmlArticle.replace(/\n/g, '<br>');
  htmlArticle = htmlArticle.replace(
    / {8}/g,
    '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
  );
  htmlArticle = htmlArticle.replace(/ {4}/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
  htmlArticle = htmlArticle.replace(/ {2}/g, '&nbsp;&nbsp;');
  return Promise.all([translateText(title), translateText(htmlArticle)]).then(
    function(translations) {
      // Replace English with translation
      let translatedTitle = translations[0][0];
      let tempArticle = translations[1][0];
      tempArticle = tempArticle.replace(/<br>/g, '\n');
      tempArticle = tempArticle.replace(/&#39;/g, "'");

      tempArticle = tempArticle.replace(
        /language-html">/g,
        'language-html">\n'
      );
      tempArticle = tempArticle.replace(/<pre> <code/g, '<pre><code');
      tempArticle = tempArticle.replace(/<\/pre> <\/code/g, '</pre></code');
      tempArticle = tempArticle.replace(/&nbsp;/g, ' ');
      let translatedArticle = turndownService.turndown(tempArticle);
      translatedArticle = translatedArticle.replace(/\n\n\`\`\`\n/g, '\n```\n');
      let translatedFile =
        meta.slice(0, i) +
        `localeTitle: ${translatedTitle}\n` +
        meta.slice(i) +
        translatedArticle;

      writeFile(translatedFile, outputPath);
    }
  );
}
示例#10
0
 installHelpers.getLatestFrameworkVersion(function(error, latestFrameworkTag) {
   if(error) {
     return handleError(error, 1, 'Failed to get the latest framework version. Check package.json.');
   }
   inputData = {
     useConfigJSON: {
       name: 'useJSON',
       description: 'Use existing config values? y/N',
       type: 'string',
       before: installHelpers.inputHelpers.toBoolean,
       default: 'N'
     },
     startInstall: {
       name: 'install',
       description: 'Continue? Y/n',
       type: 'string',
       before: installHelpers.inputHelpers.toBoolean,
       default: 'Y'
     },
     server: [
       {
         name: 'serverPort',
         type: 'number',
         description: 'Server port',
         pattern: installHelpers.inputHelpers.numberValidator,
         default: 5000
       },
       {
         name: 'serverName',
         type: 'string',
         description: 'Server name',
         default: 'localhost'
       },
       {
         name: 'dataRoot',
         type: 'string',
         description: 'Data directory path',
         pattern: installHelpers.inputHelpers.alphanumValidator,
         default: 'data'
       },
       {
         name: 'authoringToolRepository',
         type: 'string',
         description: "Git repository URL to be used for the authoring tool source code",
         default: 'https://github.com/adaptlearning/adapt_authoring.git'
       },
       {
         name: 'frameworkRepository',
         type: 'string',
         description: "Git repository URL to be used for the framework source code",
         default: 'https://github.com/adaptlearning/adapt_framework.git'
       },
       {
         name: 'frameworkRevision',
         type: 'string',
         description: 'Specific git revision to be used for the framework. Accepts any valid revision type (e.g. branch/tag/commit)',
         default: 'tags/' + latestFrameworkTag
       }
     ],
     database: {
       dbConfig: [
         {
           name: 'dbName',
           type: 'string',
           description: 'Master database name',
           pattern: installHelpers.inputHelpers.alphanumValidator,
           default: 'adapt-tenant-master'
         },
         {
           name: 'useConnectionUri',
           type: 'string',
           description: "Will you be using a full database connection URI? (all connection options in the URI) y/N",
           before: installHelpers.inputHelpers.toBoolean,
           default: 'N'
         }
       ],
       configureUri: [
         {
           name: 'dbConnectionUri',
           type: 'string',
           description: 'Database connection URI',
           default: ''
         }
       ],
       configureStandard: [
         {
           name: 'dbHost',
           type: 'string',
           description: 'Database host',
           default: 'localhost'
         },
         {
           name: 'dbPort',
           type: 'number',
           description: 'Database server port',
           pattern: installHelpers.inputHelpers.numberValidator,
           default: 27017
         },
         {
           name: 'dbUser',
           type: 'string',
           description: 'Database server user (only specify if using database authentication)',
           pattern: installHelpers.inputHelpers.alphanumValidator,
           default: ''
         },
         {
           name: 'dbPass',
           type: 'string',
           description: 'Database server password (only specify if using database authentication)',
           pattern: installHelpers.inputHelpers.alphanumValidator,
           default: ''
         },
         {
           name: 'dbAuthSource',
           type: 'string',
           description: 'Database server authentication database (only specify if using database authentication)',
           pattern: installHelpers.inputHelpers.alphanumValidator,
           default: ''
         },
       ]
     },
     features: {
       smtp: {
         confirm: {
           name: 'useSmtp',
           type: 'string',
           description: "Will you be using an SMTP server? (used for sending emails) y/N",
           before: installHelpers.inputHelpers.toBoolean,
           default: 'N'
         },
         confirmConnectionUrl: {
           name: 'useSmtpConnectionUrl',
           type: 'string',
           description: "Will you use a URL to connect to your smtp Server y/N",
           before: installHelpers.inputHelpers.toBoolean,
           default: 'N'
         },
         configure: [
           {
             name: 'fromAddress',
             type: 'string',
             description: "Sender email address",
             default: '',
           },
           {
             name: 'rootUrl',
             type: 'string',
             description: "The url this install will be accessible from",
             default: '' // set using default server options
           }
         ],
         configureService: [
           {
             name: 'smtpService',
             type: 'string',
             description: "Which SMTP service (if any) will be used? (see https://github.com/andris9/nodemailer-wellknown#supported-services for a list of supported services.)",
             default: 'none',
           },
           {
             name: 'smtpUsername',
             type: 'string',
             description: "SMTP username",
             default: '',
           },
           {
             name: 'smtpPassword',
             type: 'string',
             description: "SMTP password",
             hidden: true,
             replace: installHelpers.inputHelpers.passwordReplace,
             default: '',
             before: installHelpers.inputHelpers.passwordBefore
           }
         ],
         configureConnectionUrl: [
           {
             name: 'smtpConnectionUrl',
             type: 'string',
             description: "Custom connection URL: smtps://user%40gmail.com:pass@smtp.gmail.com/?pool=true",
             default: 'none',
           }
         ]
       }
     },
     tenant: [
       {
         name: 'masterTenantName',
         type: 'string',
         description: "Set a unique name for your tenant",
         pattern: installHelpers.inputHelpers.alphanumValidator,
         default: 'master'
       },
       {
         name: 'masterTenantDisplayName',
         type: 'string',
         description: 'Set the display name for your tenant',
         default: 'Master'
       }
     ],
     tenantDelete: {
       name: "confirm",
       description: "Continue? (Y/n)",
       before: installHelpers.inputHelpers.toBoolean,
       default: "Y"
     },
     superUser: [
       {
         name: 'suEmail',
         type: 'string',
         description: "Email address",
         required: true
       },
       {
         name: 'suPassword',
         type: 'string',
         description: "Password",
         hidden: true,
         replace: installHelpers.inputHelpers.passwordReplace,
         required: true,
         before: installHelpers.inputHelpers.passwordBefore
       },
       {
         name: 'suRetypePassword',
         type: 'string',
         description: "Confirm Password",
         hidden: true,
         replace: installHelpers.inputHelpers.passwordReplace,
         required: true,
         before: installHelpers.inputHelpers.passwordBefore
       }
     ]
   };
   if(!IS_INTERACTIVE) {
     return start();
   }
   console.log('');
   if(!fs.existsSync('conf/config.json')) {
     fs.ensureDirSync('conf');
     return start();
   }
   console.log('Found an existing config.json file. Do you want to use the values in this file during install?');
   installHelpers.getInput(inputData.useConfigJSON, function(result) {
     console.log('');
     USE_CONFIG = result.useJSON;
     start();
   });
 });
var jpsPassbook = new Passbook(program);
var utils = require(path.resolve(__dirname, './lib/utils.js'));
var Pass = require(path.resolve(__dirname, './lib/models/pass.js'));
//var Passes = require(path.resolve(__dirname, './lib/models/passes.js'));
var Device = require(path.resolve(__dirname, './lib/models/device.js'));
var child_process = require('child_process');
const SignPass = require('./lib/signpass');

var output_url = path.resolve(__dirname, './tmp');
var wwdr_url = path.resolve(__dirname, './certificates/wwdr-authority.pem');
var cert_url = path.resolve(__dirname, './certificates/pass-cert.pem');
var key_url = path.resolve(__dirname, './certificates/pass-key.pem');
var cert_pass = '******';
var pass_url = path.resolve(__dirname, './data/passes/pass-jonniespratley.raw');

fs.ensureDirSync(output_url);


var logger = utils.getLogger('scratch');

var APN_CERT = './certificates/passbookmanager-apns-cert.p12';
var APN_KEY = './certificates/passbookmanager-apns-key.p12';
var APN_CERT_PEM = APN_CERT.replace('.p12', '.pem');
var APN_KEY_PEM = APN_KEY.replace('.p12', '.pem');
var APN_KEY_PEM_PASS = '******';

// TODO: Sign cert_pass
var exec = child_process.exec;

//var cmd1 = `openssl x509 -in ${APN_CERT} -inform DER -outform PEM -out ${APN_CERT_PEM}`
var cmd1 = `openssl pkcs12 -clcerts -nokeys -out ${APN_CERT_PEM} -in ${APN_CERT}`;
示例#12
0
 exportAndroidStudioProject(name, _targetOptions, from) {
     let safename = name.replace(/ /g, '-');
     this.safename = safename;
     let targetOptions = {
         package: 'tech.kode.kha',
         installLocation: "internalOnly",
         screenOrientation: 'sensor',
         permissions: new Array()
     };
     if (_targetOptions != null && _targetOptions.android != null) {
         let userOptions = _targetOptions.android;
         if (userOptions.package != null)
             targetOptions.package = userOptions.package;
         if (userOptions.installLocation != null)
             targetOptions.installLocation = userOptions.installLocation;
         if (userOptions.screenOrientation != null)
             targetOptions.screenOrientation = userOptions.screenOrientation;
         if (userOptions.permissions != null)
             targetOptions.permissions = userOptions.permissions;
     }
     let indir = path.join(__dirname, '..', '..', 'Data', 'android');
     let outdir = path.join(this.options.to, this.sysdir(), safename);
     fs.copySync(path.join(indir, 'gitignore'), path.join(outdir, '.gitignore'));
     fs.copySync(path.join(indir, 'build.gradle'), path.join(outdir, 'build.gradle'));
     fs.copySync(path.join(indir, 'gradle.properties'), path.join(outdir, 'gradle.properties'));
     fs.copySync(path.join(indir, 'gradlew'), path.join(outdir, 'gradlew'));
     fs.copySync(path.join(indir, 'gradlew.bat'), path.join(outdir, 'gradlew.bat'));
     fs.copySync(path.join(indir, 'settings.gradle'), path.join(outdir, 'settings.gradle'));
     fs.copySync(path.join(indir, 'app', 'gitignore'), path.join(outdir, 'app', '.gitignore'));
     let gradle = fs.readFileSync(path.join(indir, 'app', 'build.gradle'), { encoding: 'utf8' });
     gradle = gradle.replace(/{package}/g, targetOptions.package);
     fs.writeFileSync(path.join(outdir, 'app', 'build.gradle'), gradle, { encoding: 'utf8' });
     fs.copySync(path.join(indir, 'app', 'proguard-rules.pro'), path.join(outdir, 'app', 'proguard-rules.pro'));
     fs.ensureDirSync(path.join(outdir, 'app', 'src'));
     // fs.emptyDirSync(path.join(outdir, 'app', 'src'));
     let manifest = fs.readFileSync(path.join(indir, 'main', 'AndroidManifest.xml'), { encoding: 'utf8' });
     manifest = manifest.replace(/{package}/g, targetOptions.package);
     manifest = manifest.replace(/{installLocation}/g, targetOptions.installLocation);
     manifest = manifest.replace(/{screenOrientation}/g, targetOptions.screenOrientation);
     manifest = manifest.replace(/{permissions}/g, targetOptions.permissions.map(function (p) { return '\n\t<uses-permission android:name="' + p + '"/>'; }).join(''));
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main'));
     fs.writeFileSync(path.join(outdir, 'app', 'src', 'main', 'AndroidManifest.xml'), manifest, { encoding: 'utf8' });
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'values'));
     let strings = fs.readFileSync(path.join(indir, 'main', 'res', 'values', 'strings.xml'), { encoding: 'utf8' });
     strings = strings.replace(/{name}/g, name);
     fs.writeFileSync(path.join(outdir, 'app', 'src', 'main', 'res', 'values', 'strings.xml'), strings, { encoding: 'utf8' });
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-hdpi'));
     ImageTool_1.exportImage(this.options.kha, findIcon(from, this.options), path.join(this.options.to, this.sysdir(), safename, 'app', 'src', 'main', 'res', 'mipmap-hdpi', 'ic_launcher'), { width: 72, height: 72 }, 'png', false, false, {});
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-mdpi'));
     ImageTool_1.exportImage(this.options.kha, findIcon(from, this.options), path.join(this.options.to, this.sysdir(), safename, 'app', 'src', 'main', 'res', 'mipmap-mdpi', 'ic_launcher'), { width: 48, height: 48 }, 'png', false, false, {});
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-xhdpi'));
     ImageTool_1.exportImage(this.options.kha, findIcon(from, this.options), path.join(this.options.to, this.sysdir(), safename, 'app', 'src', 'main', 'res', 'mipmap-xhdpi', 'ic_launcher'), { width: 96, height: 96 }, 'png', false, false, {});
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-xxhdpi'));
     ImageTool_1.exportImage(this.options.kha, findIcon(from, this.options), path.join(this.options.to, this.sysdir(), safename, 'app', 'src', 'main', 'res', 'mipmap-xxhdpi', 'ic_launcher'), { width: 144, height: 144 }, 'png', false, false, {});
     fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-xxxhdpi'));
     ImageTool_1.exportImage(this.options.kha, findIcon(from, this.options), path.join(this.options.to, this.sysdir(), safename, 'app', 'src', 'main', 'res', 'mipmap-xxxhdpi', 'ic_launcher'), { width: 192, height: 192 }, 'png', false, false, {});
     fs.copySync(path.join(indir, 'gradle', 'wrapper', 'gradle-wrapper.jar'), path.join(outdir, 'gradle', 'wrapper', 'gradle-wrapper.jar'));
     fs.copySync(path.join(indir, 'gradle', 'wrapper', 'gradle-wrapper.properties'), path.join(outdir, 'gradle', 'wrapper', 'gradle-wrapper.properties'));
     fs.copySync(path.join(indir, 'idea', 'gradle.xml'), path.join(outdir, '.idea', 'gradle.xml'));
     fs.copySync(path.join(indir, 'idea', 'misc.xml'), path.join(outdir, '.idea', 'misc.xml'));
     fs.copySync(path.join(indir, 'idea', 'runConfigurations.xml'), path.join(outdir, '.idea', 'runConfigurations.xml'));
     fs.copySync(path.join(indir, 'idea', 'codeStyles', 'Project.xml'), path.join(outdir, '.idea', 'codeStyles', 'Project.xml'));
 }
示例#13
0
var fs			= require('fs-extra');
var path		= require('path-extra');
var jsop		= require('jsop');

var datadir = path.datadir('com.athom.homey-cli');
var datafile = path.join( datadir, 'settings.json' );

fs.ensureDirSync(datadir);

global.settings = jsop(datafile);
示例#14
0
console.log("Bundling Rabix Executor", requiredExecutorVersion);
const targetDir = path.resolve(__dirname + "/../electron/executor");

try {
    const test = child.execSync("java -jar " + targetDir + "/lib/rabix-cli.jar --version");
    const output = "v" + test.toString().trim().slice(6);
    if (requiredExecutorVersion === output) {
        console.log("Stopping download, Rabix executor is already bundled.");
        process.exit(0);
    }
} catch (ex) {
    console.log("Preparing to download...");
}

rimraf.sync(targetDir);
fs.ensureDirSync(targetDir);

const tmpDir = targetDir + "/tmp";
fs.ensureDir(tmpDir);

console.log("Downloading", executorDownloadURL);

const write = request.get({
    uri: executorDownloadURL,
    gzip: true,
    encoding: null,
}).pipe(tar.x({
    C: tmpDir
}));

write.on("close", () => {
0,f="backup"+b;this._hasBackupWithPrefix(f,a);)b++,f="backup"+b;return f};e.prototype._hasBackupWithPrefix=function(a,b){for(var f=0;f<b.length;f++)if(b[f]&&b[f].substr(0,a.length)==a)return!0;return!1};e.prototype._unzip=function(a,b,f){var e=require("adm-zip"),d=this._fm.getTmpDir(),g=require("path"),c=require("fs-extra");a=new e(a);b=g.join(d,b);try{c.existsSync(b)&&c.removeSync(b),c.ensureDirSync(b),a.extractAllTo(b,!0),f&&f(null,b)}catch(n){f&&f(n)}};e.prototype._deleteCurrentFolders=function(a,
示例#16
0
 fs.readFile(path.join(global.nodulsRepo, module_name + ".zip"), function (err, data) {
     if (err)
         throw err;
     var zip = new JSZip(data);
     var fileData = zip.file(consts.MANIFEST_NAME).asText();
     fs.writeFileSync(path.join(baseFolder, consts.MANIFEST_NAME), fileData, 'utf8');
     var manifest_file = fs.readJsonSync(path.join(baseFolder, consts.MANIFEST_NAME), { throws: true });
     if (manifest_file.files !== undefined) {
         for (var i = 0; i < manifest_file.files.length; i++) {
             var filename = manifest_file.files[i];
             if (zip.file(filename)) {
                 var fileData = zip.file(filename).asText();
                 if (filename.indexOf('/') > -1) {
                     var directoryPath = (path.join(baseFolder, path.normalize(filename)));
                     directoryPath = path.dirname(directoryPath); //.substr(0, directoryPath.lastIndexOf('\\'));
                     if (!fs.existsSync(directoryPath))
                         mkdirp.sync(directoryPath);
                 }
                 fs.writeFileSync(path.join(baseFolder, filename), fileData, 'utf8');
             }
         }
     }
     if (manifest_file.routes !== undefined) {
         for (var i = 0; i < manifest_file.routes.length; i++) {
             var filename = manifest_file.routes[i].path;
             if (zip.folder("routes").file(filename)) {
                 var fileData = zip.folder("routes").file(filename).asText();
                 fs.writeFileSync(path.join(serverRoot, "routes", filename), fileData, 'utf8');
             }
             //attach the new route to express
             app.use(module_name, require('../routes/' + filename));
         }
     }
     if (manifest_file.scripts !== undefined) {
         fs.ensureDirSync(path.join(baseFolder, "scripts"));
         for (var i = 0; i < manifest_file.scripts.length; i++) {
             var filename = manifest_file.scripts[i];
             if (zip.folder("scripts").file(filename)) {
                 var fileData = zip.folder("scripts").file(filename).asText();
                 fs.writeFileSync(path.join(baseFolder, "scripts", filename), fileData, 'utf8');
             }
         }
     }
     var aboutfilename = "about.html";
     if (zip.file(aboutfilename) !== null) {
         var fileData = zip.file(aboutfilename).asText();
         fs.writeFileSync(path.join(baseFolder, aboutfilename), fileData, 'utf8');
     }
     var modules_file = {};
     modules_file = config.modulesSettings;
     if (modules_file[module_name] === undefined) {
         modules_file[module_name] = {};
     }
     //merge the manifest into the  file
     if (manifest_file === null)
         callback("invalid json, try using ascii file");
     //update navigation
     if (manifest_file.navigation)
         dal.connect(function (err, db) {
             for (var i = 0; i < manifest_file.navigation.length; i++) {
                 db.collection("Navigation").save(manifest_file.navigation[i], function (err, data) {
                 });
             }
         });
     modules_file[module_name] = manifest_file;
     if (manifest_file.npm !== undefined) {
         var arr = [];
         for (var x in manifest_file.npm) {
             arr.push({ name: x, ver: manifest_file.npm[x] });
         }
         //install npm dependencies
         var async = require("async");
         async.each(arr, instance.npm_install, function () {
             //fs.writeFileSync(modules_configuration_path, JSON.stringify(modules_file));
             callback(null, manifest_file);
         });
     }
     else {
         // fs.writeFileSync(modules_configuration_path, JSON.stringify(modules_file));
         callback(null, manifest_file);
     }
 });
示例#17
0
 .then(() => fs.ensureDirSync('src'))
示例#18
0
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');

var Build = require('@jupyterlab/buildutils').Build;
var package_data = require('./package.json');

// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
  packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
  output: jlab.outputDir
});

fs.ensureDirSync('node_modules/codemirror/mode/prolog');
fs.copySync(path.join(path.resolve(jlab.buildDir),'../../../kernels/yap_kernel/prolog.js'), 'node_modules/codemirror/mode/prolog/prolog.js');
fs.copySync(path.join(path.resolve(jlab.buildDir),'../../../kernels/yap_kernel/meta.js'), 'node_modules/codemirror/mode/meta.js');

// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
  jupyterlab_extensions: extensions,
  jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);

// Ensure a clear build directory.
var buildDir = path.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
示例#19
0
文件: tasks.js 项目: endel/LD34
async function copy() {
  fs.ensureDirSync('release');
  fs.copySync('res/html/index.html', 'release/index.html');
  fs.copySync('res/images', 'release/images');
  fs.copySync('res/fonts', 'release/fonts');
}
示例#20
0
	exportSolution(solution, from, to, platform, vr) {
		let project = solution.getProjects()[0];
		let safename = solution.getName().replaceAll(' ', '-');
		this.safename = safename;

		const indir = path.join(__dirname, 'Data', 'android');
		const outdir = path.join(to.toString(), safename);

		fs.copySync(path.join(indir, 'build.gradle'), path.join(outdir, 'build.gradle'));
		fs.copySync(path.join(indir, 'gradle.properties'), path.join(outdir, 'gradle.properties'));
		fs.copySync(path.join(indir, 'gradlew'), path.join(outdir, 'gradlew'));
		fs.copySync(path.join(indir, 'gradlew.bat'), path.join(outdir, 'gradlew.bat'));
		fs.copySync(path.join(indir, 'settings.gradle'), path.join(outdir, 'settings.gradle'));

		let nameiml = fs.readFileSync(path.join(indir, 'name.iml'), {encoding: 'utf8'});
		nameiml = nameiml.replaceAll('{name}', safename);
		fs.writeFileSync(path.join(outdir, safename + '.iml'), nameiml, {encoding: 'utf8'});

		fs.copySync(path.join(indir, 'app', 'proguard-rules.pro'), path.join(outdir, 'app', 'proguard-rules.pro'));

		let flags = '\n';
		flags += '        cppFlags += "-fexceptions"\n';
		flags += '        cppFlags += "-frtti"\n';
		for (let def of project.getDefines()) {
			flags += '        cppFlags += "-D' + def + '"\n';
			flags += '        CFlags += "-D' + def + '"\n';
		}
		for (let inc of project.getIncludeDirs()) {
			inc = inc.replaceAll('\\', '/');
			while (inc.startsWith('../')) inc = inc.substr(3);
			flags += '        cppFlags += "-I${file("src/main/jni/' + inc + '")}".toString()\n';
			flags += '        CFlags += "-I${file("src/main/jni/' + inc + '")}".toString()\n';
		}

		let gradle = fs.readFileSync(path.join(indir, 'app', 'build.gradle'), {encoding: 'utf8'});
		gradle = gradle.replaceAll('{name}', safename);
		gradle = gradle.replaceAll('{flags}', flags);

		let javasources = '';
		for (let dir of project.getJavaDirs()) {
			javasources += "                    srcDir '" + path.relative(path.join(outdir, 'app'), from.resolve(dir).toString()).replaceAll('\\', '/') + "'\n";
		}
		javasources += "                    srcDir '" + path.relative(path.join(outdir, 'app'), path.join(Project.koreDir.toString(), 'Backends', 'Android', 'Java-Sources')).replaceAll('\\', '/') + "'\n";
		gradle = gradle.replaceAll('{javasources}', javasources);

		//gradle = gradle.replaceAll('{cppsources}', ''); // Currently at the default position
		fs.writeFileSync(path.join(outdir, 'app', 'build.gradle'), gradle, {encoding: 'utf8'});

		let appiml = fs.readFileSync(path.join(indir, 'app', 'app.iml'), {encoding: 'utf8'});
		appiml = appiml.replaceAll('{name}', safename);
		fs.writeFileSync(path.join(outdir, 'app', 'app.iml'), appiml, {encoding: 'utf8'});

		fs.ensureDirSync(path.join(outdir, 'app', 'src'));
		//fs.emptyDirSync(path.join(outdir, 'app', 'src'));

		fs.copySync(path.join(indir, 'main', 'AndroidManifest.xml'), path.join(outdir, 'app', 'src', 'main', 'AndroidManifest.xml'));

		let strings = fs.readFileSync(path.join(indir, 'main', 'res', 'values', 'strings.xml'), {encoding: 'utf8'});
		strings = strings.replaceAll('{name}', solution.getName());
		fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'values'));
		fs.writeFileSync(path.join(outdir, 'app', 'src', 'main', 'res', 'values', 'strings.xml'), strings, {encoding: 'utf8'});

		fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-hdpi'));
		Icon.exportPng(to.resolve(Paths.get(safename, 'app', 'src', 'main', 'res', 'mipmap-hdpi', "ic_launcher.png")), 72, 72, undefined, from);
		fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-mdpi'));
		Icon.exportPng(to.resolve(Paths.get(safename, 'app', 'src', 'main', 'res', 'mipmap-mdpi', "ic_launcher.png")), 48, 48, undefined, from);
		fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-xhdpi'));
		Icon.exportPng(to.resolve(Paths.get(safename, 'app', 'src', 'main', 'res', 'mipmap-xhdpi', "ic_launcher.png")), 96, 96, undefined, from);
		fs.ensureDirSync(path.join(outdir, 'app', 'src', 'main', 'res', 'mipmap-xxhdpi'));
		Icon.exportPng(to.resolve(Paths.get(safename, 'app', 'src', 'main', 'res', 'mipmap-xxhdpi', "ic_launcher.png")), 144, 144, undefined, from);

		fs.copySync(path.join(indir, 'gradle', 'wrapper', 'gradle-wrapper.jar'), path.join(outdir, 'gradle', 'wrapper', 'gradle-wrapper.jar'));
		fs.copySync(path.join(indir, 'gradle', 'wrapper', 'gradle-wrapper.properties'), path.join(outdir, 'gradle', 'wrapper', 'gradle-wrapper.properties'));

		fs.copySync(path.join(indir, 'idea', 'compiler.xml'), path.join(outdir, '.idea', 'compiler.xml'));
		fs.copySync(path.join(indir, 'idea', 'encodings.xml'), path.join(outdir, '.idea', 'encodings.xml'));
		fs.copySync(path.join(indir, 'idea', 'gradle.xml'), path.join(outdir, '.idea', 'gradle.xml'));
		fs.copySync(path.join(indir, 'idea', 'misc.xml'), path.join(outdir, '.idea', 'misc.xml'));
		fs.copySync(path.join(indir, 'idea', 'runConfigurations.xml'), path.join(outdir, '.idea', 'runConfigurations.xml'));
		fs.copySync(path.join(indir, 'idea', 'vcs.xml'), path.join(outdir, '.idea', 'vcs.xml'));
		fs.copySync(path.join(indir, 'idea', 'copyright', 'profiles_settings.xml'), path.join(outdir, '.idea', 'copyright', 'profiles_settings.xml'));

		let namename = fs.readFileSync(path.join(indir, 'idea', 'name'), {encoding: 'utf8'});
		namename = namename.replaceAll('{name}', solution.getName());
		fs.writeFileSync(path.join(outdir, '.idea', '.name'), namename, {encoding: 'utf8'});

		let modules = fs.readFileSync(path.join(indir, 'idea', 'modules.xml'), {encoding: 'utf8'});
		modules = modules.replaceAll('{name}', safename);
		fs.writeFileSync(path.join(outdir, '.idea', 'modules.xml'), modules, {encoding: 'utf8'});

		if (project.getDebugDir().length > 0) this.copyDirectory(from.resolve(project.getDebugDir()), to.resolve(Paths.get(safename, 'app', 'src', 'main', 'assets')));

		for (let file of project.getFiles()) {
			let localFile = file;
			while (localFile.startsWith('../')) localFile = localFile.substr(3);
			let target = to.resolve(Paths.get(safename, 'app', 'src', 'main', 'jni')).resolve(localFile);
			this.createDirectory(Paths.get(target.path.substr(0, target.path.lastIndexOf('/'))));
			Files.copyIfDifferent(from.resolve(file), target, true);
		}
	}
示例#21
0
 createRandomDirectory() {
   const randomDir = fs.mkdtempSync(path.join(os.tmpdir(), 'detoxrand-'));
   fs.ensureDirSync(randomDir);
   return randomDir;
 }
示例#22
0
var make_lib_files = function (import_format, source_maps, with_app_dir, only_legacy) {
    if (!import_format) {
        throw new Error("you must specify an import format to generate compiled noVNC libraries");
    } else if (!SUPPORTED_FORMATS.has(import_format)) {
        throw new Error(`unsupported output format "${import_format}" for import/export -- only ${Array.from(SUPPORTED_FORMATS)} are supported`);
    }

    // NB: we need to make a copy of babel_opts, since babel sets some defaults on it
    const babel_opts = () => ({
        plugins: [`transform-es2015-modules-${import_format}`],
        ast: false,
        sourceMaps: source_maps,
    });

    // No point in duplicate files without the app, so force only converted files
    if (!with_app_dir) {
        only_legacy = true;
    }

    var in_path;
    if (with_app_dir) {
        var out_path_base = paths.out_dir_base;
        in_path = paths.main;
    } else {
        var out_path_base = paths.lib_dir_base;
    }
    const legacy_path_base = only_legacy ? out_path_base : path.join(out_path_base, 'legacy');

    fse.ensureDirSync(out_path_base);

    const helpers = require('./use_require_helpers');
    const helper = helpers[import_format];

    const outFiles = [];

    var handleDir = (js_only, vendor_rewrite, in_path_base, filename) => Promise.resolve()
    .then(() => {
        if (no_copy_files.has(filename)) return;

        const out_path = path.join(out_path_base, path.relative(in_path_base, filename));
        const legacy_path = path.join(legacy_path_base, path.relative(in_path_base, filename));

        if(path.extname(filename) !== '.js') {
            if (!js_only) {
                console.log(`Writing ${out_path}`);
                return copy(filename, out_path);
            }
            return;  // skip non-javascript files
        }

        return Promise.resolve()
        .then(() => {
            if (only_legacy && !no_transform_files.has(filename)) {
                return;
            }
            return ensureDir(path.dirname(out_path))
            .then(() => {
                console.log(`Writing ${out_path}`);
                return copy(filename, out_path);
            })
        })
        .then(() => ensureDir(path.dirname(legacy_path)))
        .then(() => {
            if (no_transform_files.has(filename)) {
                return;
            }

            const opts = babel_opts();
            if (helper && helpers.optionsOverride) {
                helper.optionsOverride(opts);
            }
            // Adjust for the fact that we move the core files relative
            // to the vendor directory
            if (vendor_rewrite) {
                opts.plugins.push(["import-redirect",
                                   {"root": legacy_path_base,
                                    "redirect": { "vendor/(.+)": "./vendor/$1"}}]);
            }

            return babelTransformFile(filename, opts)
            .then(res => {
                console.log(`Writing ${legacy_path}`);
                var {code, map, ast} = res;
                if (source_maps === true) {
                    // append URL for external source map
                    code += `\n//# sourceMappingURL=${path.basename(legacy_path)}.map\n`;
                }
                outFiles.push(`${legacy_path}`);
                return writeFile(legacy_path, code)
                .then(() => {
                    if (source_maps === true || source_maps === 'both') {
                        console.log(`  and ${legacy_path}.map`);
                        outFiles.push(`${legacy_path}.map`);
                        return writeFile(`${legacy_path}.map`, JSON.stringify(map));
                    }
                });
            });
        });
    });

    if (with_app_dir && helper && helper.noCopyOverride) {
        helper.noCopyOverride(paths, no_copy_files);
    }

    Promise.resolve()
    .then(() => {
        let handler = handleDir.bind(null, true, false, in_path || paths.main);
        let filter = (filename, stats) => !no_copy_files.has(filename);
        return walkDir(paths.vendor, handler, filter);
    })
    .then(() => {
        let handler = handleDir.bind(null, true, !in_path, in_path || paths.core);
        let filter = (filename, stats) => !no_copy_files.has(filename);
        return walkDir(paths.core, handler, filter);
    })
    .then(() => {
        if (!with_app_dir) return;
        let handler = handleDir.bind(null, false, false, in_path);
        let filter = (filename, stats) => !no_copy_files.has(filename);
        return walkDir(paths.app, handler, filter);
    })
    .then(() => {
        if (!with_app_dir) return;

        if (!helper || !helper.appWriter) {
            throw new Error(`Unable to generate app for the ${import_format} format!`);
        }

        const out_app_path = path.join(legacy_path_base, 'app.js');
        console.log(`Writing ${out_app_path}`);
        return helper.appWriter(out_path_base, legacy_path_base, out_app_path)
        .then(extra_scripts => {
            let rel_app_path = path.relative(out_path_base, out_app_path);
            let legacy_scripts = extra_scripts.concat([rel_app_path]);
            transform_html(legacy_scripts, only_legacy);
        })
        .then(() => {
            if (!helper.removeModules) return;
            console.log(`Cleaning up temporary files...`);
            return Promise.all(outFiles.map(filepath => {
                unlink(filepath)
                .then(() => {
                    // Try to clean up any empty directories if this
                    // was the last file in there
                    let rmdir_r = dir => {
                        return rmdir(dir)
                        .then(() => rmdir_r(path.dirname(dir)))
                        .catch(() => {
                            // Assume the error was ENOTEMPTY and ignore it
                        });
                    };
                    return rmdir_r(path.dirname(filepath));
                });
            }));
        });
    })
    .catch((err) => {
        console.error(`Failure converting modules: ${err}`);
        process.exit(1);
    });
};
示例#23
0
 copyFiles: function (webappDir) {
     fse.ensureDirSync(webappDir + '/resources/plugins/markdown');
     fse.copySync(path.resolve(__dirname, './web'), webappDir + '/resources/plugins/markdown');
 },
示例#24
0
文件: build.js 项目: Eric2014/chihuo
const fs   = require('fs-extra');
const path = require('path');

const lib = path.resolve(__dirname, '..', 'lib');
const pkg = path.resolve(__dirname, '..', 'package.json');
const dest = path.resolve(__dirname, 'node_modules', 'react-dropzone-component');

fs.ensureDirSync(dest);
fs.emptyDirSync(dest);
fs.copySync(lib, path.resolve(dest, 'lib'));
fs.copySync(pkg, path.resolve(dest, 'package.json'));
示例#25
0
// Script start
module.exports = {
  // main flow
  run(str, option, callback) {
    // moji config
    let asc, end, j;
    let i;
    mojiConfig.moji = str.split('');
    // create id
    const id = randomId(8);
    // dirconfig
    const tmpMojiDir = `${__dirname}/tmp/moji/${id}`;
    const tmpNoDir = `${__dirname}/tmp/no/${id}`;
    // make temporary directory
    fs.ensureDirSync(tmpMojiDir);
    fs.ensureDirSync(tmpNoDir);
    // set splice (first str + each str = moji image width)
    let splice = 0;
    for (let s of Array.from(mojiConfig.size)) {
      splice += s - Math.floor(s / 10);
    }
    // create each moji
    for (
      j = 0, i = j, end = mojiConfig.moji.length - 1, asc = 0 <= end;
      asc ? j <= end : j >= end;
      asc ? j++ : j--, i = j
    ) {
      image.moji(
        {
          pointsize: mojiConfig.size[i],
示例#26
0
Builder.prototype.compileSite = function () {
  logger.info('Compiling site...');
  var builder     = this;
  var buildLoc    = builder.settings.buildLocation;
  var binDir      = builder.settings.binPath;
  var iframeHead  = '';

  /**
   * Right now I'm just wiping the old directory away
   * I think I should consider putting it into a cache
   * location trying to do the build and rolling back
   * if I'm not successful.
   */
  fs.removeSync(buildLoc);

  var buildPaths = {
    jsPath: '/js',
    cssPath: '/stylesheets',
    bowerPath: '/bower_components'
  };

  for (var key in buildPaths) {
    fs.ensureDirSync( path.join(buildLoc, buildPaths[key]) );
  }

  builder.htmlFiles.forEach(function (element, index, array) {
    for (var key in element) {
      if (key === 'heads') {
        iframeHead = element[key].tmps.join(" ");
      } else {
        builder.appendTemplates(element[key].tmps, element[key].data, buildLoc, key);
      }
    }
  });

  builder.htmlFiles = []; // Reset html files to nothing

  builder.documents.forEach(function (element, index, array) {
    var basePath = element.replace(builder.settings.site, '');
    var target = path.join(buildLoc, basePath);
    fs.copySync(element, target);
  });

  builder.documents = []; // Reset html files to nothing

  Handlebars.registerPartial('head', iframeHead);
  var rawIframe = fs.readFileSync(binDir + '/client/html/iframe.handlebars', 'utf8');
  var iframe = Handlebars.compile(rawIframe);
  fs.writeFileSync(buildLoc + '/iframe.html', iframe());

  for (var k in buildPaths) {
    fs.copySync(
        path.join(binDir, '/client/', buildPaths[k]),
        path.join(buildLoc, buildPaths[k])
      );
  }

  fs.copySync(
      path.join(binDir, '/client/html/index.html'),
      path.join(buildLoc, '/index.html')
    );
};
示例#27
0
router.get('/pdf/:id/:start/:end', (req, res, next) => {
  let json = {};
  json.startDate = moment(req.params.start).format('DD/MM') + '/' + (moment(req.params.start).get('year')+543);
  json.endDate = moment(req.params.end).format('DD/MM') + '/' + (moment(req.params.end).get('year') + 543);
  fse.ensureDirSync('./templates/html');
  fse.ensureDirSync('./templates/pdf');

  var destPath = './templates/html/' + moment().format('x');
  fse.ensureDirSync(destPath);

  gulp.task('html', (cb) => {
    return gulp.src('./templates/user-report.jade')
      .pipe(data(function () {
        return json;
      }))
      .pipe(jade())
      .pipe(gulp.dest(destPath));
  });

  gulp.task('pdf', ['html'], () => {
    let html = fs.readFileSync(destPath + '/user-report.html', 'utf8')
    let options = {
      format: 'A4',
      orientation: "landscape",
      footer: {
        height: "15mm",
        contents: '<span style="color: #444;"><small>Printed: ' + new Date() + '</small></span>'
      }
    };

    let pdfName = `./templates/pdf/user-report-${moment().format('x')}.pdf`;

    pdf.create(html, options).toFile(pdfName, (err, resp) => {
      if (err) {
        res.send({ ok: false, msg: err });
      } else {
        res.download(pdfName, () => {
          rimraf.sync(destPath);
          fse.removeSync(pdfName);
        });
      }
    });
  });

    // get user info
  Employee.getInfo(req.db, req.params.id)
    .then(rows => {
      let user = rows[0];

      json.fullname = `${user.first_name} ${user.last_name}`;
      json.departmentName = user.main_name;
      json.subDepartmentName = user.sub_name;

      return Meetings.getExportData(req.db, req.params.id, req.params.start, req.params.end);
    })
    .then(rows => {
      //json.data = rows;
      console.log(rows);
      let meetings = [];

      rows.forEach(v => {
        let obj = {};
        obj.title = v.title;
        obj.owner = v.owner;
        obj.place = v.place;
        obj.start_date = moment(v.start_date).format('DD/MM') + '/' + (moment(v.start_date).get('year') + 543);
        obj.end_date = moment(v.end_date).format('DD/MM') + '/' + (moment(v.end_date).get('year') + 543);
        obj.score = numeral(v.score).format('0,0.00');
        obj.price = numeral(v.price).format('0,0.00');
        obj.type_meetings_name = v.type_meetings_name;
        obj.money_name = v.money_name;
        meetings.push(obj);
      });

      json.meetings = meetings;
      // Convert html to pdf
      gulp.start('pdf');

    })

    .catch(err => res.send({ ok: false, msg: err }));
});
示例#28
0
 before('before clean upload 测试', function () {
   fs.ensureDirSync(basePath);
   fs.copySync(path.resolve(__dirname, '../files'), `${basePath}`);
 });
示例#29
0
function createTmpDirectory() {
  removeSync(join(__dirname, '../../../../.tmp'));
  ensureDirSync(join(__dirname, '../../../../.tmp'));
}
示例#30
0
			Cloudbook.Actions[component].metadata.external_css.forEach(function(element){
					var orig = path.join(Cloudbook.Actions[component].path,element);
					var dest = path.join(destpath,'css',element);
					fsextra.ensureDirSync(path.dirname(dest));
					fsextra.copySync(orig,dest);
				}