os#tmpdir TypeScript Examples

The following examples show how to use os#tmpdir. 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: crop.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
crop = async (filename: string): Promise<Buffer> => {
    const file = await new Promise<string>((resolve) => {
        const name = `${tmpdir()}/${Math.random().toString(36)}.webp`
        Ffmpeg(filename)
            // eslint-disable-next-line no-useless-escape
            .outputOptions([
                '-vcodec',
                'libwebp',
                '-vf',
                // eslint-disable-next-line no-useless-escape
                `crop=w='min(min(iw\,ih)\,500)':h='min(min(iw\,ih)\,500)',scale=500:500,setsar=1,fps=15`,
                '-loop',
                '0',
                '-preset',
                'default',
                '-an',
                '-vsync',
                '0',
                '-s',
                '512:512'
            ])
            .save(name)
            .on('end', () => resolve(name))
    })
    return await readFile(file)
}
Example #2
Source File: context.ts    From lage with MIT License 6 votes vote down vote up
export function createContext(
  config: Pick<Config, "concurrency" | "profile" | "dist" | "workerQueueOptions">
): RunContext {
  const { concurrency, profile } = config;

  const useCustomProfilePath = typeof profile === "string";

  const profilerOutputDir = useCustomProfilePath ? dirname(profile as string) : join(tmpdir(), "lage", "profiles");

  mkdirSync(profilerOutputDir, { recursive: true });

  const profiler = new Profiler(
    useCustomProfilePath
      ? {
          concurrency,
          customOutputPath: profile as string,
        }
      : {
          concurrency,
          prefix: "lage",
          outDir: profilerOutputDir,
        }
  );

  return {
    measures: {
      start: [0, 0],
      duration: [0, 0],
      failedTargets: [],
    },
    targets: new Map(),
    profiler,
    workerQueue: config.dist ? new WorkerQueue(config) : undefined,
  };
}
Example #3
Source File: prepare-config.ts    From amman with Apache License 2.0 6 votes vote down vote up
export async function solanaConfig(config: {
  jsonRpcUrl: string
  websocketUrl: string
  commitment: Commitment
}) {
  const { jsonRpcUrl, websocketUrl, commitment } = config
  const configText = `---
json_rpc_url: "${jsonRpcUrl}"
websocket_url: "${websocketUrl}"
commitment: ${commitment} 
`
  const configHash = createHash(Buffer.from(configText))
  const configPath = path.join(tmpdir(), `amman-config.${configHash}.yml`)
  await fs.writeFile(configPath, configText, 'utf8')

  return { configPath, cleanupConfig: () => fs.unlink(configPath) }
}
Example #4
Source File: index.ts    From amman with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the path to a temporary directory in which to store the test
 * validator ledger.
 *
 * @param testLabel label used to name that directory
 * @category utils
 */
