fs-extra#mkdirSync TypeScript Examples

The following examples show how to use fs-extra#mkdirSync. 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: utils.ts    From cli with Apache License 2.0 7 votes vote down vote up
export async function startVerdaccio() {
  mkdirSync(
    resolve(join(__dirname, '..', 'verdaccio', 'verdaccio', 'storage')),
    {
      recursive: true,
    }
  );
  const args = [...npm(), 'run', 'verdaccio'];
  const verdaccioTerminal = new Terminal(
    args.shift()!,
    args,
    {cwd: resolve(join(__dirname, '..')), detached: process.env.CI === 'true'},
    global.processManager!,
    'verdaccio'
  );
  await verdaccioTerminal
    .when(/localhost:4873/)
    .on('stdout')
    .do()
    .once();
  await waitOn({resources: ['tcp:4873']});
}
Example #2
Source File: utils.ts    From cli with Apache License 2.0 7 votes vote down vote up
export async function installCli() {
  const tmpDir = tmpDirSync();
  const cliDir = join(tmpDir.name, 'coveoShim');
  mkdirSync(cliDir, {recursive: true});
  const npmInitArgs = [...npm(), 'init', '-y'];
  const npmInitTerminal = new Terminal(
    npmInitArgs.shift()!,
    npmInitArgs,
    {
      cwd: cliDir,
    },
    global.processManager!,
    'cli-install-init'
  );
  await npmInitTerminal.when('exit').on('process').do().once();
  const npmInstallArgs = [...npm(), 'install', '@coveo/cli'];
  const npmInstallTerminal = new Terminal(
    npmInstallArgs.shift()!,
    npmInstallArgs,
    {
      cwd: cliDir,
    },
    global.processManager!,
    'cli-install-init'
  );
  await npmInstallTerminal.when('exit').on('process').do().once();
  process.env.CLI_EXEC_PATH = resolve(
    cliDir,
    'node_modules',
    '@coveo',
    'cli',
    'bin',
    'run'
  );
}
Example #3
Source File: AttachmentsFilesService.ts    From node-experience with MIT License 6 votes vote down vote up
static async  getTempFilesAttachments(emailNotification: EmailNotification): Promise<IFilesAttachments[]>
    {
        const filesystem = FilesystemFactory.create();

        emailNotification.tempFilesAttachments =  await Promise.all(emailNotification.attachedFiles.map(async(_file) =>
        {
            const stream = await filesystem.downloadStreamFile(_file);
            const fileName = `${_file.originalName}.${_file.extension}`;
            const uqFileName = `${_file.name}.${_file.extension}`;
            const tempDir = PATH.join(`${__dirname}/../../../temp`);
            const dirName = PATH.join(`${tempDir}/${uqFileName}`);
            // eslint-disable-next-line no-unused-expressions
            !existsSync(tempDir) && mkdirSync(tempDir);
            void await writeFile(dirName, '01011');
            const ws = createWriteStream(dirName);
            stream.pipe(ws);

            return {
                filename: fileName,
                path:dirName
            };
        }));

        return emailNotification.tempFilesAttachments;
    }
Example #4
Source File: utils.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function restoreCliConfig() {
  mkdirSync(dirname(getConfigFilePath()), {recursive: true});
  copyFileSync('decrypted', getConfigFilePath());
}
Example #5
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 #6
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 #7
Source File: filelogger.ts    From cli with Apache License 2.0 5 votes vote down vote up
public constructor(name: string) {
    const dir = join(LOGS_PATH, name);
    mkdirSync(dir, {recursive: true});
    this.stdout = createWriteStream(join(dir, 'stdout'));
    this.stderr = createWriteStream(join(dir, 'stderr'));
  }
Example #8
Source File: index.ts    From cli with MIT License 4 votes vote down vote up
hooks = {
    'package:generateSpec': async () => {
      this.core.cli.log('Generate spec file...');
      await generateFunctionsSpecFile(
        this.getSpecJson(),
        join(this.midwayBuildPath, 'template.yml')
      );
    },
    'package:generateEntry': async () => {
      this.core.cli.log('Generate entry file...');
      const { version } = findMidwayVersion(this.servicePath);
      this.setGlobalDependencies(
        '@midwayjs/serverless-fc-starter',
        version.major || '*'
      );
      const preloadFile = this.getStore('preloadFile', 'global');

      writeWrapper({
        baseDir: this.servicePath,
        service: this.core.service,
        distDir: this.midwayBuildPath,
        starter: '@midwayjs/serverless-fc-starter',
        preloadFile,
      });
    },
    'deploy:deploy': async () => {
      if (!this.options.useFun) {
        return this.deployUseServerlessDev();
      }

      let AliyunDeploy;
      try {
        AliyunDeploy = require('@alicloud/fun/lib/commands/deploy');
      } catch {
        console.error(
          '阿里云 FC 发布默认使用 @serverless/devs,若要继续使用 funcraft 发布,请手动安装 @alicloud/fun 依赖'
        );
        throw new Error('-- 请手动安装 @alicloud/fun 依赖 --');
      }

      const profPath = join(homedir(), '.fcli/config.yaml');
      const isExists = existsSync(profPath);
      if (!isExists || this.options.resetConfig) {
        // aliyun config
        if (
          process.env.SERVERLESS_DEPLOY_ID &&
          process.env.SERVERLESS_DEPLOY_AK &&
          process.env.SERVERLESS_DEPLOY_SECRET
        ) {
          // for ci
          const profDir = join(homedir(), '.fcli');
          if (!existsSync(profDir)) {
            mkdirSync(profDir);
          }
          const endPoint =
            process.env.SERVERLESS_DEPLOY_ENDPOINT || 'cn-hangzhou';
          const config = [
            `endpoint: 'https://${process.env.SERVERLESS_DEPLOY_ID}.${endPoint}.fc.aliyuncs.com'`,
            "api_version: '2016-08-15'",
            `access_key_id: ${process.env.SERVERLESS_DEPLOY_AK}`,
            `access_key_secret: ${process.env.SERVERLESS_DEPLOY_SECRET}`,
            "security_token: ''",
            'debug: false',
            `timeout: ${process.env.SERVERLESS_DEPLOY_TIMEOUT || 1000}`,
            'retries: 3',
            `sls_endpoint: ${endPoint}.log.aliyuncs.com`,
            'report: true',
            'enable_custom_endpoint: false',
          ].join('\n');
          writeFileSync(profPath, config);
        } else {
          this.core.cli.log('please input aliyun config');
          const AliyunConfig = require('@alicloud/fun/lib/commands/config');
          await AliyunConfig();
        }
      }

      // 执行 package 打包
      await this.core.invoke(['package'], true, {
        ...this.options,
        skipZip: true, // 跳过压缩成zip
      });
      this.core.cli.log('Start deploy by @alicloud/fun');
      try {
        if (!this.options.skipDeploy) {
          await AliyunDeploy({
            template: join(this.midwayBuildPath, 'template.yml'),
            assumeYes: this.options.yes,
          });
        }
        this.core.cli.log('Deploy success');
      } catch (e) {
        this.core.cli.log(`Deploy error: ${e.message}`);
      }
    },
  };