fs-extra#ensureFileSync TypeScript Examples

The following examples show how to use fs-extra#ensureFileSync. 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: snapshot.ts    From cli with Apache License 2.0 6 votes vote down vote up
public saveDetailedReport(projectPath: string) {
    const pathToReport = join(
      projectPath,
      'snapshot-reports',
      `${this.latestReport.id}.json`
    );
    ensureFileSync(pathToReport);
    writeJsonSync(pathToReport, this.latestReport, {spaces: 2});
    return pathToReport;
  }
Example #2
Source File: file.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function saveToEnvFile(
  pathToEnv: string,
  additionalEnvironment: Record<string, unknown>
) {
  ensureFileSync(pathToEnv);
  const environment = parse(readFileSync(pathToEnv, {encoding: 'utf-8'}));

  const updatedEnvironment = {
    ...environment,
    ...additionalEnvironment,
  };

  truncateSync(pathToEnv);
  for (const [key, value] of Object.entries(updatedEnvironment)) {
    appendFileSync(pathToEnv, `${key}=${value}${EOL}`);
  }
}
Example #3
Source File: express.adapter.ts    From nx-plugins with MIT License 5 votes vote down vote up
deploy(
    context: BuilderContext,
    cwd: string,
    options: NxDeployItDeployBuilderSchema,
    configuration: string,
    targetOptions: any
  ): Observable<BuilderOutput> {
    const distributationPath = getDistributionPath(context);

    const project = getProjectConfig(context);
    const infrastructureFolder = resolve(
      context.workspaceRoot,
      project.root,
      'infrastructure'
    );

    const processCwd = process.cwd();
    process.chdir(infrastructureFolder);

    const build$: Observable<BuilderOutput> = from(
      ncc(resolve(infrastructureFolder, 'functions/main/index.ts'), {
        cache: resolve(infrastructureFolder, 'buildcache')
      })
    ).pipe(
      map(
        (buildResult: {
          code: string;
          asset: { [index: string]: { source: string } };
        }) => {
          process.chdir(processCwd);
          ensureDirSync(resolve(infrastructureFolder, 'functions/dist/main'));
          // compiled javascript
          writeFileSync(
            resolve(infrastructureFolder, 'functions/dist/main/index.js'),
            buildResult.code
          );
          // assets
          for (const file in buildResult.asset) {
            const content = buildResult.asset[file];
            ensureFileSync(
              resolve(infrastructureFolder, `functions/dist/main/${file}`)
            );
            writeFileSync(
              resolve(infrastructureFolder, `functions/dist/main/${file}`),
              content.source.toString()
            );
          }
          return { success: true };
        }
      )
    );

    return build$.pipe(
      switchMap(() =>
        this.up(
          cwd,
          options,
          configuration,
          targetOptions,
          distributationPath,
          context.target.project
        )
      )
    );
  }
Example #4
Source File: nestjs.adapter.ts    From nx-plugins with MIT License 5 votes vote down vote up
deploy(
    context: BuilderContext,
    cwd: string,
    options: NxDeployItDeployBuilderSchema,
    configuration: string,
    targetOptions: any
  ): Observable<BuilderOutput> {
    const distributationPath = getDistributionPath(context);

    const project = getProjectConfig(context);
    const infrastructureFolder = resolve(
      context.workspaceRoot,
      project.root,
      'infrastructure'
    );

    const processCwd = process.cwd();
    process.chdir(infrastructureFolder);

    const build$: Observable<BuilderOutput> = from(
      ncc(resolve(infrastructureFolder, 'functions/main/index.ts'), {
        cache: resolve(infrastructureFolder, 'buildcache')
      })
    ).pipe(
      map(
        (buildResult: {
          code: string;
          asset: { [index: string]: { source: string } };
        }) => {
          process.chdir(processCwd);
          ensureDirSync(resolve(infrastructureFolder, 'functions/dist/main'));
          // compiled javascript
          writeFileSync(
            resolve(infrastructureFolder, 'functions/dist/main/index.js'),
            buildResult.code
          );
          // assets
          for (const file in buildResult.asset) {
            const content = buildResult.asset[file];
            ensureFileSync(
              resolve(infrastructureFolder, `functions/dist/main/${file}`)
            );
            writeFileSync(
              resolve(infrastructureFolder, `functions/dist/main/${file}`),
              content.source.toString()
            );
          }
          return { success: true };
        }
      )
    );

    return build$.pipe(
      switchMap(() =>
        this.up(
          cwd,
          options,
          configuration,
          targetOptions,
          distributationPath,
          context.target.project
        )
      )
    );
  }
