fs-extra#writeFileSync TypeScript Examples

The following examples show how to use fs-extra#writeFileSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: build.ts    From malagu with MIT License 6 votes vote down vote up
async function renderEntry(entryTemplate: string, cfg: ApplicationConfig, entry: string) {
    ensureDir(PathUtil.getProjectHomePath());
    const server = ConfigUtil.getBackendMalaguConfig(cfg).server;
    const port = server?.port ?? 9000;
    let path = server?.path ?? '';
    let entryContent = readFileSync(entryTemplate, { encoding: 'utf8' });
    entry = entry.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    path = path.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    entryContent = entryContent
        .replace(/{{ entry }}/g, entry)
        .replace(/{{ port }}/g, port)
        .replace(/{{ path }}/g, path);
    await ensureDir(PathUtil.getBackendProjectDistPath());
    const newEntry = join(PathUtil.getBackendProjectDistPath(), 'gen-entry.js');
    writeFileSync(newEntry, entryContent, { encoding: 'utf8' });
    return newEntry;

}
Example #2
Source File: index.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export function updateFile(
  f: string,
  content: string | ((content: string) => string),
): void {
  ensureDirSync(path.dirname(tmpProjPath(f)));
  if (typeof content === 'string') {
    writeFileSync(tmpProjPath(f), content);
  } else {
    writeFileSync(
      tmpProjPath(f),
      content(readFileSync(tmpProjPath(f)).toString()),
    );
  }
}
Example #3
Source File: utils.test.ts    From cli with MIT License 6 votes vote down vote up
describe('faas-code-analysis:/test/utils.test.ts', () => {
  it('formatUpperCamel', async () => {
    const camel = formatUpperCamel('ABC');
    assert(camel === 'a-b-c');
  });

  it('compareFileChange', async () => {
    writeFileSync(join(base, 'a.txt'), Date.now() + '');
    const fileChange = await compareFileChange(['*.txt'], ['*.data'], {
      cwd: base,
    });
    assert(fileChange[0] === 'a.txt');

    const noFrom = await compareFileChange(['*.zip'], ['*.data'], {
      cwd: base,
    });
    assert(noFrom.length === 0);

    const noTo = await compareFileChange(['*.txt'], ['*.zip'], {
      cwd: base,
    });
    assert(noTo.length === 1);
    assert(noTo[0] === 'a.txt');

    writeFileSync(join(base, 'b.data'), Date.now() + '');
    const fileChange2 = await compareFileChange(['*.txt'], ['*.data'], {
      cwd: base,
    });
    assert(fileChange2.length === 0);
  });

  it('copyStaticFiles', async () => {
    await copyStaticFiles({ sourceDir: null, targetDir: null, log: null });
    const target = join(__dirname, 'tmpCopyFileDir');
    if (existsSync(target)) {
      await remove(target);
    }
    mkdirSync(target);
    await copyStaticFiles({
      sourceDir: base,
      targetDir: target,
      log: () => {},
    });
    assert(existsSync(join(target, 'a.txt')));
    assert(existsSync(join(target, 'b.data')));
    assert(!existsSync(join(target, 'c.ts')));

    await copyStaticFiles({
      sourceDir: base,
      targetDir: target,
      log: () => {},
    });
    await remove(target);
  });
});
Example #4
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
// 安装npm到构建文件夹
  private async npmInstall(
    options: {
      npmList?: string[];
      baseDir?: string;
      production?: boolean;
    } = {}
  ) {
    return new Promise((resolve, reject) => {
      const installDirectory = options.baseDir || this.midwayBuildPath;
      const pkgJson: string = join(installDirectory, 'package.json');
      if (!existsSync(pkgJson)) {
        writeFileSync(pkgJson, '{}');
      }
      installNpm({
        baseDir: installDirectory,
        moduleName: options.npmList ? `${options.npmList.join(' ')}` : '',
        mode: options.production ? ['production'] : [],
        register: this.getNPMClient(),
        registerPath: this.options.registry,
        slience: true,
        debugLog: this.core.debug,
      })
        .then(resolve)
        .catch(err => {
          const errmsg = (err && err.message) || err;
          this.core.cli.log(` - npm install err ${errmsg}`);
          reject(errmsg);
        });
    });
  }
