fs-extra#remove TypeScript Examples

The following examples show how to use fs-extra#remove. 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.test.ts    From cli with MIT License 6 votes vote down vote up
describe('/test/utils.test.ts', () => {
  beforeAll(async done => {
    if (existsSync(nm)) {
      await remove(nm);
    }
    execSync(`cd ${demoDir};npm install`);
    done();
  });
  it('findModuleFromNodeModules', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name,
        version: deps[name],
      };
    });
    const copyResult = await findModuleFromNodeModules(moduleInfoList, nm, nm);
    assert(Object.keys(copyResult).length > 1);
  });
  it('copyFromNodeModules', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name,
        version: deps[name],
      };
    });
    const target = join(demoDir, 'node_modules2');
    if (existsSync(target)) {
      await remove(target);
    }
    const start = Date.now();
    const copyResult = await copyFromNodeModules(moduleInfoList, nm, target);
    const useTime = Date.now() - start;
    console.log('useTime', useTime);
    assert(copyResult.length);
  });
  it('not exists', async () => {
    const copyResult = await findModuleFromNodeModules(
      [{ name: 'xxx', version: '*' }],
      nm,
      nm
    );
    assert(!copyResult);
  });
  it('not match version', async () => {
    const deps = JSON.parse(
      readFileSync(join(demoDir, 'package.json')).toString()
    ).dependencies;
    const moduleInfoList = Object.keys(deps).map(name => {
      return {
        name: name + 'x',
        version: '^100',
      };
    });
    const copyResult = await findModuleFromNodeModules(moduleInfoList, nm, nm);
    assert(!copyResult);
  });
});
Example #2
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 6 votes vote down vote up
async removeTag() {
    const items = (await PageUtil.pageToAllList(tagApi.list)).map(
      (tag) =>
        ({
          label: tag.title,
          tag,
        } as vscode.QuickPickItem & { tag: TagGetRes }),
    )
    const selectItem = await vscode.window.showQuickPick(items, {
      placeHolder: i18n.t('Please select the tag to delete'),
    })
    if (!selectItem) {
      return
    }
    await tagApi.remove(selectItem.tag.id)
    vscode.window.showInformationMessage(
      i18n.t('Remove tag [{{title}}] success', {
        title: selectItem.tag.title,
      }),
    )
  }
Example #3
Source File: midwayfaas3.test.ts    From cli with MIT License 6 votes vote down vote up
describe('/test/midwayfaas3.test.ts', () => {
  it('package', async () => {
    const baseDir = resolve(__dirname, './fixtures/midwayfaas3');
    const buildDir = resolve(baseDir, './.serverless');
    await remove(buildDir);
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      options: {
        bundle: true,
      },
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package']);
    const specFunctions = (core as any).coreInstance.service.functions;
    assert(specFunctions);
  });
});
Example #4
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 6 votes vote down vote up
/**
   * 删除附件
   */
  async removeResource() {
    const list = (
      await PageUtil.pageToAllList(resourceApi.list, {
        order_by: 'user_updated_time',
        order_dir: 'DESC',
      })
    ).map(
      (item) =>
        ({
          label: item.title,
          id: item.id,
        } as vscode.QuickPickItem & { id: string }),
    )
    const selectItemList = await vscode.window.showQuickPick(list, {
      canPickMany: true,
      placeHolder: '请选择要删除的附件资源',
    })
    if (!selectItemList || selectItemList.length === 0) {
      return
    }
    await Promise.all(selectItemList.map(async (item) => resourceApi.remove(item.id)))
    vscode.window.showInformationMessage(selectItemList.map((item) => item.label).join('\n'), {
      title: '删除附件成功',
    })
  }
