UNPKG

1.85 kBPlain TextView Raw
1import { _, env, inject, Logger } from "oly-core";
2import { join, resolve } from "path";
3import { FileService } from "./FileService";
4
5/**
6 * Provide a safe place to store files
7 */
8export class WorkspaceProvider {
9
10 /**
11 * Workspace directory.
12 */
13 @env("WORKSPACE_DIRECTORY")
14 public readonly directory: string = join(process.cwd(), "workspace");
15
16 /**
17 * Temporary directory.
18 */
19 @env("WORKSPACE_TMP")
20 public readonly tmp: string = ".tmp";
21
22 /**
23 * Remove workspace on start.
24 */
25 @env("WORKSPACE_DIRECTORY_RESET")
26 public readonly reset: boolean = false;
27
28 /**
29 *
30 */
31 @inject(Logger)
32 protected logger: Logger;
33
34 /**
35 *
36 */
37 @inject(FileService)
38 protected file: FileService;
39
40 /**
41 * Absolute path of tmp directory.
42 *
43 * @return {string}
44 */
45 get tmpDirectory() {
46 return this.join(this.tmp) + "/";
47 }
48
49 /**
50 * Get the absolute path of a workspace active.
51 *
52 * @param filename Filename or path replace to the workspace
53 */
54 public join(filename: string): string {
55 if (filename[0] === "/") { // already absolute, don't resolve!
56 return filename;
57 }
58 return resolve(this.directory, filename);
59 }
60
61 /**
62 * Generate a filepath. Useful for temp file or test.
63 *
64 * @return Random filepath
65 */
66 public rand(ext = ""): string {
67 return resolve(this.tmpDirectory, _.shortid() + ext);
68 }
69
70 /**
71 *
72 */
73 protected async onStart(): Promise<void> {
74 if (this.reset) {
75 await this.file.remove(this.directory);
76 }
77 await this.file.mkdirp(this.directory);
78 await this.file.remove(this.tmpDirectory);
79 await this.file.mkdirp(this.tmpDirectory);
80 }
81
82 /**
83 *
84 */
85 protected async onStop(): Promise<void> {
86 await this.file.remove(this.tmpDirectory);
87 if (this.reset) {
88 await this.file.remove(this.directory);
89 }
90 }
91}