UNPKG

2.45 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const fs_1 = __importDefault(require("fs"));
7const fast_glob_1 = __importDefault(require("fast-glob"));
8const path_1 = __importDefault(require("path"));
9const tmp_1 = __importDefault(require("tmp"));
10const errors_1 = require("./errors");
11/**
12 * A utility base class for the `Parser` and `Generator` classes
13 * providing a convenient interface to a filesystem folder and HTTP requests
14 */
15class Doer {
16 constructor(urlFetcher, folder) {
17 if (!folder)
18 folder = tmp_1.default.dirSync().name;
19 this.folder = folder;
20 this.urlFetcher = urlFetcher;
21 }
22 /**
23 * Does a path exist within the project folder?
24 *
25 * @param subpath The path within the folder
26 */
27 exists(subpath) {
28 return fs_1.default.existsSync(path_1.default.join(this.folder, subpath));
29 }
30 /**
31 * Get a list of paths that match a pattern in the project folder.
32 *
33 * @param pattern The glob pattern
34 */
35 glob(pattern) {
36 try {
37 return fast_glob_1.default.sync(pattern, {
38 cwd: this.folder
39 });
40 }
41 catch (error) {
42 if (error.code === 'EACCES') {
43 throw new errors_1.PermissionError(`You do no have permission to access the whole of folder "${this.folder}". Are you sure you want Dockter to compile this folder?`);
44 }
45 else
46 throw error;
47 }
48 }
49 /**
50 * Read a file within the project folder
51 *
52 * @param subpath The path within the folder
53 */
54 read(subpath) {
55 return fs_1.default.readFileSync(path_1.default.join(this.folder, subpath), 'utf8');
56 }
57 /**
58 * Write to a file within the project folder
59 *
60 * @param subpath The path within the folder
61 * @param content The content to write to the file
62 */
63 write(subpath, content) {
64 fs_1.default.writeFileSync(path_1.default.join(this.folder, subpath), content, 'utf8');
65 }
66 /**
67 * Fetch content from a URL
68 *
69 * @param url The URL to fetch
70 * @param options Request options
71 */
72 async fetch(url, options = { json: true }) {
73 return this.urlFetcher.fetchUrl(url, options);
74 }
75}
76exports.default = Doer;