index.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { spawn } from 'child_process';
  2. import { mkdir, writeFile } from 'fs/promises';
  3. export interface RunOptions {
  4. cwd: string;
  5. }
  6. export async function run(command: string, options: RunOptions) {
  7. console.log(`Running ${command} in ${options.cwd}`);
  8. const process = spawn(command, { shell: true, cwd: options.cwd, stdio: 'inherit' });
  9. return new Promise<void>((resolve, reject) => {
  10. process.on('exit', (code) => {
  11. if (code !== 0) {
  12. reject(new Error(`Command ${command} exited with code ${code}`));
  13. } else {
  14. resolve();
  15. }
  16. });
  17. });
  18. }
  19. export async function gitShallowClone(targetPath: string, repositoryUrl: string, ref: string) {
  20. await mkdir(targetPath, { recursive: true });
  21. const options: RunOptions = { cwd: targetPath };
  22. await run('git init', options);
  23. await run(`git remote add origin ${repositoryUrl}`, options);
  24. await run(`git fetch --depth 1 origin ${ref}`, options);
  25. await run(`git checkout ${ref}`, options);
  26. }
  27. export async function group(name: string, body: () => Promise<void>): Promise<void> {
  28. console.log(`##[group]${name}`);
  29. try {
  30. await body();
  31. } catch (e) {
  32. console.error(e);
  33. throw e;
  34. } finally {
  35. console.log('##[endgroup]');
  36. }
  37. }
  38. export async function writeJsonFile(filePath: string, jsonData: unknown): Promise<void> {
  39. await writeFile(filePath, JSON.stringify(jsonData, null, '\t') + '\n');
  40. }