1 | import path from 'path';
|
2 | import fs from 'fs';
|
3 |
|
4 | import { StrykerOptions } from '@stryker-mutator/api/core';
|
5 | import { Logger } from '@stryker-mutator/api/logging';
|
6 | import { commonTokens, tokens } from '@stryker-mutator/api/plugin';
|
7 | import { Disposable } from 'typed-inject';
|
8 |
|
9 | import { fileUtils } from './file-utils.js';
|
10 | import { objectUtils } from './object-utils.js';
|
11 |
|
12 | export class TemporaryDirectory implements Disposable {
|
13 | private readonly temporaryDirectory: string;
|
14 | private isInitialized = false;
|
15 | public removeDuringDisposal: boolean;
|
16 |
|
17 | public static readonly inject = tokens(commonTokens.logger, commonTokens.options);
|
18 | constructor(private readonly log: Logger, options: StrykerOptions) {
|
19 | this.temporaryDirectory = path.resolve(options.tempDirName);
|
20 | this.removeDuringDisposal = options.cleanTempDir;
|
21 | }
|
22 |
|
23 | public async initialize(): Promise<void> {
|
24 | this.log.debug('Using temp directory "%s"', this.temporaryDirectory);
|
25 | await fs.promises.mkdir(this.temporaryDirectory, { recursive: true });
|
26 | this.isInitialized = true;
|
27 | }
|
28 |
|
29 | public getRandomDirectory(prefix: string): string {
|
30 | return path.resolve(this.temporaryDirectory, `${prefix}${objectUtils.random()}`);
|
31 | }
|
32 |
|
33 | |
34 |
|
35 |
|
36 |
|
37 | public async createDirectory(name: string): Promise<void> {
|
38 | if (!this.isInitialized) {
|
39 | throw new Error('initialize() was not called!');
|
40 | }
|
41 | await fs.promises.mkdir(path.resolve(this.temporaryDirectory, name), { recursive: true });
|
42 | }
|
43 |
|
44 | |
45 |
|
46 |
|
47 | public async dispose(): Promise<void> {
|
48 | if (!this.isInitialized) {
|
49 | throw new Error('initialize() was not called!');
|
50 | }
|
51 | if (this.removeDuringDisposal) {
|
52 | this.log.debug('Deleting stryker temp directory %s', this.temporaryDirectory);
|
53 | try {
|
54 | await fileUtils.deleteDir(this.temporaryDirectory);
|
55 | } catch (e) {
|
56 | this.log.info(`Failed to delete stryker temp directory ${this.temporaryDirectory}`);
|
57 | }
|
58 | }
|
59 | }
|
60 | }
|