export function tmpLedgerDir(testLabel = 'amman-ledger') {
  return path.join(tmpdir(), testLabel)
}
Example #5
Source File: persistence.ts    From amman with Apache License 2.0 6 votes vote down vote up
export async function createTemporarySnapshot(
  addresses: string[],
  // Keyed pubkey:label
  accountLabels: Record<string, string>,
  keypairs: Map<string, { keypair: Keypair; id: string }>,
  accountOverrides: Map<string, PersistedAccountInfo> = new Map()
) {
  logDebug('Creating temporary snapshot')
  logTrace(accountOverrides)

  const label = 'temporary'
  const snapshotFolder = path.join(tmpdir(), 'amman-snapshots')
  const config: SnapshotConfig = {
    snapshotFolder,
    load: label,
  }
  const persister = new AccountPersister(
    snapshotFolder,
    new Connection(LOCALHOST, 'confirmed')
  )
  const snapshotDir = await persister.snapshot(
    label,
    addresses,
    accountLabels,
    keypairs,
    accountOverrides
  )

  function cleanupSnapshotDir() {
    return fs.rm(snapshotDir, { recursive: true })
  }

  return { config, cleanupSnapshotDir }
}
Example #6
Source File: utils-node.ts    From micropython-ctl with MIT License 6 votes vote down vote up
getTmpFilename = (ext: string) => {
  return path.join(tmpdir(), crypto.randomBytes(16).toString('hex') + ext)
}
Example #7
Source File: temp-location.ts    From open-design-sdk with Apache License 2.0 6 votes vote down vote up
export async function createTempLocation(): Promise<string> {
  const dirname = tmpdir()
  const id = `opendesignsdk-test-${uuid()}`

  const location = `${dirname}/${id}`
  await mkdirp(location)

  return location
}
Example #8
Source File: utils.ts    From vsc-markdown-image with MIT License 6 votes vote down vote up
function getTmpFolder() {
    let savePath = path.join(tmpdir(), pkg.name);
    if (!fs.existsSync(savePath)) { fs.mkdirSync(savePath); }
    return savePath;
}
Example #9
Source File: index.test.ts    From icepkg with MIT License 6 votes vote down vote up
test('getAndExtractTarballWithDir', () => {
  const tempDir = path.resolve(tmpdir(), 'babel_helper_function_name_tarball');
  return getAndExtractTarball(
    tempDir,
    `${defaultRegistry}/@babel/helper-function-name/download/@babel/helper-function-name-7.1.0.tgz`
  )
    .then((files) => {
      rimraf.sync(tempDir);
      expect(files.length > 0).toBe(true);
    })
    .catch(() => {
      rimraf.sync(tempDir);
    });
});
Example #10
Source File: index.test.ts    From icepkg with MIT License 6 votes vote down vote up
test('getAndExtractTarball', () => {
  const tempDir = path.resolve(tmpdir(), 'ice_npm_utils_tarball');
  let percent;
  return getAndExtractTarball(tempDir, `${defaultRegistry}/ice-npm-utils/-/ice-npm-utils-1.0.0.tgz`, (state) => {
    percent = state.percent;
  })
    .then((files) => {
      rimraf.sync(tempDir);
      expect(files.length > 0).toBe(true);
      expect(percent).toBe(1);
    })
    .catch(() => {
      rimraf.sync(tempDir);
    });
});
Example #11
Source File: utils.ts    From action-setup-vim with MIT License 6 votes vote down vote up
export async function makeTmpdir(): Promise<string> {
    const dir = tmpdir();
    await mkdirP(dir);
    core.debug(`Created temporary directory ${dir}`);
    return dir;
}
Example #12
Source File: BodyParser.ts    From ZenTS with MIT License 6 votes vote down vote up
constructor() {
    super()

    this.encoding = config.web?.bodyParser?.encoding ?? 'utf-8'
    this.maxFields = config.web?.bodyParser?.maxFields ?? 1000
    this.maxFieldsSize = config.web?.bodyParser?.maxFieldsSize ?? 20 * 1024 * 1024
    this.maxFileSize = config.web?.bodyParser?.maxFileSize ?? 200 * 1024 * 1024
    this.keepExtensions = config.web?.bodyParser?.keepExtensions ?? false
    this.uploadDir = config.web?.bodyParser?.uploadDir ?? tmpdir()
    this.multiples = config.web?.bodyParser?.multiples ?? false
  }
Example #13
Source File: utils.ts    From uivonim with GNU Affero General Public License v3.0 6 votes vote down vote up
getPipeName = (name: string) =>
  join(tmpdir(), `${name}${uuid()}.sock`)
