UNPKG

2.23 kBPlain TextView Raw
1import fs from 'fs'
2import glob from 'fast-glob'
3import path from 'path'
4import tmp from 'tmp'
5
6import { PermissionError } from './errors'
7import IUrlFetcher from './IUrlFetcher'
8
9/**
10 * A utility base class for the `Parser` and `Generator` classes
11 * providing a convenient interface to a filesystem folder and HTTP requests
12 */
13export default abstract class Doer {
14
15 /**
16 * The directory to scan for relevant files
17 */
18 folder: string
19
20 /**
21 * The instance of IUrlFetcher to fetch URLs
22 */
23 protected readonly urlFetcher: IUrlFetcher
24
25 constructor (urlFetcher: IUrlFetcher, folder: string | undefined) {
26 if (!folder) folder = tmp.dirSync().name
27 this.folder = folder
28 this.urlFetcher = urlFetcher
29 }
30
31 /**
32 * Does a path exist within the project folder?
33 *
34 * @param subpath The path within the folder
35 */
36 exists (subpath: string): boolean {
37 return fs.existsSync(path.join(this.folder, subpath))
38 }
39
40 /**
41 * Get a list of paths that match a pattern in the project folder.
42 *
43 * @param pattern The glob pattern
44 */
45 glob (pattern: string | Array<string>): Array<string> {
46 try {
47 return glob.sync(pattern, {
48 cwd: this.folder
49 })
50 } catch (error) {
51 if (error.code === 'EACCES') {
52 throw new PermissionError(
53 `You do no have permission to access the whole of folder "${this.folder}". Are you sure you want Dockter to compile this folder?`
54 )
55 } else throw error
56 }
57 }
58
59 /**
60 * Read a file within the project folder
61 *
62 * @param subpath The path within the folder
63 */
64 read (subpath: string): string {
65 return fs.readFileSync(path.join(this.folder, subpath), 'utf8')
66 }
67
68 /**
69 * Write to a file within the project folder
70 *
71 * @param subpath The path within the folder
72 * @param content The content to write to the file
73 */
74 write (subpath: string, content: string) {
75 fs.writeFileSync(path.join(this.folder, subpath), content, 'utf8')
76 }
77
78 /**
79 * Fetch content from a URL
80 *
81 * @param url The URL to fetch
82 * @param options Request options
83 */
84 async fetch (url: string, options: any = { json: true }): Promise<any> {
85 return this.urlFetcher.fetchUrl(url, options)
86 }
87}