Example #5
Source File: package-hooks.test.ts    From cli with MIT License 6 votes vote down vote up
describe('/test/package-hooks.test.ts', () => {
  const baseDir = resolve(__dirname, './fixtures/hooks');

  afterEach(async () => {
    await remove(join(baseDir, '.serverless'));
    await remove(join(baseDir, 'node_modules'));
  });
  it('base package', async () => {
    const originNodeEnv = process.env.NODE_ENV;

    process.env.MIDWAY_TS_MODE = 'false';
    process.env.NODE_ENV = 'dev';
    execSync(`cd ${baseDir};npm install @midwayjs/hooks-core@2`);
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      options: {
        skipZip: true,
        skipInstallDep: true,
      },
      log: console,
    });
    core.addPlugin(PackagePlugin);
    await core.ready();
    await core.invoke(['package']);
    process.env.NODE_ENV = originNodeEnv;
    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'abc/def.txt')));
    assert(
      (core as any).coreInstance.service.functions.all._handlers.length === 2
    );
  });
});
Example #6
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 6 votes vote down vote up
/**
   * 创建资源
   */
  async createResource() {
    const globalStoragePath = GlobalContext.context.globalStorageUri.fsPath
    const title = await vscode.window.showInputBox({
      placeHolder: i18n.t('Please enter what you want to create {{type}} name', {
        type: i18n.t('attachment'),
      }),
      value: '',
    })
    if (!title) {
      return
    }
    const filePath = path.resolve(globalStoragePath, `.tempResource/${title}`)
    await createEmptyFile(filePath)
    let { res, markdownLink } = await UploadResourceUtil.uploadFileByPath(filePath)
    // 如果是 svg 图片则作为图片插入
    if (path.extname(filePath) === '.svg') {
      markdownLink = '!' + markdownLink
    }
    await Promise.all([
      uploadResourceService.insertUrlByActiveEditor(markdownLink),
      uploadResourceService.refreshResourceList(res.id),
    ])
    if (await pathExists(filePath)) {
      await remove(filePath)
    }
    vscode.window.showInformationMessage(i18n.t('Attachment resource created successfully'))
    await this.handlerService.openResource(res.id)
  }
Example #7
Source File: remove-useless-files.test.ts    From cli with MIT License 6 votes vote down vote up
describe('/test/remove-useless-files.test.ts', () => {
  const baseDir = resolve(__dirname, './fixtures/base-app');
  afterEach(async () => {
    await remove(join(baseDir, 'serverless.zip'));
    // await remove(join(baseDir, 'package-lock.json'));
    // await remove(join(baseDir, '.serverless'));
    // await remove(join(baseDir, 'node_modules'));
  });
  it('base package', async () => {
    const service = loadSpec(baseDir);
    service.experimentalFeatures = {
      removeUselessFiles: true,
    };
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service,
      provider: 'aliyun',
      options: {
        skipZip: true,
      },
      log: console,
    });
    core.addPlugin(PackagePlugin);
    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/@midwayjs/core/LICENSE')));
  });
});
Example #8
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 6 votes vote down vote up
/**
   * remove folder or note
   * @param item
   */
  async remove(item: FolderOrNote = this.config.noteListTreeView.selection[0]) {
    console.log('joplinNote.remove: ', item)
    const folderOrNote = item.item
    if (appConfig.deleteConfirm) {
      const confirmMsg = i18n.t('confirm')
      const cancelMsg = i18n.t('cancel')
      const res = await vscode.window.showQuickPick([confirmMsg, cancelMsg], {
        placeHolder: i18n.t('delete or not {{type}} [{{title}}]', {
          type: i18n.t(
            folderOrNote.type_ === TypeEnum.Folder
              ? 'folder'
              : (folderOrNote as JoplinListNote).is_todo
              ? 'todo'
              : 'note',
          ),
          title: folderOrNote.title,
        }),
      })
      console.log(res)
      if (res !== confirmMsg) {
        return
      }
    }

    if (GlobalContext.openNoteMap.get(item.id)) {
      await remove(GlobalContext.openNoteMap.get(item.id)!)
      GlobalContext.openNoteMap.delete(item.id)
      GlobalContext.openNoteResourceMap.delete(item.id)
      // TODO 目前无法关闭指定的 TextDocument,参考:https://github.com/Microsoft/vscode/commit/d625b55e9ec33f95d2fe1dd7a4b7cb50abb4772c#diff-4654cd1aa2a333bc6cc7ca0d19fdfb6e
    }
    await this.folderOrNoteExtendsApi.remove(item.item)
    await this.config.noteViewProvider.refresh()
  }