Example #5
Source File: snapshot.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedEnsureFileSync = jest.mocked(ensureFileSync)
Example #6
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 #7
Source File: plugin.test.ts    From cli with MIT License 4 votes vote down vote up
describe('command-core:plugin.test.ts', () => {
  it('base plugin', async () => {
    class TestPlugin extends BasePlugin {
      commands = {
        test: {
          lifecycleEvents: ['a', 'b'],
        },
      };

      hooks = {
        'before:test:a': async () => {
          this.setGlobalDependencies('@midwayjs/faas');
        },
        'test:a': async () => {
          this.setStore('a', 123);
          this.setStore('globala', 456, true);
        },
        'after:test:a': async () => {
          this.setGlobalDependencies('@midwayjs/core', '1.0.0');
        },
        'before:test:b': async () => {
          this.core.cli.log(this.core.service.globalDependencies);
        },
        'test:b': async () => {
          const data = [
            this.getStore('a'),
            this.getStore('a', 'global'),
            this.getStore('globala'),
            this.getStore('globala', 'global'),
          ];
          this.core.cli.log(data);
        },
      };
    }
    const result = [];
    const core = new CommandCore({
      commands: ['test'],
      log: {
        log: msg => {
          result.push(msg);
        },
      },
    });
    core.addPlugin(TestPlugin);
    await core.ready();
    await core.invoke();
    assert(result[0]['@midwayjs/faas'] === '*');
    assert(result[0]['@midwayjs/core'] === '1.0.0');
    assert(result[1][0] === 123);
    assert(result[1][1] === undefined);
    assert(result[1][2] === undefined);
    assert(result[1][3] === 456);
  });
  it('filterPluginByCommand', async () => {
    const result = filterPluginByCommand(
      [
        'notSupport',
        {},
        {
          mod: 'plugin1',
          command: 'test',
        },
        {
          mod: 'plugin2',
          command: 'lalala',
        },
        {
          mod: 'plugin3',
          command: ['test', 'lalala'],
        },
        {
          mod: 'plugin4',
        },
        {
          mod: 'plugin5',
          platform: 'a',
        },
        {
          mod: 'plugin6',
          platform: 'a',
        },
        {
          mod: 'plugin7',
          platform: 'a',
        },
        {
          mod: 'plugin8',
          platform: 'a',
        },
        {
          mod: 'plugin9',
          platform: 'aaaa',
        },
        {
          mod: 'plugin10',
          command: ['lalala'],
        },
      ],
      {
        command: 'test',
        platform: 'a',
        load: pluginConfigPath => {
          if (pluginConfigPath === 'plugin3/plugin.json') {
            return {
              match: {
                file: 'plugin/plugin3.json',
              },
            };
          }
          if (pluginConfigPath === 'plugin5/plugin.json') {
            return {
              match: {
                command: ['lalala'],
              },
            };
          }
          if (pluginConfigPath === 'plugin6/plugin.json') {
            return {
              match: {
                command: 'lalala',
              },
            };
          }
          if (pluginConfigPath === 'plugin7/plugin.json') {
            return {
              match: {
                command: ['test', 'lalala'],
              },
            };
          }
          if (pluginConfigPath === 'plugin8/plugin.json') {
            return {
              match: {
                command: 'test',
              },
            };
          }
        },
      }
    );
    assert(result.find(plugin => plugin.mod === 'plugin1'));
    assert(result.find(plugin => plugin.mod === 'plugin4'));
    assert(result.find(plugin => plugin.mod === 'plugin7'));
    assert(result.find(plugin => plugin.mod === 'plugin8'));

    assert(!result.find(plugin => plugin.mod === 'plugin2'));
    assert(!result.find(plugin => plugin.mod === 'plugin3'));
    assert(!result.find(plugin => plugin.mod === 'plugin5'));
    assert(!result.find(plugin => plugin.mod === 'plugin6'));
    assert(!result.find(plugin => plugin.mod === 'plugin10'));
  });

  it('getPluginClass', async () => {
    let i = 0;
    const cwd = join(__dirname, './fixtures/plugin-test');
    const nm = join(cwd, 'node_modules');
    if (existsSync(nm)) {
      await remove(nm);
    }
    const existsFile = join(nm, 'exists/index.js');
    if (!existsSync(existsFile)) {
      ensureFileSync(existsFile);
    }
    const list = await getPluginClass(
      [
        { mod: 'plugin1', name: 'test' },
        { mod: 'plugin1', name: 'test2' },
        { mod: 'plugin2' },
        { mod: 'debug' },
        { mod: 'not-npm-module' },
        { mod: 'exists' },
        { mod: 'not exists' },
      ],
      {
        cwd,
        load: name => {
          if (name === 'plugin1') {
            return {
              test: {},
            };
          } else if (name === 'plugin2') {
            return {};
          } else if (name === 'debug') {
            if (i === 0) {
              i++;
              throw new Error('xxx');
            } else {
              return {};
            }
          } else if (name === 'exists') {
            throw new Error('xxx');
          } else if (name === 'not-npm-module') {
            throw new Error('xxx');
          }
          return;
        },
      }
    );
    assert(list.length);
  });

  it('plugin command alias', async () => {
    let testAExeced = false;
    class TestPlugin extends BasePlugin {
      commands = {
        test: {
          lifecycleEvents: ['a', 'b'],
          alias: 't',
        },
      };

      hooks = {
        'test:a': async () => {
          testAExeced = true;
        },
      };
    }
    const result = [];
    const core = new CommandCore({
      commands: ['t'],
      log: {
        log: msg => {
          result.push(msg);
        },
      },
    });
    core.addPlugin(TestPlugin);
    await core.ready();
    await core.invoke();
    assert(testAExeced);
  });

  it('plugin child command alias', async () => {
    let testChildExeced = false;
    class TestPlugin extends BasePlugin {
      commands = {
        test: {
          lifecycleEvents: ['a', 'b'],
          alias: 't',
          commands: {
            child: {
              lifecycleEvents: ['c', 'd'],
              alias: 'c',
            },
          },
        },
      };

      hooks = {
        'test:child:c': async () => {
          testChildExeced = true;
        },
      };
    }
    const result = [];
    const core = new CommandCore({
      commands: ['t', 'c'],
      log: {
        log: msg => {
          result.push(msg);
        },
      },
    });
    core.addPlugin(TestPlugin);
    await core.ready();
    await core.invoke();
    assert(testChildExeced);
  });
});
Example #8
Source File: index.test.ts    From cli with MIT License 4 votes vote down vote up
describe('/test/index.test.ts', () => {
  describe('test all format', () => {
    it('test transform yml', () => {
      const result = transform(path.join(__dirname, './fixtures/fun.yml'));
      assert(result['functions']['hello']['handler'] === 'index.handler');
    });

    it('test transform yaml', () => {
      const result = transform(path.join(__dirname, './fixtures/fun.yaml'));
      assert(result['functions']['hello']['handler'] === 'index.handler');
    });

    it('test add variable for yml', () => {
      mm(process.env, 'FAAS_PROVIDER', 'fc');
      mm(process.env, 'FN_HANDLER', 'index.handler');
      mm(process.env, 'FN_HTTP_PATH', '/foo');
      mm(process.env, 'FN_HTTP_METHOD', 'get');
      const result = transform(path.join(__dirname, './fixtures/fun-var.yml'));
      assert(result['provider']['name'] === 'fc');
      assert(result['provider']['runtime'] === '${ env.NODEJS_VERSION }');
      assert(result['functions']['hello']['events'][0].http.path === '/foo');
      assert(result['functions']['hello']['events'][0].http.method === 'get');
      mm.restore();
    });
  });

  describe('test custom builder', () => {
    it('test use custom builder', () => {
      class CustomBuilder extends SpecBuilder {
        getTest() {
          return {
            test: {
              hello: 'test',
            },
          };
        }

        toJSON() {
          return {
            ...this.getTest(),
          };
        }
      }

      const result = transform(
        path.join(__dirname, './fixtures/fun.yml'),
        CustomBuilder
      );
      assert(result['test']['hello'] === 'test');
    });
  });

  describe('test generate file', () => {
    it('test generate test.yml', () => {
      generate(path.join(__dirname, './fixtures/fun.yml'), 'test.yml');
      assert(fs.existsSync(path.join(__dirname, './fixtures/test.yml')));
      fs.unlinkSync(path.join(__dirname, './fixtures/test.yml'));
    });
  });

  describe('export function', () => {
    it('filterUserDefinedEnv', () => {
      mm(process.env, 'UDEV_NODE_ENV', 'prod');
      const env = filterUserDefinedEnv();
      assert(env['NODE_ENV'] === 'prod');
      mm.restore();
    });
    it('loadSpec', () => {
      const spec = loadSpec(path.join(__dirname, './fixtures/yaml-test'));
      assert(spec.name === 'test');
    });
    it('no spec', () => {
      const spec = loadSpec(path.join(__dirname, './fixtures/not-exists-dir'));
      assert(Object.keys(spec).length === 0);
    });
    it('writeToSpec', async () => {
      const testYamlDir = path.join(__dirname, './fixtures/tmp-test-yaml-dir');
      const testYamlFile = path.join(testYamlDir, 'f.yaml');
      await ensureFileSync(testYamlFile);
      const data = Date.now();
      writeToSpec(testYamlDir, { data });
      const writedData = loadSpec(testYamlDir);
      await remove(testYamlDir);
      assert(writedData.data === data);
    });
  });
});