scriptable-testlab
Version:
A lightweight, efficient tool designed to manage and update scripts for Scriptable.
90 lines (74 loc) • 2.13 kB
text/typescript
import {AbsPath} from 'scriptable-abstract';
interface PathState {
components: string[];
}
const _DEFAULT_STATE: PathState = {
components: [],
};
export class MockPath extends AbsPath<PathState> {
constructor(components: string[] = []) {
super({
components: [...components],
});
}
get components(): string[] {
return [...this.state.components];
}
static parse(pathString: string): Path {
const normalized = pathString.replace(/\\/g, '/').replace(/^\/+/, '');
const components = normalized.split('/');
const result: string[] = [];
for (const component of components) {
if (!component || component === '.') {
continue;
}
if (component === '..') {
if (result.length > 0 && result[result.length - 1] !== '..') {
result.pop();
} else {
result.push('..');
}
continue;
}
result.push(component);
}
return new MockPath(result) as unknown as Path;
}
static join(...paths: string[]): Path {
const normalized = paths
.map(p => p.replace(/\\/g, '/'))
.filter(Boolean)
.join('/');
return MockPath.parse(normalized);
}
static documentsDirectory(): Path {
return MockPath.parse('~/Documents');
}
static libraryDirectory(): Path {
return MockPath.parse('~/Library');
}
static temporaryDirectory(): Path {
return MockPath.parse('~/tmp');
}
static cacheDirectory(): Path {
return MockPath.parse('~/Library/Caches');
}
toString(): string {
if (this.components.length === 0) return '';
return this.components.join('/');
}
appendComponent(component: string): Path {
const newComponents = [...this.components, component];
return new MockPath(newComponents) as unknown as Path;
}
appendingComponent(component: string): Path {
return this.appendComponent(component);
}
lastComponent(): string | null {
if (this.components.length === 0) return null;
return this.components[this.components.length - 1];
}
lastPathComponent(): string | null {
return this.lastComponent();
}
}