Example #9
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 #10
Source File: build.ts    From joplin-utils with MIT License 6 votes vote down vote up
async function main() {
  await remove(path.resolve(__dirname, 'dist'))
  const isWatch = process.argv.includes('-w')
  const options = {
    base: __dirname,
    isWatch: isWatch,
  }
  const program = new ESBuildProgram(options)
  const deps = await ESBuildProgram.getDeps(options.base)
  const platform = await ESBuildProgram.getPlatform(options.base)
  const cliOptions = program.getBuildCliOption({
    deps: deps,
    platform: platform,
  })
  cliOptions.external = [...cliOptions.external, ...deps]
  const cli = {
    title: 'cli',
    task: () => program.build(cliOptions),
  }
  const { cjs, esm, dts } = await program.getTasks()
  await program.execTasks([cjs, esm, cli, dts])
}
Example #11
Source File: ResourceWriter.ts    From joplin-blog with MIT License 6 votes vote down vote up
async clean() {
    const postPath = path.resolve(this.config.postPath)
    const resourcePath = path.resolve(this.config.resourcePath)

    async function clean(dirPath: string) {
      if (await pathExists(dirPath)) {
        await remove(dirPath)
      }
      await mkdirp(dirPath)
    }

    await Promise.all([clean(postPath), clean(resourcePath)])
  }
Example #12
Source File: nx.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export async function readDependenciesFromNxDepGraph(
  workspaceRoot: string,
  project: string,
) {
  const depGraphFile = join('tmp', 'dep-graph.json');
  execSync(`npx nx dep-graph --file ${depGraphFile}`, {
    cwd: workspaceRoot,
    stdio: 'inherit',
  });
  const absolutePath = join(workspaceRoot, depGraphFile);
  const { graph } = await readJson(absolutePath);
  await remove(absolutePath);

  const deps: Array<{ source: string; target: string }> =
    graph.dependencies[project];
  console.log('[E2E]: Found dependencies', deps);
  return new Set(deps.map((x) => x.target));
}
Example #13
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
async clean() {
    if (!this.options.clean) {
      return;
    }
    const outdir = this.getOutDir();
    if (existsSync(outdir)) {
      await remove(outdir);
    }
  }
Example #14
Source File: get-source.ts    From fect with MIT License 6 votes vote down vote up
getSVGSource = async () => {
  await remove(sourcePath)
  try {
    const res = await fetchDta()
    return res
  } catch (error) {
    console.log(error)
    process.exit(1)
  }
}
Example #15
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
// 生成默认入口
  async defaultGenerateEntry() {
    const functions = this.core.service.functions || {};
    for (const func in functions) {
      const handlerConf = functions[func];
      const [handlerFileName] = handlerConf.handler.split('.');
      const othEnterFile = [
        join(this.defaultTmpFaaSOut, handlerFileName + '.js'),
        join(this.core.config.servicePath, handlerFileName + '.js'),
      ].find(file => existsSync(file));
      if (othEnterFile) {
        const fileName = join(this.midwayBuildPath, `${handlerFileName}.js`);
        await copy(othEnterFile, fileName);
        this.core.debug('Use user entry', othEnterFile);
      }
    }
    if (existsSync(this.defaultTmpFaaSOut)) {
      this.core.debug('Tmp Out Dir Removed');
      await remove(this.defaultTmpFaaSOut);
    }
  }
