|
| 1 | +import { CreatePlan, DestroyPlan, RefreshContext, Resource, ResourceSettings, getPty } from 'codify-plugin-lib'; |
| 2 | +import { ResourceConfig } from 'codify-schemas'; |
| 3 | + |
| 4 | +import { codifySpawn } from '../../../utils/codify-spawn.js'; |
| 5 | +import schema from './pip-sync-schema.json' |
| 6 | +import { RequirementFilesParameter } from './requirement-files-parameter.js'; |
| 7 | + |
| 8 | +export interface PipSyncConfig extends ResourceConfig { |
| 9 | + requirementFiles: string[]; |
| 10 | + virtualEnv?: string; |
| 11 | + cwd?: string; |
| 12 | +} |
| 13 | + |
| 14 | +export class PipSync extends Resource<PipSyncConfig> { |
| 15 | + getSettings(): ResourceSettings<PipSyncConfig> { |
| 16 | + return { |
| 17 | + id: 'pip-sync', |
| 18 | + schema, |
| 19 | + parameterSettings: { |
| 20 | + requirementFiles: { type: 'stateful', definition: new RequirementFilesParameter() }, |
| 21 | + virtualEnv: { type: 'directory', setting: true }, |
| 22 | + cwd: { type: 'directory', setting: true } |
| 23 | + }, |
| 24 | + dependencies: ['pyenv', 'pip', 'venv-project', 'virtualenv-project', 'virtualenv'], |
| 25 | + allowMultiple: { |
| 26 | + identifyingParameters: ['virtualEnv'], |
| 27 | + } |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + async refresh(parameters: Partial<PipSyncConfig>, context: RefreshContext<PipSyncConfig>): Promise<Partial<PipSyncConfig> | Partial<PipSyncConfig>[] | null> { |
| 32 | + const pty = getPty() |
| 33 | + |
| 34 | + const { status: pipStatus } = await pty.spawnSafe(PipSync.withVirtualEnv('which pip', parameters.virtualEnv), { cwd: parameters.cwd ?? undefined }); |
| 35 | + if (pipStatus === 'error') { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + const { status: pipSyncStatus } = await pty.spawnSafe(PipSync.withVirtualEnv('which pip-sync', parameters.virtualEnv), { cwd: parameters.cwd ?? undefined }) |
| 40 | + return pipSyncStatus === 'error' ? null : parameters; |
| 41 | + } |
| 42 | + |
| 43 | + async create(plan: CreatePlan<PipSyncConfig>): Promise<void> { |
| 44 | + await codifySpawn(PipSync.withVirtualEnv('pip install pip-tools', plan.desiredConfig.virtualEnv), { cwd: plan.desiredConfig.cwd ?? undefined }) |
| 45 | + } |
| 46 | + |
| 47 | + async destroy(plan: DestroyPlan<PipSyncConfig>): Promise<void> { |
| 48 | + await codifySpawn(PipSync.withVirtualEnv('pip uninstall -y pip-tools', plan.currentConfig.virtualEnv), { cwd: plan.currentConfig.cwd ?? undefined }) |
| 49 | + } |
| 50 | + |
| 51 | + static withVirtualEnv(command: string, virtualEnv?: string, ): string { |
| 52 | + if (!virtualEnv) { |
| 53 | + return command; |
| 54 | + } |
| 55 | + |
| 56 | + return `( set -e; source ${virtualEnv}/bin/activate; ${command}; deactivate )`; |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments