38 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2020-05-15 16:53:45 +02:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of console-app which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
2020-05-09 19:51:43 +02:00
import fs from 'fs-extra';
import { TypeValidation } from './TypeValidation';
export class PathType extends TypeValidation {
2020-05-09 21:30:37 +02:00
public get string_type (): 'string'|'number'|'boolean'|'object' {
2020-05-09 19:51:43 +02:00
return 'string';
}
2020-05-18 11:03:49 +02:00
public get persistent_type (): 'string'|'number'|'boolean'|'array' {
return 'string';
}
2020-05-09 19:51:43 +02:00
public async to_type (value: unknown): Promise<unknown> {
if (typeof value !== 'string')
2020-05-09 21:30:37 +02:00
throw new Error (`invalid type for ${this.option_type}`);
2020-07-24 08:18:36 +02:00
const escaped = value.replace (/\\$/u, '')
.replace (/"$/u, '');
2020-07-24 08:18:36 +02:00
if (!await fs.pathExists (escaped))
2020-05-09 19:51:43 +02:00
throw new Error ('path does not exist');
2020-05-09 21:30:37 +02:00
if (this.option_type === 'path')
2020-07-24 08:18:36 +02:00
return escaped;
2020-05-09 19:51:43 +02:00
2020-07-24 08:18:36 +02:00
const stat = await fs.stat (escaped);
2020-05-09 21:30:37 +02:00
if (stat.isDirectory () === (this.option_type === 'folder'))
2020-07-24 08:18:36 +02:00
return escaped;
2020-05-09 19:51:43 +02:00
throw new Error ('cannot assign folder to file');
}
}