import Path from './Path'; import * as pathutils from 'path'; export default class PathHelper { /** 检测目录是否是忽略目录 */ static CheckPathDirFirst(p: string, c:string[] = [ "_", "~"]) { var p = p.replace(/\\/g, '/'); var arr = p.split('/'); for(var item of arr) { for(var ci of c) { if(item.startsWith(ci)) { return true; } } } return false; } // 获取导入路径 public static GetImportPath(curPath: string , importPath: string ):string { var path: string = this.RelativePath(curPath, importPath); path = this.ChangeExtension(path, ""); return path; } // 绝对路径 转 相对路径 public static RelativePath(absolutePath: string , relativeTo:string ):string { absolutePath = absolutePath.replace(/\\/g, '/'); relativeTo = relativeTo.replace(/\\/g, '/'); //from - www.cnphp6.com let absoluteDirectories: string[] = absolutePath.split('/'); let relativeDirectories: string[] = relativeTo.split('/'); //Get the shortest of the two paths let length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length : relativeDirectories.length; //Use to determine where in the loop we exited let lastCommonRoot: number = -1; let index: number; //Find common root for (index = 0; index < length; index++) if (absoluteDirectories[index] == relativeDirectories[index]) lastCommonRoot = index; else break; //If we didn't find a common prefix then throw if (lastCommonRoot == -1) throw new Error("Paths do not have a common base"); //Build up the relative path var relativePath = []; //Add on the .. for (index = lastCommonRoot + 2; index < absoluteDirectories.length; index++) if (absoluteDirectories[index].length > 0) relativePath.push("../"); if(lastCommonRoot + 3 == relativeDirectories.length) { relativePath.push("./"); } //Add on the folders for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) relativePath.push(relativeDirectories[index] + "/"); relativePath.push(relativeDirectories[relativeDirectories.length - 1]); return relativePath.join(''); } public static CheckPath(path: string, isFile: boolean = true) { if(isFile) path = path.substr(0,path.lastIndexOf('/')); let dirs: string[] = path.split('/'); let target = ""; let first = true; for(let dir of dirs) { if(first){ first = false; target += dir; continue; } if(!dir) continue; target += "/" + dir; if(!Path.Exists(target)) { Path.CreateDirectory(target); } } } public static ChangeExtension( p:string, ext:string): string { var e = pathutils.extname(p); if(e != "") { var i = p.lastIndexOf(e); return p.substring(0, i) + ext; } else { return p + ext; } } }