All files / src/services auxClasspath.ts

31.36% Statements 69/220
100% Branches 1/1
7.69% Functions 1/13
31.36% Lines 69/220

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 2211x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                       1x 1x                 1x 1x                         1x 1x             1x 1x           1x 1x                               1x 1x                                 1x 1x                 1x 1x           1x 1x       1x 1x                                                                                       1x 1x        
import { existsSync, statSync, readFileSync, writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { spawn, type ChildProcess } from 'child_process';
import { getPMDAutoAuxClasspath } from '../config';
 
export interface AuxClasspathInfo {
  classpath: string;
  source?: 'maven' | 'gradle';
  error?: string;
}
 
interface BuildTarget {
  kind: 'maven' | 'gradle';
  path: string;
}
 
interface CacheEntry {
  buildFile: string;
  mtimeMs: number;
  info: AuxClasspathInfo;
}
 
const BUILD_TIMEOUT = 120_000;
 
const GRADLE_INIT_SCRIPT = `
gradle.allprojects { proj ->
    if (proj == gradle.rootProject) {
        proj.tasks.register('_printRuntimeClasspath') {
            doLast {
                if (proj.plugins.hasPlugin('java')) {
                    def main = proj.sourceSets.findByName('main')
                    if (main != null) {
                        println main.runtimeClasspath.asPath
                    }
                }
            }
        }
    }
}
`;
 
export class AuxClasspathResolver {
  private cache = new Map<string, CacheEntry>();
  private inflight = new Map<string, Promise<AuxClasspathInfo>>();
 
  async resolve(workingDir: string): Promise<AuxClasspathInfo> {
    if (!getPMDAutoAuxClasspath()) {
      return { classpath: '' };
    }
    const build = this.detectBuildFile(workingDir);
    if (!build) {
      return { classpath: '' };
    }
    const mtime = this.statMtime(build.path);
    const cached = this.cache.get(workingDir);
    if (cached && cached.buildFile === build.path && cached.mtimeMs === mtime) {
      return cached.info;
    }
    const pending = this.inflight.get(workingDir);
    if (pending) {
      return pending;
    }
    const running = this.runBuild(workingDir, build)
      .then((info) => {
        this.cache.set(workingDir, { buildFile: build.path, mtimeMs: mtime, info });
        return info;
      })
      .finally(() => {
        this.inflight.delete(workingDir);
      });
    this.inflight.set(workingDir, running);
    return running;
  }
 
  clear(workingDir?: string): void {
    if (workingDir) {
      this.cache.delete(workingDir);
      this.inflight.delete(workingDir);
    } else {
      this.cache.clear();
      this.inflight.clear();
    }
  }
 
  private detectBuildFile(workingDir: string): BuildTarget | null {
    const candidates: BuildTarget[] = [
      { kind: 'maven', path: join(workingDir, 'pom.xml') },
      { kind: 'gradle', path: join(workingDir, 'build.gradle') },
      { kind: 'gradle', path: join(workingDir, 'build.gradle.kts') },
    ];
    for (const candidate of candidates) {
      if (existsSync(candidate.path)) {
        return candidate;
      }
    }
    return null;
  }
 
  private statMtime(file: string): number {
    try {
      return statSync(file).mtimeMs;
    } catch {
      return 0;
    }
  }
 
  private runBuild(workingDir: string, build: BuildTarget): Promise<AuxClasspathInfo> {
    if (build.kind === 'maven') {
      return this.runMaven(workingDir);
    }
    return this.runGradle(workingDir);
  }
 
  private async runMaven(workingDir: string): Promise<AuxClasspathInfo> {
    const outputFile = join(tmpdir(), `pmd-auxcp-${process.pid}-${Date.now()}.txt`);
    const cmd = this.resolveTool(workingDir, ['mvnw.cmd', 'mvnw'], isWindows() ? 'mvn.cmd' : 'mvn');
    try {
      const args = ['-B', '-q', `-Dmdep.outputFile=${outputFile}`, 'dependency:build-classpath'];
      await this.exec(cmd, args, workingDir);
      const cp = existsSync(outputFile) ? readFileSync(outputFile, 'utf8').trim() : '';
      return { classpath: cp, source: 'maven' };
    } catch (err) {
      return { classpath: '', source: 'maven', error: err instanceof Error ? err.message : String(err) };
    } finally {
      if (existsSync(outputFile)) {
        unlinkSync(outputFile);
      }
    }
  }
 
  private async runGradle(workingDir: string): Promise<AuxClasspathInfo> {
    const cmd = this.resolveTool(workingDir, ['gradlew.bat', 'gradlew'], isWindows() ? 'gradle.bat' : 'gradle');
    const initScript = join(tmpdir(), `pmd-auxcp-${process.pid}-${Date.now()}.gradle`);
    writeFileSync(initScript, GRADLE_INIT_SCRIPT, 'utf8');
    try {
      const args = ['-q', '-I', initScript, '_printRuntimeClasspath'];
      const output = await this.exec(cmd, args, workingDir);
      const cp = this.lastNonEmptyLine(output);
      return { classpath: cp, source: 'gradle' };
    } catch (err) {
      return { classpath: '', source: 'gradle', error: err instanceof Error ? err.message : String(err) };
    } finally {
      if (existsSync(initScript)) {
        unlinkSync(initScript);
      }
    }
  }
 
  private resolveTool(workingDir: string, wrapperNames: string[], systemName: string): string {
    for (const name of wrapperNames) {
      const wrapper = join(workingDir, name);
      if (existsSync(wrapper)) {
        return wrapper;
      }
    }
    return systemName;
  }
 
  private quoteCmdArg(arg: string): string {
    if (/^[\w.,:=/@%\\+-]+$/.test(arg)) {
      return arg;
    }
    return `"${arg.replace(/"/g, '""')}"`;
  }
 
  private lastNonEmptyLine(output: string): string {
    const lines = output.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
    return lines.length > 0 ? lines[lines.length - 1] : '';
  }
 
  private exec(cmd: string, args: string[], cwd: string): Promise<string> {
    return new Promise((resolve, reject) => {
      let proc: ChildProcess | null = null;
      let stdout = '';
      let stderr = '';
      const timer = setTimeout(() => {
        if (proc) {
          proc.kill();
        }
        reject(new Error(`Command timed out after ${BUILD_TIMEOUT}ms: ${cmd}`));
      }, BUILD_TIMEOUT);
      try {
        if (isWindows() && /\.(cmd|bat)$/i.test(cmd)) {
          const inner = `${this.quoteCmdArg(cmd)} ${args.map((arg) => this.quoteCmdArg(arg)).join(' ')}`;
          proc = spawn('cmd.exe', ['/d', '/s', '/c', `"${inner}"`], {
            cwd,
            windowsHide: true,
            windowsVerbatimArguments: true,
          });
        } else {
          proc = spawn(cmd, args, { cwd, windowsHide: true });
        }
      } catch (err) {
        clearTimeout(timer);
        reject(err);
        return;
      }
      const child = proc;
      child.stdout?.on('data', (data: Buffer) => { stdout += data.toString(); });
      child.stderr?.on('data', (data: Buffer) => { stderr += data.toString(); });
      child.on('error', (err) => {
        clearTimeout(timer);
        reject(err);
      });
      child.on('close', (code) => {
        clearTimeout(timer);
        if (code === 0) {
          resolve(stdout);
        } else {
          reject(new Error(`${cmd} exited with code ${code}: ${(stderr || stdout).trim()}`));
        }
      });
    });
  }
}
 
function isWindows(): boolean {
  return process.platform === 'win32';
}