Example #5
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
async preload() {
    if (this.midwayVersion !== '3' || !this.options.bundle) {
      return;
    }

    let preloadCode = '';
    const distDir = join(this.midwayBuildPath, 'dist');
    const preloadFile = join(distDir, '_midway_preload_modules.js');
    const requireList = await globby(['**/*.js'], {
      cwd: distDir,
    });
    preloadCode += [
      'exports.modules = [',
      ...requireList.map(file => {
        return `  require('./${file}'),`;
      }),
      '];',
    ].join('\n');
    const configurationFilePath = join(distDir, 'configuration.js');
    if (existsSync(configurationFilePath)) {
      preloadCode += "exports.configuration = require('./configuration.js');";
    }
    this.setStore(
      'preloadFile',
      relative(this.midwayBuildPath, preloadFile),
      true
    );
    writeFileSync(preloadFile, preloadCode);
  }
Example #6
Source File: utils.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Create config file if it doesn't exist
   */
  static genConfigFile({
    podsDir,
    podClass,
    force,
  }: {
    podsDir: string;
    podClass: PodClassEntryV4;
    force?: boolean;
  }) {
    const podConfigPath = PodUtils.getConfigPath({ podsDir, podClass });
    ensureDirSync(path.dirname(podConfigPath));
    // eslint-disable-next-line new-cap
    const pod = new podClass();
    const required = pod.config.required;
    const podConfig = pod.config.properties;
    const config = Object.keys(podConfig)
      .map((ent: any) => {
        podConfig[ent] = _.defaults(podConfig[ent], { default: "TODO" });
        const args = [
          `# description: ${podConfig[ent].description}`,
          `# type: ${podConfig[ent].type}`,
        ];
        let configPrefix = "# ";
        if (required.includes(`${ent}`)) {
          args.push(`# required: true`);
          configPrefix = "";
        }
        args.push(`${configPrefix}${ent}: ${podConfig[ent].default}`);
        return args.join("\n");
      })
      .join("\n\n");

    if (!fs.existsSync(podConfigPath) || force) {
      writeFileSync(podConfigPath, config);
    }
    return podConfigPath;
  }
Example #7
Source File: ConfigFileUtils.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
   * Create config file if it doesn't exist
   */
  static genConfigFileV2<T>({
    fPath,
    configSchema,
    force,
    setProperties,
  }: {
    fPath: string;
    configSchema: any;
    force?: boolean;
    setProperties?: Partial<T>;
  }) {
    ensureDirSync(path.dirname(fPath));
    const required = configSchema.required;
    const podConfig = configSchema.properties;
    const config = Object.keys(podConfig)
      .map((ent: any) => {
        podConfig[ent] = _.defaults(podConfig[ent], { default: "TODO" });
        const args = [
          `# description: ${podConfig[ent].description}`,
          `# type: ${podConfig[ent].type}`,
        ];
        let configPrefix = "# ";
        if (required.includes(`${ent}`)) {
          args.push(`# required: true`);
          configPrefix = "";
        }

        // If a pre-set value for an optional param has been passed in, then keep it.
        if (setProperties && ent in setProperties) {
          configPrefix = "";
        }

        /**
         * add NOTE for config options having note property. Mark the option as a comment.
         * added for exportScope config option
         */
        if (podConfig[ent].note) {
          args.push(`# NOTE: ${podConfig[ent].note}`);
          configPrefix = "# ";
        }
        args.push(
          `${configPrefix}${ent}: ${
            setProperties && ent in setProperties
              ? setProperties[ent as keyof T]
              : podConfig[ent].default
          }`
        );
        return args.join("\n");
      })
      .join("\n\n");

    const fileExists = fs.existsSync(fPath);
    if (!fileExists || force) {
      writeFileSync(fPath, config);
    } else if (fileExists && !force) {
      throw new Error("Config already exists!");
    }
    return fPath;
  }
Example #8
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async bundle() {
    if (!this.options.bundle) {
      return;
    }
    const nccPkgJsonFile = require.resolve('@vercel/ncc/package');
    const nccPkgJson = JSON.parse(readFileSync(nccPkgJsonFile).toString());
    const nccCli = join(nccPkgJsonFile, '../', nccPkgJson.bin.ncc);
    const outDir = join(this.core.cwd, this.getOutDir());

    let preloadCode = '// midway bundle';
    const preloadFile = 'midway_bundle_entry.js';
    const requireList = await globby(['**/*.js'], {
      cwd: outDir,
    });

    preloadCode += requireList
      .map((file, index) => {
        return `require('./${file}');`;
      })
      .join('\n');

    const configurationFilePath = join(outDir, 'configuration.js');
    if (existsSync(configurationFilePath)) {
      preloadCode += `
      const configuration = require('./configuration.js');
      if (typeof configuration === 'object') {
        const configurationKey = Object.keys(configuration).find(key => typeof configuration[key] === 'function');
        if (configurationKey) {
          exports.configuration = configuration[configurationKey];
        }
      } else {
        exports.configuration = configuration;
      }
      `;
    }
    writeFileSync(join(outDir, preloadFile), preloadCode);

    this.core.cli.log('Build bundle...');
    await forkNode(
      nccCli,
      ['build', preloadFile, '-o', 'ncc_build_tmp', '-m'],
      {
        cwd: outDir,
      }
    );
    const tmpFile = join(tmpdir(), `midway_bundle_${Date.now()}.js`);
    await move(join(outDir, 'ncc_build_tmp/index.js'), tmpFile);
    await remove(outDir);
    await move(tmpFile, join(outDir, 'bundle.js'));
    await remove(tmpFile);
    this.core.cli.log(
      `Success compile to ${relative(
        process.cwd(),
        join(outDir, 'bundle.js')
      )}.`
    );
    this.core.cli.log(
      'You can use it through the configurationModule parameter in the bootstrap file.'
    );
  }