Example #14
Source File: utils.ts    From gdmod with MIT License 6 votes vote down vote up
editAsar = async (
  asarFile: string,
  editor: (pathToGame: string) => Promise<void>,
  debug: boolean
) => {
  const tempDir: string = join(await fs.realpath(tmpdir()), "GDModTemp");
  const tempAsar: string = join(tempDir, "app.asar");

  // Make sure temp directory is empty
  try {
    await fs.mkdir(tempDir);
  } catch {
    console.log(chalk.blue(chalk.italic("Cleaning up old files...")));
    await fs.rmdir(tempDir, { recursive: true });
    await fs.mkdir(tempDir);
  }

  // Read file
  const asarFileContent: Buffer = await fs.readFile(asarFile);

  // Backup asar
  console.log(chalk.greenBright(chalk.italic("Backing up old asar file...")));
  await fs.writeFile(asarFile + ".bak", asarFileContent);

  // Copy asar to temp folder
  console.log(chalk.greenBright(chalk.italic("Loading asar file...")));
  await fs.writeFile(tempAsar, asarFileContent);

  // Unpack the asar
  try {
    console.log(chalk.greenBright(chalk.italic("Unpacking asar file...")));
    extractAll(tempAsar, tempDir);
    await fs.unlink(tempAsar); // To not repack it later
  } catch (e) {
    if (debug) console.log(e);
    console.error(
      chalk.redBright(chalk.bold("[ERROR] ") + "Invalid asar File!")
    );
    return false;
  }

  // Run asar editor
  editor(join(tempDir, "app")).then(
    () => {
      // Success, repacking the asar
      console.log(chalk.greenBright(chalk.italic("Repacking asar file...")));
      createPackage(tempDir, tempAsar).then(async () => {
        // Copy temporary new asar back to the original path
        await fs.writeFile(asarFile, await fs.readFile(tempAsar));
        console.log(chalk.greenBright(chalk.bold("DONE !")));
        console.log(chalk.blue(chalk.italic("Cleaning up...")));
        // Delete temp directory
        await fs.rmdir(tempDir, { recursive: true });
      });
    },
    async (e) => {
      // Patch aborted, cleaning up:
      console.log(chalk.redBright(chalk.bold("Error! ")), e);
      console.log(chalk.blue(chalk.italic("Cleaning up...")));
      // Delete temp directory
      await fs.rmdir(tempDir, { recursive: true });
    }
  );
}
Example #15
Source File: resolver.ts    From devoirs with MIT License 6 votes vote down vote up
async resolve(...path: string[]): Promise<string> {
    const resourceDirectory = await this.finder.find(...path);
    const temporaryDirectory = join(tmpdir(), '.devoirs', ...path);

    await createDirectory(temporaryDirectory);
    await copyDirectory(resourceDirectory, temporaryDirectory);

    return temporaryDirectory;
  }
Example #16
Source File: test-helpers.ts    From setup-cpp with Apache License 2.0 6 votes vote down vote up
export async function setupTmpDir(testName: string) {
  const tempDirectory = path.join(tmpdir(), "setup cpp temp", testName)
  try {
    await io.rmRF(tempDirectory)
    await io.mkdirP(tempDirectory)
  } catch {
    console.log("Failed to remove test directories")
  }
  process.env.SETUP_CPP_DIR = tempDirectory
  return tempDirectory
}
Example #17
Source File: read-file-or-url.spec.ts    From graphql-mesh with MIT License 6 votes vote down vote up
describe('readFile', () => {
  it('should convert relative paths to absolute paths correctly', async () => {
    const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
    const tmpFileContent = {
      test: 'TEST',
    };
    writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
    const tmpFileRelativePath = relative(cwd(), tmpFileAbsolutePath);
    const receivedFileContent = await readFile(tmpFileRelativePath);
    expect(receivedFileContent).toStrictEqual(tmpFileContent);
  });
  it('should respect absolute paths correctly', async () => {
    const tmpFileAbsolutePath = join(tmpdir(), './tmpfile.json');
    const tmpFileContent = {
      test: 'TEST',
    };
    writeFileSync(tmpFileAbsolutePath, JSON.stringify(tmpFileContent));
    const receivedFileContent = await readFile(tmpFileAbsolutePath);
    expect(receivedFileContent).toStrictEqual(tmpFileContent);
  });
});
Example #18
Source File: imagesToWebp.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
imagesToWebp = async (filename: string): Promise<Buffer> => {
    const file = await new Promise<string>((resolve) => {
        const name = `${tmpdir()}/${Math.random().toString(36)}.webp`
        Ffmpeg(filename)
            .outputOption('-lavfi split[v],palettegen,[v]paletteuse')
            .outputOption('-vcodec libwebp')
            .outputFPS(10)
            .loop(0)
            .save(name)
            .on('end', () => resolve(name))
    })
    return await readFile(file)
}
Example #19
Source File: videoToGif.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
videoToGif = async (data: Buffer): Promise<Buffer> => {
    const filename = `${tmpdir()}/${Math.random().toString(36)}`
    const [video, gif] = ['video', 'gif'].map((ext) => `${filename}.${ext}`)
    await writeFile(video, data)
    await new Promise((resolve) => {
        ffmpeg(video).save(gif).on('end', resolve)
    })
    const buffer = await readFile(gif)
    ;[video, gif].forEach((file) => unlink(file))
    return buffer
}
Example #20
Source File: qemu.ts    From Assistive-Webdriver with MIT License 6 votes vote down vote up
async takePNGScreenshot(): Promise<PNG> {
    const tempDirName = await mkdtemp(join(tmpdir(), "awd-qemu-"));
    let imageContent: Buffer;
    try {
      const filename = join(tempDirName, "screenshot.ppm");
      await this._sendCommand({
        execute: "screendump",
        arguments: { filename }
      });
      imageContent = await readFile(filename);
      await unlink(filename);
    } finally {
      await rmdir(tempDirName);
    }
    return parsePPM(imageContent);
  }