Example #16
Source File: TagUseService.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
it('基本示例', async () => {
  const configPath = path.resolve(__dirname, 'temp/db.json')
  await remove(configPath)
  const tagUseService = new TagUseService(configPath)
  expect(await tagUseService.getMap()).toEqual(new Map())
  await tagUseService.save([{ id: '1', title: 'hello' }])
  expect((await tagUseService.getMap()).get('1')!.title).toEqual('hello')
  await tagUseService.save([{ id: '1', title: 'world' }])
  expect((await tagUseService.getMap()).get('1')!.title).toEqual('world')
})
Example #17
Source File: not-commonjs.test.ts    From cli with MIT License 6 votes vote down vote up
describe('test/not-commonjs.test.ts', () => {
  it('dev', async () => {
    const tsConfigFile = join(cwd, 'tsconfig.json');
    if (existsSync(tsConfigFile)) {
      await remove(tsConfigFile);
    }
    await copy(join(cwd, 'tsconfig.json.origin'), tsConfigFile);
    const { close, port, getData } = await run(cwd, {
      silent: true,
      fast: false,
    });
    const response = await fetch(`http://127.0.0.1:${port}/hello?name=midway`);
    const body = await response.text();
    const functions = await getData('functions');
    await close();
    const tsconfig = JSON.parse(readFileSync(tsConfigFile).toString());
    await remove(tsConfigFile);
    assert(functions.http);
    assert(body === 'hello world,midway');
    assert(tsconfig['ts-node'].compilerOptions.module === 'commonjs');
  });
});
Example #18
Source File: main.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function withFileLock(lockFilePath: string, cb: () => Promise<void>): Promise<LockFileResult> {
  console.log("Checking for lock file...");
  if (await pathExists(lockFilePath)) {
    const lastRunStartTimestamp = (await tryReadJson(lockFilePath, isLockfileFormat))?.timestamp || currentTimeStamp();
    const elapsedSeconds = (Date.now() - Date.parse(lastRunStartTimestamp)) / 1000;
    if (elapsedSeconds < getFunctionTimeoutSeconds()) {
      console.log("Lock file exists; new run not triggered.");
      return { triggered: false, timestamp: lastRunStartTimestamp };
    }
  }

  console.log("Lock file does not exist; writing lock file and running.");
  await writeFile(lockFilePath, JSON.stringify({ timestamp: currentTimeStamp() }));
  cb().then(
    () => remove(lockFilePath),
    async (error) => {
      console.error(error?.stack || error?.message || error);
      applicationinsights.defaultClient.trackException({
        exception: error,
      });

      await remove(lockFilePath);
      process.exit(1);
    }
  );

  return { triggered: true };
}
Example #19
Source File: createEmptyFile.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 createEmptyFile', () => {
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it.skip('基本示例', async () => {
    const filePath = path.resolve(tempPath, 'test.drawio.svg')
    let handle: number
    try {
      handle = await createEmptyFile(filePath)
      expect(await readFile(filePath, 'utf-8')).toBe('')
    } finally {
      await close(handle!)
    }
  })
})
Example #20
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
async newFormatCommand() {
    this.template = this.options.template;
    if (this.options.type) {
      this.template = templateList[this.options.type]?.package;
    }
    if (!this.template) {
      this.template = await this.userSelectTemplate();
    }

    if (!this.options.npm) {
      const { cmd, npm, registry } = findNpm();
      if (['yarn', 'pnpm'].includes(npm)) {
        this.options.npm = 'npm' + (registry ? ` --registry=${registry}` : '');
      } else {
        this.options.npm = cmd;
      }
    }

    const { commands } = this.core.coreOptions;
    let projectPath = this.options.target || commands[1];
    if (!projectPath) {
      projectPath = await new (enquirer as any).Input({
        message: 'What name would you like to use for the new project?',
        initial: 'midway-project',
      }).run();
    }
    this.projectName = projectPath;
    const { cwd } = this.core;
    this.core.debug('cwd', cwd);
    const projectDirPath = join(cwd, projectPath);
    if (existsSync(projectDirPath)) {
      const isOverwritten = await new (enquirer as any).Confirm({
        name: 'question',
        message: `The name '${projectPath}' already exists, is it overwritten?`,
        initial: true,
      }).run();
      if (!isOverwritten) {
        process.exit();
      }
      await remove(projectDirPath);
    }
    this.projectDirPath = projectDirPath;
  }
Example #21
Source File: withFileLock.test.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
describe("withFileLock", () => {
  // The file lock should be cleaned up as part of a successful test run,
  // but we clean up before and after just to make sure we don't create
  // any weird state with a failed or canceled test.
  beforeAll(() => {
    try {
      return remove(lockFilePath);
    } catch {
      return;
    }
  });
  afterAll(() => {
    try {
      return remove(lockFilePath);
    } catch {
      return;
    }
  });

  function getDeferred() {
    const eventEmitter = new EventEmitter();
    const resolve = () => eventEmitter.emit("resolve");
    const promise = new Promise<void>((resolve) => {
      eventEmitter.once("resolve", resolve);
    });
    return { resolve, promise };
  }

  it("works", async () => {
    const { resolve, promise } = getDeferred();

    // Awaiting `withFileLock` does not await its callback!
    // `promise` will be pending until we call `resolve()`,
    // but `withFileLock` writes a file and resolves as soon
    // as it can.
    const result1 = await withFileLock(lockFilePath, () => promise);
    expect(result1).toMatchObject({ triggered: true });

    // At this point the file still exists and `promise` is still
    // pending. Calling again should tell us that the callback
    // was not triggered due to an ongoing run.
    const result2 = await withFileLock(lockFilePath, () => Promise.resolve());
    expect(result2).toMatchObject({ triggered: false });
    expect(result2).toHaveProperty("timestamp");

    // Resolving our promise should clean up.
    resolve();
    await promise;
    expect(!(await pathExists(lockFilePath)));
  });
});
Example #22
Source File: TestWorkspace.ts    From yarn-plugins with MIT License 5 votes vote down vote up
public async cleanup(): Promise<void> {
    await remove(this.path);
  }
