|  | 
|  | 1 | +import path from 'node:path'; | 
|  | 2 | +import fs from 'node:fs'; | 
|  | 3 | +import { tmpdir } from 'node:os'; | 
|  | 4 | +import { execSync } from 'node:child_process'; | 
|  | 5 | + | 
|  | 6 | +export const PNPM_STORE_PATH = path.resolve(__dirname, '../.pnpm-test-store'); | 
|  | 7 | +export const NPM_RC_FILE = '.npmrc'; | 
|  | 8 | +export const NPM_RC_CONTENTS = `store-dir = ${PNPM_STORE_PATH}`; | 
|  | 9 | +export const PACKAGE_JSON_FILE = 'package.json'; | 
|  | 10 | +export const PACKAGE_JSON_CONTENTS = '{"name":"test-project","version":"1.0.0"}'; | 
|  | 11 | + | 
|  | 12 | +export function preparePackageJson(dependencies: {[key: string]: string} = {}, devDependencies: {[key: string]: string} = {}): string { | 
|  | 13 | +  const tmpDir = fs.mkdtempSync(path.join(tmpdir(), 'zenstack-test-')); | 
|  | 14 | +  try { | 
|  | 15 | +  const packageJsonContents =  | 
|  | 16 | +`{ | 
|  | 17 | +  "name":"test-project", | 
|  | 18 | +  "version":"1.0.0", | 
|  | 19 | +  "dependencies": { | 
|  | 20 | +    ${Object.entries(dependencies).map(([k, v]) => `"${k}": "${v}"`).join(',\n')} | 
|  | 21 | +  }, | 
|  | 22 | +  "devDependencies": { | 
|  | 23 | +    ${Object.entries(devDependencies).map(([k, v]) => `"${k}": "${v}"`).join(',\n')} | 
|  | 24 | +  } | 
|  | 25 | +}`; | 
|  | 26 | + | 
|  | 27 | +  initProjectDir(tmpDir, packageJsonContents, false); | 
|  | 28 | + | 
|  | 29 | +  return packageJsonContents; | 
|  | 30 | +  } finally { | 
|  | 31 | +    fs.rmSync(tmpDir, {recursive: true, force: true}); | 
|  | 32 | +    console.log(`Loaded dependencies into store via temp dir ${tmpDir}`); | 
|  | 33 | +  } | 
|  | 34 | +} | 
|  | 35 | + | 
|  | 36 | +function execCmdSync(cmd: string, path: string) { | 
|  | 37 | +  console.log(`Running: ${cmd}, in ${path}`); | 
|  | 38 | +  try { | 
|  | 39 | +      execSync(cmd, { cwd: path, stdio: 'ignore' }); | 
|  | 40 | +  } catch (err) { | 
|  | 41 | +      console.error(`Test project scaffolding cmd error: ${err}`); | 
|  | 42 | +      throw err; | 
|  | 43 | +  } | 
|  | 44 | +} | 
|  | 45 | + | 
|  | 46 | +export function initProjectDir(projectDir: string, packageJsonContents: string, offline: boolean = true) { | 
|  | 47 | +  if (!fs.existsSync(projectDir)) { | 
|  | 48 | +    fs.mkdirSync(projectDir, { recursive: true }); | 
|  | 49 | +  } | 
|  | 50 | +  fs.writeFileSync(path.join(projectDir, PACKAGE_JSON_FILE), packageJsonContents, { flag: 'w+' }); | 
|  | 51 | +  fs.writeFileSync(path.join(projectDir, NPM_RC_FILE), NPM_RC_CONTENTS, { flag: 'w+' }); | 
|  | 52 | +  execCmdSync(`pnpm install ${offline ? '--offline ' : ''}--ignore-workspace`, projectDir); | 
|  | 53 | +} | 
0 commit comments