Example #9
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
// generate version.json to midwayBuildPath
  async generateVercelJson() {
    const funcList = this.getFunctionList();

    let vercelJson: any = {};
    if (existsSync(this.vercelJsonFile)) {
      vercelJson = JSON.parse(readFileSync(this.vercelJsonFile).toString());
    }

    const userDefinedEnv = filterUserDefinedEnv();
    if (!vercelJson.env) {
      vercelJson.env = {};
    }
    Object.assign(vercelJson.env, userDefinedEnv);

    if (!vercelJson.functions) {
      vercelJson.functions = {};
    }
    if (!vercelJson.functions) {
      vercelJson.functions = {};
    }

    if (!vercelJson.routes) {
      vercelJson.routes = [];
    }

    for (const func of funcList) {
      const { funcInfo, entryFileName } = func;
      if (!vercelJson.functions[entryFileName]) {
        vercelJson.functions[entryFileName] = {
          memory:
            funcInfo.memorySize ||
            this.core.service?.provider?.memorySize ||
            128, // 0 - 1024, step 64
          maxDuration:
            funcInfo.timeout || this.core.service?.provider?.timeout || 10, // 0 - 10
        };
      }

      if (!funcInfo.events || !Array.isArray(funcInfo.events)) {
        continue;
      }

      for (const event of funcInfo.events) {
        const trigger = event?.http;
        if (!trigger) {
          continue;
        }

        // * to 正则表达式
        const path = (trigger.path || '/*').replace(/\*/g, '.*');
        vercelJson.routes.push({
          src: path,
          dest: entryFileName,
          methods: convertMethods(trigger.method),
        });
      }
    }

    writeFileSync(this.vercelJsonFile, JSON.stringify(vercelJson, null, 2));
  }
Example #10
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
// vercel deploy
  async vercelDeploy() {
    // 执行 package 打包
    await this.core.invoke(['package'], true, {
      ...this.options,
      skipZip: true, // 跳过压缩成zip
      skipInstallDep: true,
    });

    await this.safeRemoveUselessFile();

    // 清理 package.json
    const pkgJsonFile = join(this.midwayBuildPath, 'package.json');
    if (existsSync(pkgJsonFile)) {
      const pkgJson = JSON.parse(readFileSync(pkgJsonFile).toString());
      delete pkgJson.devDependencies;
      writeFileSync(pkgJsonFile, JSON.stringify(pkgJson, null, 2));
    }

    this.core.cli.log('Start deploy by vercel/cli');
    try {
      const vercelPkg = require.resolve('vercel/package.json');
      const vercelPkgJson = JSON.parse(readFileSync(vercelPkg).toString());
      const vercelBin = join(dirname(vercelPkg), vercelPkgJson.bin.vercel);

      const args = [`--local-config=${this.vercelJsonFile}`];
      const token = this.options.token || process.env.VERCEL_TOKEN;
      if (token) {
        args.push(`--token=${token}`);
      }
      this.core.debug('Vercel Bin', vercelBin);
      this.core.debug('Vercel Deploy Args', args);
      await forkNode(`${vercelBin}`, args, {
        cwd: this.midwayBuildPath,
      });
      this.core.cli.log('Deploy success');
    } catch (e) {
      this.core.cli.log(`Deploy error: ${e.message}`);
    }
  }