Example #23
Source File: build.ts    From malagu with MIT License 5 votes vote down vote up
export async function after(ctx: CliContext) {

    const genEntry = join(PathUtil.getBackendProjectDistPath(), 'gen-entry.js');
    if (existsSync(genEntry)) {
        remove(genEntry);
    }
}
Example #24
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 entryList = await globby(['*.js'], {
      cwd: this.midwayBuildPath,
    });

    if (!entryList.length) {
      return;
    }

    this.core.cli.log('Build bundle...');

    await Promise.all(
      entryList.map(async entry => {
        const entryName = entry.slice(0, -3);
        await forkNode(
          nccCli,
          ['build', entry, '-o', 'ncc_build_tmp/' + entryName, '-m'],
          {
            cwd: this.midwayBuildPath,
          }
        );
        await remove(join(this.midwayBuildPath, entry));
        await move(
          join(
            this.midwayBuildPath,
            'ncc_build_tmp/' + entryName + '/index.js'
          ),
          join(this.midwayBuildPath, entry)
        );
      })
    );

    await remove(join(this.midwayBuildPath, 'node_modules'));
    await remove(join(this.midwayBuildPath, 'dist'));
    await remove(join(this.midwayBuildPath, 'ncc_build_tmp'));
    await remove(join(this.midwayBuildPath, 'src'));
  }
