@tobiastengler/create-relay-app
Version:
Easy configuration of Relay for existing projects
91 lines (90 loc) • 2.73 kB
JavaScript
import path from "path";
import fs from "fs/promises";
import { existsSync, lstatSync } from "fs";
import fsExtra from "fs-extra";
export class Filesystem {
getParent(filepath) {
return path.dirname(filepath);
}
isDirectory(directoryPath) {
if (!this.exists(directoryPath)) {
// If the path does not exist, we check that it doesn't
// have a file extension to determine whether it's a
// directory path.
const ext = path.extname(directoryPath);
return !ext;
}
return lstatSync(directoryPath).isDirectory();
}
isFile(filePath) {
if (!this.exists(filePath)) {
// If the path does not exist, we check if it has a
// file extension to determine whether it's a file or not.
const ext = path.extname(filePath);
return !!ext;
}
return lstatSync(filePath).isFile();
}
isSubDirectory(parent, dir) {
const relative = path.relative(parent, dir);
return !relative.startsWith("..") && !path.isAbsolute(relative);
}
copyFile(src, dest) {
return fs.copyFile(src, dest);
}
exists(filepath) {
return existsSync(filepath);
}
async readFromFile(filepath) {
try {
return await fs.readFile(filepath, "utf-8");
}
catch (error) {
throw new ReadFromFileError(filepath, error);
}
}
async writeToFile(filepath, content) {
try {
await fs.writeFile(filepath, content, "utf-8");
}
catch (error) {
throw new WriteToFileError(filepath, error);
}
}
async appendToFile(filepath, content) {
try {
await fs.appendFile(filepath, content, "utf-8");
}
catch (error) {
throw new AppendToFileError(filepath, error);
}
}
async createDirectory(directoryPath) {
try {
await fsExtra.mkdir(directoryPath, { recursive: true });
}
catch (error) {
throw new CreateDirectoryError(directoryPath, error);
}
}
}
class CreateDirectoryError extends Error {
constructor(path, cause) {
super(`Failed to create directory: ${path}`, { cause });
}
}
class WriteToFileError extends Error {
constructor(path, cause) {
super(`Failed to write to file: ${path}`, { cause });
}
}
class AppendToFileError extends Error {
constructor(path, cause) {
super(`Failed to append to file: ${path}`, { cause });
}
}
class ReadFromFileError extends Error {
constructor(path, cause) {
super(`Failed to read from file: ${path}`, { cause });
}
}