library-ts/node/files/PathReference.ts

151 lines
3.1 KiB
TypeScript

import { RegExpUtility } from "../../browser/text/RegExpUtitlity";
import { Files } from "./Files";
export class PathReference
{
_parentReference:PathReference;
_relative:boolean;
_path:string;
_cachedAbsolutePath:string;
constructor( absolutePath:string )
{
this._path = RegExpUtility.normalizePath( absolutePath );
this._relative = false;
this._parentReference = null;
}
createRelative( path:string )
{
path = RegExpUtility.normalizePath( path );
let link = new PathReference( path );
link._relative = true;
link._parentReference = this;
return link;
}
createRelativeFromAbsolute( otherAbsolutePath:string, isFile:boolean )
{
otherAbsolutePath = RegExpUtility.normalizePath( otherAbsolutePath );
if ( ! isFile )
{
let relativePath = RegExpUtility.createRelativeDirectoryPath( this.absolutePath, otherAbsolutePath );
return this.createRelative( relativePath )
}
let filePath = RegExpUtility.fileNameOrLastPath( otherAbsolutePath );
let parentPath = RegExpUtility.parentPath( otherAbsolutePath );
let relativePath = RegExpUtility.createRelativeDirectoryPath( this.absolutePath, parentPath );
relativePath = RegExpUtility.join( relativePath, filePath );
return this.createRelative( relativePath )
}
get isRelative()
{
return this._relative;
}
get relativePath()
{
return this._path;
}
get fileName()
{
return RegExpUtility.fileNameOrLastPath( this._path );
}
get fileNameWithoutExtension()
{
return RegExpUtility.trimFileTypeExtension( this.fileName );
}
pathEndsWith( extension:string )
{
return this._path.toLowerCase().endsWith( extension.toLowerCase() );
}
async isFileWithExtension( extension:string )
{
if ( ! this.pathEndsWith( extension ) )
{
return false;
}
return this.isFile();
}
get absolutePath()
{
if ( ! this._relative )
{
return this._path;
}
if ( this._cachedAbsolutePath )
{
return this._cachedAbsolutePath;
}
let cachedAbsolutePath = RegExpUtility.join( this._parentReference.absolutePath, this._path );
cachedAbsolutePath = RegExpUtility.resolvePath( cachedAbsolutePath );
this._cachedAbsolutePath = cachedAbsolutePath;
return this._cachedAbsolutePath;
}
async exists():Promise<boolean>
{
return Files.exists( this.absolutePath );
}
async isFile():Promise<boolean>
{
return Files.isFile( this.absolutePath );
}
async isDirectory():Promise<boolean>
{
return Files.isDirectory( this.absolutePath );
}
async isSymbolicLink():Promise<boolean>
{
return Files.isSymbolicLink( this.absolutePath );
}
async loadUTF8()
{
return Files.loadUTF8( this.absolutePath );
}
async loadHTML()
{
return Files.loadHTML( this.absolutePath );
}
async saveHTML( rootElement:Element )
{
return Files.saveHTML( this.absolutePath, rootElement );
}
async loadXML()
{
return Files.loadXML( this.absolutePath );
}
async loadJSON<T>()
{
return Files.loadJSON<T>( this.absolutePath );
}
}