Example #25
Source File: ResourceApi.test.ts    From joplin-utils with MIT License 4 votes vote down vote up
describe('test ResourceApi', () => {
  let id: string
  beforeAll(async () => {
    id = (await createTestResource()).id
  })
  afterAll(async () => {
    await resourceApi.remove(id)
  })
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it('test list', async () => {
    const res = await resourceApi.list({ fields: ['id', 'title'] })
    console.log(res)
    expect(res.items.length).toBeGreaterThan(0)
  })
  it('test get', async () => {
    const res = await resourceApi.get(id)
    console.log(res)
    expect(res.id).toBe(id)
  })
  /**
   * TODO 一个官方未修复的 bug,参考:https://github.com/laurent22/joplin/issues/4575
   */
  it.skip('test get filename', async () => {
    const res = await resourceApi.get(id, ['id', 'filename'])
    console.log(res)
    expect(res.filename).not.toBe('')
  })

  describe('diff fetch and axios', () => {
    const path = resolve(__dirname, '../resource/resourcesByFileId.png')
    it('test create', async () => {
      const title = 'image title'
      const json = await resourceApi.create({
        title,
        data: createReadStream(path),
      })
      expect(json.title).toBe(title)
    })
  })
  describe('test update', () => {
    it('basic example', async () => {
      const title = `new title ${Date.now()}`
      const updateRes = await resourceApi.update({ id, title })
      expect(updateRes.title).toBe(title)
    })
    it('update file', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update properties and file', async () => {
      const title = `new title ${Date.now()}`
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const updateRes = await resourceApi.update({ id, title, data: createReadStream(txtPath) })
      expect(updateRes.title).toBe(title)
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
    })
    it('update file only', async () => {
      const content = 'test'
      const txtPath = path.resolve(tempPath, 'test.txt')
      await writeFile(txtPath, content)
      const { title } = await resourceApi.get(id)
      await resourceApi.update({ id, data: createReadStream(txtPath) })
      const res = await resourceApi.fileByResourceId(id)
      expect(res.toString()).toBe(content)
      expect((await resourceApi.get(id)).title).toBe(title)
    })
  })
  /**
   * 已知错误
   * https://discourse.joplinapp.org/t/pre-release-v2-8-is-now-available-updated-14-april/25158/10?u=rxliuli
   */
  it.skip('test remove ', async () => {
    const id = (await createTestResource()).id
    await resourceApi.remove(id)
    await expect(resourceApi.get(id)).rejects.toThrowError()
  })
  it('test fileByResourceId', async () => {
    const res = await resourceApi.fileByResourceId(id)
    console.log(typeof res)
    const path = resolve(tempPath, 'resourcesByFileId.png')
    await writeFile(path, res)
    expect(pathExistsSync(path)).toBeTruthy()
  })
  it('test to get the size of the attachment resource', async () => {
    const id = (await createTestResource()).id
    const res = await resourceApi.get(id, ['id', 'title', 'size'])
    const stats = await stat(path.resolve(__dirname, '../resource/resourcesByFileId.png'))
    expect(res.size).toEqual(stats.size)
  })
})
Example #26
Source File: wrapper.test.ts    From cli with MIT License 4 votes vote down vote up
describe('/test/wrapper.test.ts', () => {
  const wrapperPath = resolve(__dirname, './fixtures/wrapper');

  afterEach(async () => {
    await remove(wrapperPath);
  });

  describe('test all format', () => {
    beforeEach(async () => {
      await remove(wrapperPath);
      mkdirpSync(wrapperPath);
    });
    it('writeWrapper functionMap', async () => {
      const wrapperPath = resolve(__dirname, './fixtures/wrapper');
      writeWrapper({
        initializeName: 'initializeUserDefine',
        middleware: ['test1', 'test2'],
        cover: true,
        service: {
          functions: {
            aggregation: {
              handler: 'aggre.handler',
              _isAggregation: true,
              functions: ['index'],
              _handlers: [
                { path: '/api/test', handler: 'index.handler' },
                { path: '/*', handler: 'render.handler' },
              ],
            },
            index: {
              handler: 'index.handler',
              isFunctional: true,
              exportFunction: 'aggregation',
              sourceFilePath: 'fun-index.js',
            },
            render: {
              handler: 'render.handler',
            },
          },
        },
        baseDir: wrapperPath,
        distDir: wrapperPath,
        starter: 'testStarter',
        moreArgs: true,
      });
      const aggrePath = resolve(wrapperPath, 'aggre.js');
      const indexPath = resolve(wrapperPath, 'index.js');
      const renderPath = resolve(wrapperPath, 'render.js');

      assert(existsSync(aggrePath));
      assert(existsSync(indexPath));
      assert(existsSync(renderPath));
      const aggreContent = readFileSync(aggrePath).toString();
      assert(/exports\.initializeUserDefine\s*=/.test(aggreContent));
      assert(
        aggreContent.indexOf('handler.method.indexOf(currentMethod)') !== -1
      );
      assert(
        aggreContent.indexOf(
          'frameworkInstance.handleInvokeWrapper(handler.handler)(ctx, ...args)'
        ) !== -1
      );
      assert(aggreContent.indexOf('async (ctx, ...args)') !== -1);
      assert(
        /exports\.initializeUserDefine\s*=/.test(
          readFileSync(indexPath).toString()
        )
      );
      assert(
        /exports\.initializeUserDefine\s*=/.test(
          readFileSync(renderPath).toString()
        )
      );
    });

    it('writeWrapper aggregation', async () => {
      const wrapperPath = resolve(__dirname, './fixtures/wrapper');
      const registerFunction = resolve(wrapperPath, 'registerFunction.js');
      if (existsSync(registerFunction)) {
        await remove(registerFunction);
      }
      writeWrapper({
        initializeName: 'initializeUserDefine',
        middleware: ['test1', 'test2'],
        cover: true,
        service: {
          functions: {
            aggregation: {
              handler: 'aggre.handler',
              _isAggregation: true,
              functions: ['index'],
              _handlers: [
                {
                  path: '/api/test',
                  handler: 'index.handler',
                  argsPath: 'ctx.request.data.args',
                  isFunctional: true,
                  exportFunction: 'test',
                  sourceFilePath: 'fun-index.js',
                },
                { path: '/*', handler: 'render.handler' },
              ],
            },
          },
          layers: {
            testNpm: {
              path: 'npm:test',
            },
            'remote-debug': {
              path: 'oss:remote-debug',
            },
            testOss: {
              path: 'oss:test',
            },
          },
        },
        baseDir: wrapperPath,
        distDir: wrapperPath,
        starter: 'testStarter',
      });
      const aggrePath = resolve(wrapperPath, 'aggre.js');
      assert(
        /const layer_npm_testNpm = require\('test'\);/.test(
          readFileSync(aggrePath).toString()
        )
      );
      assert(/layer_oss_remote_debug/.test(readFileSync(aggrePath).toString()));
    });
    it('writeWrapper', async () => {
      const wrapperPath = resolve(__dirname, './fixtures/wrapper');
      const registerFunction = resolve(wrapperPath, 'registerFunction.js');
      if (existsSync(registerFunction)) {
        await remove(registerFunction);
      }
      writeWrapper({
        initializeName: 'initializeUserDefine',
        middleware: ['test1', 'test2'],
        cover: true,
        service: {
          functions: {
            aggregation: {
              handler: 'aggre.handler',
              _isAggregation: true,
              functions: ['index'],
              _handlers: [
                { path: '/api/test', handler: 'index.handler', method: 'get' },
                {
                  path: '/*',
                  handler: 'render.handler',
                  method: ['post', 'Get'],
                },
              ],
            },
            index: {
              handler: 'index.handler',
            },
            render: {
              handler: 'render.handler',
            },
          },
        },
        baseDir: wrapperPath,
        distDir: wrapperPath,
        starter: 'testStarter',
      });
      const aggrePath = resolve(wrapperPath, 'aggre.js');
      const indexPath = resolve(wrapperPath, 'index.js');
      const renderPath = resolve(wrapperPath, 'render.js');
      assert(existsSync(aggrePath));
      assert(existsSync(indexPath));
      assert(existsSync(renderPath));
      assert(!existsSync(registerFunction));
      assert(
        !/registerFunctionToIocByConfig/.test(
          readFileSync(aggrePath).toString()
        )
      );
      assert(
        readFileSync(aggrePath)
          .toString()
          .indexOf('handler.method.indexOf(currentMethod)') !== -1
      );
      assert(
        !/require\('registerFunction\.js'\)/.test(
          readFileSync(aggrePath).toString()
        )
      );
      assert(
        /exports\.initializeUserDefine\s*=/.test(
          readFileSync(aggrePath).toString()
        )
      );
      assert(
        /exports\.initializeUserDefine\s*=/.test(
          readFileSync(indexPath).toString()
        )
      );
      assert(
        /exports\.initializeUserDefine\s*=/.test(
          readFileSync(renderPath).toString()
        )
      );
    });
  });
  it('formetAggregationHandlers', async () => {
    const formatResult = formetAggregationHandlers([
      { path: '/api/1', eventType: 'http' },
      { path: '/api/', eventType: 'http' },
      { path: '/', eventType: 'http' },
      { path: '/api/*', eventType: 'http' },
      { path: '/api2', eventType: 'http' },
      { path: '/api/2', eventType: 'http' },
      { path: '/api', eventType: 'http' },
      { path: '/*', eventType: 'http' },
    ]);
    assert(formatResult[2].router === '/api/');
    assert(formatResult[3].router === '/api/**');
    assert(formatResult[4].router === '/api2');
    assert(formatResult[5].router === '/api');
    assert(formatResult[6].router === '/');
    assert(formatResult[7].router === '/**');
  });
});
Example #27
Source File: main.ts    From DefinitelyTyped-tools with MIT License 4 votes vote down vote up
export async function runDTSLint({
  definitelyTypedAcquisition,
  onlyRunAffectedPackages = false,
  noInstall,
  onlyTestTsNext,
  expectOnly,
  localTypeScriptPath,
  nProcesses,
  shard,
}: RunDTSLintOptions) {
  let definitelyTypedPath;
  if (definitelyTypedAcquisition.kind === "clone") {
    definitelyTypedPath = joinPaths(process.cwd(), "DefinitelyTyped");
    if (!noInstall) {
      await remove(definitelyTypedPath);
      await cloneDefinitelyTyped(process.cwd(), definitelyTypedAcquisition.sha);
    }
  } else {
    definitelyTypedPath = definitelyTypedAcquisition.path;
  }

  if (!(await pathExists(definitelyTypedPath))) {
    throw new Error(`Path '${definitelyTypedPath}' does not exist.`);
  }

  const typesPath = joinPaths(definitelyTypedPath, "types");

  const { packageNames, dependents } = onlyRunAffectedPackages
    ? await prepareAffectedPackages({ definitelyTypedPath, nProcesses, noInstall })
    : await prepareAllPackages({ definitelyTypedPath, nProcesses, noInstall });

  if (!noInstall && !localTypeScriptPath) {
    if (onlyTestTsNext) {
      await installTypeScriptNext();
    } else {
      await installAllTypeScriptVersions();
    }
  }

  const allFailures: [string, string][] = [];
  const expectedFailures = getExpectedFailures(onlyRunAffectedPackages);

  const allPackages = [...packageNames, ...dependents];
  const testedPackages = shard ? allPackages.filter((_, i) => i % shard.count === shard.id - 1) : allPackages;

  const dtslintArgs = [
    "--listen",
    ...(onlyTestTsNext ? ["--onlyTestTsNext"] : []),
    ...(localTypeScriptPath ? ["--localTs", localTypeScriptPath] : []),
  ];

  await runWithListeningChildProcesses({
    inputs: testedPackages.map((path) => ({
      path,
      onlyTestTsNext: onlyTestTsNext || !packageNames.includes(path),
      expectOnly: expectOnly || !packageNames.includes(path),
    })),
    commandLineArgs: dtslintArgs,
    workerFile: require.resolve("@definitelytyped/dtslint"),
    nProcesses,
    cwd: typesPath,
    crashRecovery: true,
    crashRecoveryMaxOldSpaceSize: 0, // disable retry with more memory
    handleStart(input, processIndex) {
      const prefix = processIndex === undefined ? "" : `${processIndex}> `;
      console.log(`${prefix}${input.path} START`);
    },
    handleOutput(output, processIndex) {
      const prefix = processIndex === undefined ? "" : `${processIndex}> `;
      const { path, status } = output as { path: string; status: string };
      if (expectedFailures?.has(path)) {
        if (status === "OK") {
          console.error(`${prefix}${path} passed, but was expected to fail.`);
          allFailures.push([path, status]);
        } else {
          console.error(`${prefix}${path} failed as expected:`);
          console.error(
            prefix
              ? status
                  .split(/\r?\n/)
                  .map((line) => `${prefix}${line}`)
                  .join("\n")
              : status
          );
        }
      } else if (status === "OK") {
        console.log(`${prefix}${path} OK`);
      } else {
        console.error(`${prefix}${path} failing:`);
        console.error(
          prefix
            ? status
                .split(/\r?\n/)
                .map((line) => `${prefix}${line}`)
                .join("\n")
            : status
        );
        allFailures.push([path, status]);
      }
    },
    handleCrash(input, state, processIndex) {
      const prefix = processIndex === undefined ? "" : `${processIndex}> `;
      switch (state) {
        case CrashRecoveryState.Retry:
          console.warn(`${prefix}${input.path} Out of memory: retrying`);
          break;
        case CrashRecoveryState.RetryWithMoreMemory:
          console.warn(`${prefix}${input.path} Out of memory: retrying with increased memory (4096M)`);
          break;
        case CrashRecoveryState.Crashed:
          console.error(`${prefix}${input.path} Out of memory: failed`);
          allFailures.push([input.path, "Out of memory"]);
          break;
        default:
      }
    },
  });

  console.log("\n\n=== SUGGESTIONS ===\n");
  const suggestionLines: string[] = [];
  for (const packageName of packageNames) {
    const pkgPath = packageName.replace("/", ""); // react/v15 -> reactv15
    const path = joinPaths(suggestionsDir, pkgPath + ".txt");
    if (await pathExists(path)) {
      const suggestions = readFileSync(path, "utf8").split("\n");
      suggestionLines.push(`"${packageName}": [${suggestions.join(",")}]`);
    }
  }
  console.log(`{${suggestionLines.join(",")}}`);

  logPerformance();

  if (allFailures.length === 0) {
    return 0;
  }

  console.error("\n\n=== ERRORS ===\n");
  for (const [path, error] of allFailures) {
    console.error(`\n\nError in ${path}`);
    console.error(error);
  }

  return allFailures.length;
}