Example #11
Source File: file.ts    From cli with Apache License 2.0 5 votes vote down vote up
export function overwriteEnvFile(projectPath: string, data: string) {
  const envPath = join(projectPath, '.env');
  writeFileSync(envPath, data);
}
Example #12
Source File: create-fixture.ts    From dt-mergebot with MIT License 5 votes vote down vote up
export default async function main(directory: string, overwriteInfo: boolean) {
    const writeJsonSync = (file: string, json: unknown) =>
        writeFileSync(file, scrubDiagnosticDetails(JSON.stringify(json, undefined, 2) + "\n"));

    const fixturePath = join("src", "_tests", "fixtures", directory);
    const prNumber = parseInt(directory, 10);
    if (isNaN(prNumber)) throw new Error(`Expected ${directory} to be parseable as a PR number`);

    if (!existsSync(fixturePath)) mkdirSync(fixturePath);

    const jsonFixturePath = join(fixturePath, "_response.json");
    if (overwriteInfo || !existsSync(jsonFixturePath)) {
        writeJsonSync(jsonFixturePath, await getPRInfo(prNumber));
    }
    const response: ApolloQueryResult<PR> = readJsonSync(jsonFixturePath);

    const filesJSONPath = join(fixturePath, "_files.json");
    const filesFetched: {[expr: string]: string | undefined} = {};
    const downloadsJSONPath = join(fixturePath, "_downloads.json");
    const downloadsFetched: {[packageName: string]: number} = {};
    const derivedFixturePath = join(fixturePath, "derived.json");

    const shouldOverwrite = (file: string) => overwriteInfo || !existsSync(file);

    const prInfo = response.data.repository?.pullRequest;
    if (!prInfo) {
        console.error(`Could not get PR info for ${directory}, is the number correct?`);
        return;
    }

    const derivedInfo = await deriveStateForPR(
        prInfo,
        shouldOverwrite(filesJSONPath) ? initFetchFilesAndWriteToFile() : getFilesFromFile,
        shouldOverwrite(downloadsJSONPath) ? initGetDownloadsAndWriteToFile() : getDownloadsFromFile,
        shouldOverwrite(derivedFixturePath) ? undefined : getTimeFromFile(),
    );

    writeJsonSync(derivedFixturePath, derivedInfo);

    const resultFixturePath = join(fixturePath, "result.json");
    const actions = computeActions.process(derivedInfo);
    writeJsonSync(resultFixturePath, actions);

    const mutationsFixturePath = join(fixturePath, "mutations.json");
    const mutations = await executePrActions(actions, prInfo, /*dry*/ true);
    writeJsonSync(mutationsFixturePath, mutations);

    console.log("Recorded");

    function initFetchFilesAndWriteToFile() {
        writeJsonSync(filesJSONPath, {}); // one-time initialization of an empty storage
        return fetchFilesAndWriteToFile;
    }
    async function fetchFilesAndWriteToFile(expr: string, limit?: number) {
        filesFetched[expr] = await fetchFile(expr, limit);
        writeJsonSync(filesJSONPath, filesFetched);
        return filesFetched[expr];
    }
    function getFilesFromFile(expr: string) {
        return readJsonSync(filesJSONPath)[expr];
    }

    function initGetDownloadsAndWriteToFile() {
        writeJsonSync(downloadsJSONPath, {}); // one-time initialization of an empty storage
        return getDownloadsAndWriteToFile;
    }
    async function getDownloadsAndWriteToFile(packageName: string, until?: Date) {
        const downloads = await getMonthlyDownloadCount(packageName, until);
        downloadsFetched[packageName] = downloads;
        writeJsonSync(downloadsJSONPath, downloadsFetched);
        return downloads;
    }
    function getDownloadsFromFile(packageName: string) {
        return readJsonSync(downloadsJSONPath)[packageName];
    }

    function getTimeFromFile() {
        return new Date(readJsonSync(derivedFixturePath).now);
    }
}
Example #13
Source File: index.test.ts    From cli with MIT License 4 votes vote down vote up
describe('/test/index.test.ts', () => {
  it('use custom artifact directory', async () => {
    const baseDir = join(__dirname, './fixtures/base-fc');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package']);
    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'dist/index.js')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'src')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'tsconfig.json')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    const zip = new JSZip();
    const zipData = await readFile(join(baseDir, 'serverless.zip'));
    const zipObj = await zip.loadAsync(zipData);
    assert(zipObj.file('f.yml'));
    assert(zipObj.file('dist/index.js'));
    assert(zipObj.file('node_modules/@midwayjs/core/package.json'));
    // clean
    await remove(join(baseDir, 'serverless.zip'));
  });

  it('use custom artifact directory', async () => {
    if (process.version.includes('v10')) {
      return;
    }
    const baseDir = join(__dirname, './fixtures/base-fc');
    process.env.SERVERLESS_DEPLOY_ID = 'test';
    process.env.SERVERLESS_DEPLOY_AK = 'test';
    process.env.SERVERLESS_DEPLOY_SECRET = 'test';
    const logs = [];
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      options: {
        skipDeploy: true,
        skipInstallDep: true,
      },
      commands: ['deploy'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: {
        log: (...args) => {
          logs.push(...args);
        },
      },
    });
    core.addPlugin(DeployPlugin);
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['deploy']);
    const logStr = logs.join('\n');
    assert(logStr.includes('success'));
    // clean
    await remove(join(baseDir, '.serverless'));
  });

  it('only build index2', async () => {
    const baseDir = join(__dirname, './fixtures/base-fc');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package'], false, { function: 'index2' });
    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'dist/index.js')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'src')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'tsconfig.json')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    const entryData = readFileSync(join(buildPath, 'index.js')).toString();
    assert(!entryData.includes('exports.handler '));
    assert(entryData.includes('exports.handler2 '));

    const zip = new JSZip();
    const zipData = await readFile(join(baseDir, 'serverless.zip'));
    const zipObj = await zip.loadAsync(zipData);
    assert(zipObj.file('f.yml'));
    assert(zipObj.file('dist/index.js'));
    assert(zipObj.file('node_modules/@midwayjs/core/package.json'));
    // clean
    await remove(join(baseDir, 'serverless.zip'));
  });

  it('build eaas function', async () => {
    const baseDir = join(__dirname, './fixtures/eaas');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package']);

    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'app')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'config')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'app.js')));
    assert(existsSync(join(buildPath, 'agent.js')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    // clean
    await remove(join(baseDir, '.serverless'));
  });
  it('build by serverless-dev', async () => {
    if (process.version.includes('v10')) {
      return;
    }
    const accessYaml = join(homedir(), '.s/access.yaml');
    const exists = existsSync(accessYaml);
    if (!exists) {
      ensureFileSync(accessYaml);
      writeFileSync(accessYaml, '');
    }

    const baseDir = join(__dirname, './fixtures/serverless-devs');
    const logs = [];
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['deploy'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: {
        ...console,
        log: (...logInfo) => {
          logs.push(...logInfo);
        },
      },
      options: {
        skipDeploy: true,
        skipInstallDep: true,
      },
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(DeployPlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['deploy']);
    // clean
    await remove(join(baseDir, '.serverless'));
    const logsStr = logs.join(';');
    assert(logsStr.includes('@serverless-devs'));
    assert(logsStr.includes('deploy success'));
    if (!exists) {
      await remove(accessYaml);
    }
  });
});
Example #14
Source File: index.ts    From cli with MIT License 4 votes vote down vote up
async installDep() {
    this.core.cli.log('Install production dependencies...');

    if (+this.midwayVersion >= 2) {
      const { version } = findMidwayVersion(this.servicePath);
      this.setGlobalDependencies('@midwayjs/bootstrap', version.major || '*');
      this.setGlobalDependencies('path-to-regexp');
    } else {
      this.setGlobalDependencies('picomatch');
    }
    // globalDependencies
    // pkg.json dependencies
    const pkgJsonPath: string = join(this.midwayBuildPath, 'package.json');
    let pkgJson: any = {};
    try {
      pkgJson = JSON.parse(readFileSync(pkgJsonPath).toString());
    } catch (e) {
      /** ignore */
    }
    const allDependencies = Object.assign(
      {},
      this.core.service.globalDependencies,
      pkgJson.dependencies
    );
    if (this.core.service.coverDependencies) {
      Object.keys(this.core.service.coverDependencies).forEach(depName => {
        if (!allDependencies[depName]) {
          return;
        }
        const coverDepValue = this.core.service.coverDependencies[depName];
        if (coverDepValue === false) {
          delete allDependencies[depName];
        } else {
          allDependencies[depName] = coverDepValue;
        }
      });
    }
    pkgJson.dependencies = {};
    for (const depName in allDependencies) {
      const depVersion = allDependencies[depName];
      pkgJson.dependencies[depName] = depVersion;
    }
    pkgJson.resolutions = Object.assign(
      {},
      pkgJson.resolutions,
      this.core.service.resolutions
    );

    // 避免因为在 devDeps 里面和 deps 都写了,导致有些npm 客户端忽略安装
    if (pkgJson.devDependencies) {
      Object.keys(pkgJson.devDependencies).forEach(devDep => {
        if (pkgJson.dependencies[devDep]) {
          delete pkgJson.devDependencies[devDep];
        }
      });
    }

    writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2));

    if (this.options.skipInstallDep) {
      this.core.cli.log(' - Production dependencies install skip');
      return;
    }

    let skipNpmInstall = false;
    if (this.core.service?.experimentalFeatures?.fastInstallNodeModules) {
      this.core.debug('Fast Install Node Modules');
      const moduleInfoList = Object.keys(pkgJson.dependencies).map(name => {
        return {
          name,
          version: pkgJson.dependencies[name],
        };
      });
      const start = Date.now();
      const copyResult = await copyFromNodeModules(
        moduleInfoList,
        join(this.getCwd(), 'node_modules'),
        join(this.midwayBuildPath, 'node_modules')
      );
      skipNpmInstall = !!copyResult;
      this.core.debug('skipNpmInstall', skipNpmInstall, Date.now() - start);
    }

    if (!skipNpmInstall) {
      await this.npmInstall({
        production: true,
      });
    }
    // not await
    this.biggestDep();
    this.core.cli.log(' - Dependencies install complete');
  }
