1 | import fs from 'fs'
|
2 | import glob from 'fast-glob'
|
3 | import path from 'path'
|
4 | import tmp from 'tmp'
|
5 |
|
6 | import { PermissionError } from './errors'
|
7 | import IUrlFetcher from './IUrlFetcher'
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | export default abstract class Doer {
|
14 |
|
15 | |
16 |
|
17 |
|
18 | folder: string
|
19 |
|
20 | |
21 |
|
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 |
|
33 |
|
34 |
|
35 |
|
36 | exists (subpath: string): boolean {
|
37 | return fs.existsSync(path.join(this.folder, subpath))
|
38 | }
|
39 |
|
40 | |
41 |
|
42 |
|
43 |
|
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 |
|
61 |
|
62 |
|
63 |
|
64 | read (subpath: string): string {
|
65 | return fs.readFileSync(path.join(this.folder, subpath), 'utf8')
|
66 | }
|
67 |
|
68 | |
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | write (subpath: string, content: string) {
|
75 | fs.writeFileSync(path.join(this.folder, subpath), content, 'utf8')
|
76 | }
|
77 |
|
78 | |
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | async fetch (url: string, options: any = { json: true }): Promise<any> {
|
85 | return this.urlFetcher.fetchUrl(url, options)
|
86 | }
|
87 | }
|