ph-dev-tools
Version:
Development Tools for PHibernate
76 lines (62 loc) • 2.15 kB
text/typescript
/**
* Created by Papa on 4/28/2016.
*/
import * as fs from 'fs';
import {Configuration} from "../options/Options";
import {normalizePath} from "../resolve/pathResolver";
export class PathBuilder {
dirExistanceMap:{[path:string]:boolean} = {};
generatedDirPath:string;
sourceDirPath:string;
workingDirPath:string;
usePathCache:boolean;
constructor(
private configuration:Configuration
) {
this.workingDirPath = normalizePath(process.cwd());
this.sourceDirPath = this.workingDirPath + '/' + normalizePath(configuration.source.dir);
this.generatedDirPath = normalizePath(configuration.generated.client.dir);
this.usePathCache = configuration.cacheGeneratedPaths ? true : false;
}
getGenerationPathForFile(
sourcePath:string
):string {
sourcePath = normalizePath(sourcePath);
let indexOfSourceDirInPath = sourcePath.indexOf(this.sourceDirPath);
if (indexOfSourceDirInPath !== 0) {
throw `Cannot generate file from source outside of root source dir`;
}
let sourceRelativePath = sourcePath.substr(this.sourceDirPath.length + 1);
return this.generatedDirPath + '/' + sourceRelativePath;
}
getFullPathToGeneratedSource( //
sourcePath:string //
):string {
let generatedPath = this.getGenerationPathForFile(sourcePath);
return this.workingDirPath + '/' + generatedPath;
}
setupFileForGeneration(
sourcePath:string
):string {
let generatedPath = this.getGenerationPathForFile(sourcePath);
let genPathFragments = generatedPath.split('/');
let currentPath = this.workingDirPath;
for (let i = 0; i < genPathFragments.length - 1; i++) {
currentPath += '/' + genPathFragments[i];
if (this.usePathCache && this.dirExistanceMap[currentPath]) {
continue;
}
let pathExists = fs.existsSync(currentPath);
if (!pathExists) {
fs.mkdirSync(currentPath);
} else {
let pathStat:fs.Stats = fs.statSync(currentPath);
if (!pathStat.isDirectory()) {
throw `'${currentPath}' is not a directory`;
}
}
this.dirExistanceMap[currentPath] = true;
}
return './' + generatedPath;
}
}