Example #21
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 #22
Source File: wikiWorker.ts    From TidGi-Desktop with Mozilla Public License 2.0 5 votes vote down vote up
function executeZxScript(file: IZxFileInput, zxPath: string): Observable<IZxWorkerMessage> {
  /** this will be observed in src/services/native/index.ts */
  return new Observable<IZxWorkerMessage>((observer) => {
    observer.next({ type: 'control', actions: ZxWorkerControlActions.start });

    void (async function executeZxScriptIIFE() {
      try {
        let filePathToExecute = '';
        if ('fileName' in file) {
          const temporaryDirectory = await mkdtemp(`${tmpdir()}${path.sep}`);
          filePathToExecute = path.join(temporaryDirectory, file.fileName);
          await writeFile(filePathToExecute, file.fileContent);
        } else if ('filePath' in file) {
          filePathToExecute = file.filePath;
        }
        const execution = fork(zxPath, [filePathToExecute], { silent: true });

        execution.on('close', function (code) {
          observer.next({ type: 'control', actions: ZxWorkerControlActions.ended, message: `child process exited with code ${String(code)}` });
        });
        execution.stdout?.on('data', (stdout: Buffer) => {
          // if there are multiple console.log, their output will be concatenated into this stdout. And some of them are not intended to be executed. We use TW_SCRIPT_SEPARATOR to allow user determine the range they want to execute in the $tw context.
          const message = String(stdout);
          const zxConsoleLogMessages = extractTWContextScripts(message);
          // log and execute each different console.log result.
          zxConsoleLogMessages.forEach(({ messageType, content }) => {
            if (messageType === 'script') {
              observer.next({ type: 'execution', message: content });
              if (wikiInstance === undefined) {
                observer.next({ type: 'stderr', message: `Error in executeZxScript(): $tw is undefined` });
              } else {
                const context = getTWVmContext(wikiInstance);
                const twExecutionResult = executeScriptInTWContext(content, context);
                observer.next({ type: 'stdout', message: twExecutionResult.join('\n\n') });
              }
            } else {
              observer.next({ type: 'stdout', message: content });
            }
          });
        });
        execution.stderr?.on('data', (stdout: Buffer) => {
          observer.next({ type: 'stderr', message: String(stdout) });
        });
        execution.on('error', (error) => {
          observer.next({ type: 'stderr', message: `${error.message} ${error.stack ?? ''}` });
        });
      } catch (error) {
        const message = `zx script's executeZxScriptIIFE() failed with error ${(error as Error).message} ${(error as Error).stack ?? ''}`;
        observer.next({ type: 'control', actions: ZxWorkerControlActions.error, message });
      }
    })();
  });
}
Example #23
Source File: mkdirp.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
export async function mkdirp(name: string): Promise<string> {
  const workspace = `./${tmpdir()}/${name}`;
  if (await fsExists(workspace)) {
    await promises.rmdir(workspace, { recursive: true });
  }
  await promises.mkdir(workspace, { recursive: true });
  return workspace;
}
Example #24
Source File: mock-server.ts    From amman with Apache License 2.0 5 votes vote down vote up
AMMAN_STORAGE_ROOT = path.join(tmpdir(), 'amman-storage')
Example #25
Source File: shared.ts    From F95API with MIT License 5 votes vote down vote up
private static _session = new Session(join(tmpdir(), "f95session.json"));
Example #26
Source File: convert.ts    From wa-sticker-formatter with MIT License 5 votes vote down vote up
convert = async (
    data: Buffer,
    mime: string,
    { quality = 100, background = defaultBg, type = StickerTypes.DEFAULT }: IStickerOptions
): Promise<Buffer> => {
    const isVideo = mime.startsWith('video')
    let image = isVideo ? await videoToGif(data) : data
    const isAnimated = isVideo || mime.includes('gif')

    if (isAnimated && ['crop', 'circle'].includes(type)) {
        const filename = `${tmpdir()}/${Math.random().toString(36)}.webp`
        await writeFile(filename, image)
        ;[image, type] = [await crop(filename), type === 'circle' ? StickerTypes.CIRCLE : StickerTypes.DEFAULT]
    }

    const img = sharp(image, { animated: type !== 'circle' }).toFormat('webp')

    if (type === 'crop')
        img.resize(512, 512, {
            fit: fit.cover
        })

    if (type === 'full')
        img.resize(512, 512, {
            fit: fit.contain,
            background
        })

    if (type === 'circle') {
        img.resize(512, 512, {
            fit: fit.cover
        }).composite([
            {
                input: Buffer.from(
                    `<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><circle cx="256" cy="256" r="256" fill="${background}"/></svg>`
                ),
                blend: 'dest-in'
            }
        ])
    }

    return await img
        .webp({
            quality,
            lossless: false
        })
        .toBuffer()
}
Example #27
Source File: pdf.default.ts    From nestjs-pdf with MIT License 5 votes vote down vote up
defaultCreateOptions = {
    filename: join(tmpdir(), `html-pdf-${process.pid}.pdf`),
}
Example #28
Source File: main.ts    From obsidian-jupyter with MIT License 5 votes vote down vote up
onLoadFile(file: TFile): Promise<void> {
		// Get the base path of the vault.
		let adapter = file.vault.adapter;
		if (!(adapter instanceof FileSystemAdapter)) {
			this.contentEl.innerHTML = 'Could not determine notebook path.';
			return null;
		}
		// Convert the file by writing it to a temporary location. Piping unfortunately leads to
		// problems for long lines due to buffer overflows.
		let basePath = adapter.getBasePath();
		let filename = `${basePath}/${file.path}`;
		let htmlPath = `${tmpdir()}/${uuid()}.html`;
		let args = ['-m', 'nbconvert', `--output=${htmlPath}`, '--to=html', filename];
		let child = spawn(this.interpreter, args);

		// Process the output and delete the temporary file.
		child.on('close', (code: number) => {
			if (code) {
				this.contentEl.innerHTML = 'Failed to convert notebook to HTML.';
			} else {
				// Create the frame for rendering.
				let frame = document.createElement('iframe');
				frame.addClass('notebookPreview')
				const html = readFileSync(htmlPath).toString();
				const blob = new Blob([html], {type: 'text/html'});
				frame.src = window.URL.createObjectURL(blob);

				// Insert the frame and hook up to resize events.
				this.contentEl.innerHTML = '';
				this.contentEl.addClass('notebookPreview');
				this.contentEl.appendChild(frame);
				new ResizeObserver((entries) => {
					for (let entry of entries) {
						frame.height = `${entry.contentRect.height - 6}px`;
					}
				}).observe(this.contentEl);
			}
			rm(htmlPath, () => null);
		})
		return null;
	}