Example #15
Source File: segmentClient.spec.ts    From dendron with GNU Affero General Public License v3.0 4 votes vote down vote up
describe("SegmentClient", () => {
  let mockHomeDirStub: sinon.SinonStub;

  beforeEach(() => {
    mockHomeDirStub = TestEngineUtils.mockHomeDir();
  });
  afterEach(() => {
    mockHomeDirStub.restore();
    sinon.restore();
  });

  test("enabled by default", (done) => {
    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    done();
  });

  test("enabled by command", (done) => {
    SegmentClient.enable(TelemetryStatus.ENABLED_BY_COMMAND);

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    done();
  });

  test("enabled by config", (done) => {
    SegmentClient.enable(TelemetryStatus.ENABLED_BY_CONFIG);

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    done();
  });

  test("disabled by command", (done) => {
    SegmentClient.disable(TelemetryStatus.DISABLED_BY_COMMAND);

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    done();
  });

  test("disabled by vscode config", (done) => {
    SegmentClient.disable(TelemetryStatus.DISABLED_BY_VSCODE_CONFIG);

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    done();
  });

  test("disabled by workspace config", (done) => {
    SegmentClient.disable(TelemetryStatus.DISABLED_BY_WS_CONFIG);

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    done();
  });

  test("still recognizes legacy disable", (done) => {
    const disablePath = SegmentClient.getDisableConfigPath();
    writeFileSync(disablePath, "");

    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    done();
  });

  test("enable command overrides legacy disable", (done) => {
    const disablePath = SegmentClient.getDisableConfigPath();
    writeFileSync(disablePath, "");

    SegmentClient.enable(TelemetryStatus.ENABLED_BY_COMMAND);
    const instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    done();
  });

  test("disabled then enabled with command", (done) => {
    SegmentClient.disable(TelemetryStatus.DISABLED_BY_COMMAND);

    let instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    SegmentClient.enable(TelemetryStatus.ENABLED_BY_COMMAND);

    instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    done();
  });

  test("enabled then disabled with command", (done) => {
    SegmentClient.enable(TelemetryStatus.ENABLED_BY_COMMAND);

    let instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(false);

    SegmentClient.disable(TelemetryStatus.DISABLED_BY_COMMAND);

    instance = SegmentClient.instance({ forceNew: true });
    expect(instance.hasOptedOut).toEqual(true);

    done();
  });

  describe("WHEN: Enabled by CLI command", () => {
    test("THEN: recognized as enabled", (done) => {
      SegmentClient.enable(TelemetryStatus.ENABLED_BY_CLI_COMMAND);
      const instance = SegmentClient.instance({ forceNew: true });
      expect(instance.hasOptedOut).toBeFalsy();
      done();
    });
  });

  describe("WHEN: Disabled by CLI command", () => {
    test("THEN: recognized as disabled", (done) => {
      SegmentClient.disable(TelemetryStatus.DISABLED_BY_CLI_COMMAND);
      const instance = SegmentClient.instance({ forceNew: true });
      expect(instance.hasOptedOut).toBeTruthy();
      done();
    });
  });

  describe("WHEN: Enabled by CLI as default", () => {
    test("THEN: recognized as enabled", (done) => {
      SegmentClient.enable(TelemetryStatus.ENABLED_BY_CLI_DEFAULT);
      const instance = SegmentClient.instance({ forceNew: true });
      expect(instance.hasOptedOut).toBeFalsy();
      done();
    });
  });
});
Example #16
Source File: index.ts    From cli with MIT License 4 votes vote down vote up
hooks = {
    'before:package:cleanup': async () => {
      // 跳过zip打包
      this.options.skipZip = true;
      this.options.skipInstallDep = true;
      if (!this.core.service.package) {
        this.core.service.package = {};
      }
      this.core.service.package.include = (
        this.core.service?.package?.include || []
      ).concat(['config.json', 'sitemap.json']);
    },
    'package:generateEntry': async () => {
      this.core.cli.log('Generate entry file...');
      this.setGlobalDependencies('@midwayjs/serverless-scf-starter');
      writeWrapper({
        baseDir: this.servicePath,
        service: this.core.service,
        distDir: this.midwayBuildPath,
        starter: '@midwayjs/serverless-scf-starter',
      });
    },
    'package:package': async () => {
      // 拷贝到 cloudfunctions 目录
      let projectPkgJson: any = {};
      try {
        const json: string = readFileSync(
          join(this.servicePath, 'package.json')
        ).toString();
        projectPkgJson = JSON.parse(json);
      } catch {
        // ignore
      }
      const functions = this.core.service.functions || {};
      if (existsSync(this.wechatFunctionBuildPath)) {
        this.core.cli.log('Clear old cloud functions directory');
        await remove(this.wechatFunctionBuildPath);
      }
      await ensureDir(this.wechatFunctionBuildPath);
      for (const func in functions) {
        const handlerConf = functions[func];
        const [originFileName, handlerName] = handlerConf.handler.split('.');
        const cloudFunctionName = func;
        this.core.cli.log('Create function: ' + cloudFunctionName);

        const functionDir = join(
          this.wechatFunctionBuildPath,
          cloudFunctionName
        );
        await copy(this.midwayBuildPath, functionDir);

        await this.safeRemove(join(functionDir, 'src'));
        await this.safeRemove(join(functionDir, 'f.yml'));
        await this.safeRemove(join(functionDir, 'f.origin.yml'));
        await this.safeRemove(join(functionDir, 'tsconfig.json'));
        await this.safeRemove(join(functionDir, 'dist/midway.build.json'));
        await this.safeRemove(join(functionDir, 'dist/.mwcc-cache'));

        if (originFileName !== 'index') {
          const main = 'index.js';
          const originFile = originFileName + '.js';
          writeFileSync(
            join(functionDir, main),
            `exports.main = require('./${originFile}').${handlerName};`
          );
        }

        const pkgJsonFile = join(functionDir, 'package.json');
        let pkgJson: any = {};

        if (existsSync(pkgJsonFile)) {
          pkgJson = JSON.parse(readFileSync(pkgJsonFile).toString());
        }

        pkgJson.name = `${cloudFunctionName}`;
        pkgJson.version = projectPkgJson.version || '1.0.0';
        pkgJson.main = 'index.js';
        delete pkgJson.devDependencies;
        writeFileSync(pkgJsonFile, JSON.stringify(pkgJson, null, 2));
      }
    },
  };
