-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtempUtil.js
More file actions
60 lines (53 loc) · 1.75 KB
/
tempUtil.js
File metadata and controls
60 lines (53 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const crypto = require('crypto');
const os = require('os');
const path = require('path');
const cds = require('@sap/cds-dk');
const { fs } = cds.utils;
/**
* Use instance to ensure that tempFolders list is not global
* but local to each test
*
* const TempUtil = require('./utils/tempUtil');
* const tempUtil = new TempUtil(__filename);
*
* afterAll(async () => {
* await tempUtil.cleanUp();
* });
*
* Inside test:
* async () => {
* const tempFolder = await tempUtil.mkTempFolder();
*/
module.exports = class TempUtil {
long;
folderRndBytes;
constructor(fileName, { local = false, long = true, folderRndBytes = 4 } = {}) {
this.long = long;
this.folderRndBytes = folderRndBytes;
const random = this.getRandomString(2);
this.rootTempFolder = path.join(local ? path.dirname(fileName) : os.tmpdir(), `${long ? `${path.basename(fileName)}_` : ''}${random}.tmp`);
}
getRandomString(length) {
return crypto.randomBytes(length).toString('hex')
}
async mkTempFolder() {
const random = this.getRandomString(this.folderRndBytes);
const tempFolder = path.join(this.rootTempFolder, `${(this.long) ? 'test_' : ''}${random}`);
await fs.mkdirp(tempFolder);
return tempFolder;
}
async cleanUp() {
// FIXME chdir should not be necessary here
const cwd = path.normalize(process.cwd());
if (cwd.startsWith(this.rootTempFolder)) {
process.chdir(os.tmpdir());
}
await fs.rimraf(this.rootTempFolder);
}
async mkTempProject(src) {
const tempFolder = await this.mkTempFolder();
const dest = path.join(tempFolder, path.basename(src));
await fs.copy(src).to(dest);
return dest;
}
}