Example #29
Source File: index.ts    From cli with MIT License 4 votes vote down vote up
// 合并高密度部署
  async checkAggregation() {
    // 只在部署阶段生效
    const commands = this.core.processedInput.commands;
    if (
      !commands ||
      !commands.length ||
      (commands[0] !== 'deploy' && commands[0] !== 'package')
    ) {
      return;
    }
    if (!this.core.service.aggregation || !this.core.service.functions) {
      return;
    }

    // if (
    //   !this.core.service.custom ||
    //   !this.core.service.custom.customDomain ||
    //   !this.core.service.custom.customDomain.domainName
    // ) {
    //   console.warn(
    //     'If using aggregation deploy, it is best to configure custom domain'
    //   );
    // }

    this.core.cli.log('Aggregation Deploy');

    // use picomatch to match url
    const allAggregationPaths = [];
    let allFuncNames = Object.keys(this.core.service.functions);
    for (const aggregationName in this.core.service.aggregation) {
      const aggregationConfig = this.core.service.aggregation[aggregationName];
      const aggregationFuncName = this.getAggregationFunName(aggregationName);
      this.core.service.functions[aggregationFuncName] = aggregationConfig;
      this.core.service.functions[
        aggregationFuncName
      ].handler = `${aggregationFuncName}.handler`;
      this.core.service.functions[aggregationFuncName]._isAggregation = true;
      if (!this.core.service.functions[aggregationFuncName].events) {
        this.core.service.functions[aggregationFuncName].events = [];
      }
      // 忽略原始方法,不再单独进行部署
      const deployOrigin = aggregationConfig.deployOrigin;

      let handlers = [];
      const allAggredHttpTriggers = [];
      const allAggredEventTriggers = [];
      if (aggregationConfig.functions || aggregationConfig.functionsPattern) {
        const matchedFuncName = [];
        const notMatchedFuncName = [];
        const functions = this.core.service.functions;
        for (const functionName of allFuncNames) {
          const func = functions[functionName];
          const isHttpFunction = func.events?.find(event => {
            return Object.keys(event)[0] === 'http';
          });
          // http 函数并且开启了 eventTrigger,需要忽略
          // 非 http 函数,并且没有开启  eventTrigger,需要忽略
          let isMatch = false;
          if (
            (isHttpFunction && aggregationConfig.eventTrigger) ||
            (!isHttpFunction && !aggregationConfig.eventTrigger)
          ) {
            isMatch = false;
          } else if (aggregationConfig.functions) {
            isMatch = aggregationConfig.functions.indexOf(functionName) !== -1;
          } else if (aggregationConfig.functionsPattern) {
            isMatch = micromatch.all(
              functionName,
              aggregationConfig.functionsPattern
            );
          }
          if (isMatch) {
            matchedFuncName.push(functionName);
          } else {
            notMatchedFuncName.push(functionName);
          }
        }
        allFuncNames = notMatchedFuncName;
        matchedFuncName.forEach((functionName: string) => {
          const functions = this.core.service.functions;
          const func = functions[functionName];
          if (!func || !func.events) {
            return;
          }

          for (const event of func.events) {
            const eventType = Object.keys(event)[0];
            const handlerInfo: any = {
              ...func,
              functionName,
              eventType,
            };
            if (eventType === 'http') {
              const httpInfo = {
                path: event.http.path,
                method: event.http.method,
              };
              allAggredHttpTriggers.push(httpInfo);
              Object.assign(handlerInfo, httpInfo);
            } else if (aggregationConfig.eventTrigger) {
              // 事件触发器支持
              const existsEventTrigger = handlers.find(
                handlerInfo => handlerInfo.eventType === eventType
              );
              if (!existsEventTrigger) {
                allAggredEventTriggers.push(event);
              }
            } else {
              continue;
            }
            if (!deployOrigin) {
              // 不把原有的函数进行部署
              this.core.cli.log(
                ` - using function '${aggregationName}' to deploy '${functionName}'`
              );
              delete this.core.service.functions[functionName];
            }

            handlers.push(handlerInfo);
          }
        });
      }
      handlers = handlers.filter((func: any) => !!func);

      this.core.service.functions[aggregationFuncName]._handlers = handlers;
      this.core.service.functions[aggregationFuncName]._allAggred =
        allAggredHttpTriggers;
      this.core.service.functions[aggregationFuncName].events =
        allAggredEventTriggers;

      if (allAggredHttpTriggers?.length) {
        const allPaths = allAggredHttpTriggers.map(aggre => aggre.path);
        let currentPath = commonPrefix(allPaths);
        currentPath =
          currentPath && currentPath !== '/' ? `${currentPath}/*` : '/*';

        this.core.cli.log(
          ` - using path '${currentPath}' to deploy '${allPaths.join("', '")}'`
        );
        // path parameter
        if (currentPath.includes(':')) {
          const newCurrentPath = currentPath.replace(/\/:.*$/, '/*');
          this.core.cli.log(
            ` - using path '${newCurrentPath}' to deploy '${currentPath}' (for path parameter)`
          );
          currentPath = newCurrentPath;
        }
        if (allAggregationPaths.indexOf(currentPath) !== -1) {
          console.error(
            `Cannot use the same prefix '${currentPath}' for aggregation deployment`
          );
          process.exit(1);
        }
        allAggregationPaths.push(currentPath);
        this.core.service.functions[aggregationFuncName].events.push({
          http: { method: 'any', path: currentPath },
        });
      }
    }

    const tmpSpecFile = resolve(tmpdir(), `aggre-${Date.now()}/f.yml`);
    await ensureFile(tmpSpecFile);

    this.core.config.specFile.path = tmpSpecFile;
    writeToSpec(this.servicePath, this.core.service, this.core.config.specFile);
  }