Example #17
Source File: cli.test.ts    From cli with MIT License 4 votes vote down vote up
describe('command-core / cli.test.ts', () => {
  it('cli no command err', async () => {
    let err;
    class TestCli extends CoreBaseCLI {
      error(e) {
        err = e;
      }
    }
    try {
      const cli = new TestCli(['', '', 'nocommand']);
      await cli.start();
    } catch {
      //
    }
    assert(err.info.command === 'nocommand');
    assert(err.message === 'command nocommand not found');
  });
  it('cli help', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      async loadPlatformPlugin() {
        this.core.addPlugin(NoCommand);
        this.core.addPlugin(TestPlugin);
      }
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli(['', '', '-h']);
    await cli.start();
    const logStr = logList.join('\n');
    assert(logStr.includes('common command'));
    assert(logStr.includes('x xChild/abc'));
    assert(logStr.includes('x xChild/abc xChildChild/def'));
    assert(logStr.includes('--xn, --name'));
    assert(logStr.includes('xChild name option'));
  });
  it('cli child help', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      async loadPlatformPlugin() {
        this.core.addPlugin(NoCommand);
        this.core.addPlugin(TestPlugin);
      }
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli(['', '', 'x', 'xChild', '-h']);
    await cli.start();
    const logStr = logList.join('\n');
    assert(logStr.includes('x xChild'));
    assert(logStr.includes('--name'));
    assert(logStr.includes('super child age'));
  });
  it('cli auto load plugin success', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli(['', '', '-h', '-V']);
    const baseDir = resolve(__dirname, './fixtures/auto-plugin');
    await ensureDir(baseDir);
    const pluginName = 'test' + Math.ceil(Date.now());
    const pkjJson = resolve(baseDir, 'package.json');
    writeFileSync(
      pkjJson,
      JSON.stringify({
        'midway-cli': {
          plugins: [pluginName],
        },
      })
    );
    const nm = resolve(baseDir, 'node_modules/' + pluginName);
    await ensureDir(nm);
    writeFileSync(
      resolve(nm, 'index.js'),
      `class Test {
        constructor() {
          this.commands = { 
            ${pluginName}: {
              lifecycleEvents: ['main'],
              options: {
                mwtest123: {
                  usage: 'xxx'
                }
              }
            }
          };
        }
      };
      exports.Test = Test;`
    );
    cli.cwd = baseDir;
    await cli.start();
    await remove(nm);
    await remove(pkjJson);
    const logContext = logList.join('\n');
    assert(logContext.indexOf(pluginName) !== -1);
    assert(logContext.indexOf('mwtest123') !== -1);
  });
  it('cli auto load plugin error', async () => {
    const cli = new CoreBaseCLI(['', '', '-h']);
    const baseDir = resolve(__dirname, './fixtures/auto-plugin');
    await ensureDir(baseDir);
    const pluginName = 'test' + Math.ceil(Date.now());
    const pkjJson = resolve(baseDir, 'package.json');
    writeFileSync(
      pkjJson,
      JSON.stringify({
        'midway-cli': {
          plugins: [pluginName],
        },
      })
    );
    const nm = resolve(baseDir, 'node_modules/' + pluginName);
    await ensureDir(nm);
    writeFileSync(
      resolve(nm, 'index.js'),
      "throw new Error('plugin error 123');"
    );
    cli.cwd = baseDir;
    try {
      await cli.start();
      assert(false);
    } catch (e) {
      assert(e.message.indexOf('Auto load mw plugin error') !== -1);
      assert(e.message.indexOf('plugin error 123') !== -1);
    }
    await remove(nm);
    await remove(pkjJson);
  });
  it('cli auto load plugin not exists', async () => {
    const cli = new CoreBaseCLI(['', '', '-h']);
    const baseDir = resolve(__dirname, './fixtures/auto-plugin');
    await ensureDir(baseDir);
    const pkjJson = resolve(baseDir, 'package.json');
    writeFileSync(
      pkjJson,
      JSON.stringify({
        'midway-cli': {
          plugins: ['test'],
        },
      })
    );
    cli.cwd = baseDir;
    try {
      await cli.start();
      assert(false);
    } catch (e) {
      assert(/'test' not install/.test(e.message));
    }
    await remove(pkjJson);
  });
  it('cli auto load plugin no pacakge.json', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli(['', '', '-h', '-V']);
    const baseDir = resolve(__dirname, './fixtures/auto-plugin');
    await ensureDir(baseDir);
    const pkjJson = resolve(baseDir, 'package.json');
    if (existsSync(pkjJson)) {
      await remove(pkjJson);
    }
    cli.cwd = baseDir;
    await cli.start();
    const logContext = logList.join('\n');
    assert(logContext.indexOf('no user package.json') !== -1);
  });
  it('cli auto load plugin no auto plugins', async () => {
    const cli = new CoreBaseCLI(['', '', '-h']);
    const baseDir = resolve(__dirname, './fixtures/auto-plugin');
    await ensureDir(baseDir);
    const pkjJson = resolve(baseDir, 'package.json');
    writeFileSync(pkjJson, JSON.stringify({}));
    cli.cwd = baseDir;
    await cli.start();
    await remove(pkjJson);
  });
  it('cli argv', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      async loadPlatformPlugin() {
        this.core.addPlugin(TestPlugin);
      }
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli({ _: [], h: true });
    await cli.start();
    assert(logList.join('\n').indexOf('common command') !== -1);
  });
  it('cli load relative plugin', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli({ _: ['noLifecycleEvents'], h: true });
    cli.loadRelativePlugin(
      relative(process.cwd(), resolve(__dirname, './plugins')),
      'no-provider.ts'
    );
    await cli.start();
    assert(logList.join('\n').indexOf('noLifecycleEvents') !== -1);
  });
  it('cli load relative plugin error', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli({ _: [], h: true });
    cli.loadRelativePlugin('./', 'no-provider.ts');
    await cli.start();
    assert(logList.join('\n').indexOf('noLifecycleEvents') === -1);
  });
  it('cli verbose', async () => {
    const logList = [];
    class TestCli extends CoreBaseCLI {
      loadLog() {
        const log = super.loadLog();
        log.log = (...args) => {
          logList.push(...args);
        };
        return log;
      }
    }
    const cli = new TestCli({ _: ['common'], h: true, V: true });
    cli.loadRelativePlugin(
      relative(process.cwd(), resolve(__dirname, './plugins')),
      'no-provider.ts'
    );
    await cli.start();
    assert(logList.join('\n').indexOf('[Verbose]') !== -1);
  });

  it('cli error', async () => {
    const originExit = process.exit;
    let exitCode;
    process.exit = (code => {
      exitCode = code;
    }) as any;
    class TestCli extends CoreBaseCLI {
      async loadPlatformPlugin() {
        this.core.addPlugin(TestPlugin);
      }
    }
    try {
      const cli = new TestCli({ _: ['common'] });
      await cli.start();
    } catch {
      //
    }
    process.exit = originExit;
    assert(exitCode === 1);
  });
});