-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathcache.js
75 lines (67 loc) · 1.98 KB
/
cache.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict';
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const remote = require('./remote');
const Platform = require('./platform');
const index = require('./index');
const utils = require('./utils');
class Cache {
constructor(config) {
// TODO: replace this with a private field when it reaches enough maturity
// https://github.com/tc39/proposal-class-fields#private-fields
this.config = config;
this.cacheFolder = path.join(config.cache, 'cache');
}
lastUpdated() {
return fs.stat(this.cacheFolder);
}
getPage(page) {
let preferredPlatform = Platform.getPreferredPlatformFolder(this.config);
const preferredLanguage = process.env.LANG || 'en';
return index.findPage(page, preferredPlatform, preferredLanguage)
.then((folder) => {
if (!folder) {
return;
}
let filePath = path.join(this.cacheFolder, folder, page + '.md');
return fs.readFile(filePath, 'utf8');
})
.catch((err) => {
console.error(err);
});
}
clear() {
return fs.remove(this.cacheFolder);
}
update() {
// Temporary folder path: /tmp/tldr/{randomName}
const tempFolder = path.join(os.tmpdir(), 'tldr', utils.uniqueId());
// Downloading fresh copy
return Promise.all([
// Create new temporary folder
fs.ensureDir(tempFolder),
fs.ensureDir(this.cacheFolder)
])
.then(() => {
// Download and extract cache data to temporary folder
return remote.download(tempFolder);
})
.then(() => {
// Copy data to cache folder
return fs.copy(tempFolder, this.cacheFolder);
})
.then(() => {
return Promise.all([
// Remove temporary folder
fs.remove(tempFolder),
index.rebuildPagesIndex()
]);
})
// eslint-disable-next-line no-unused-vars
.then(([_, shortIndex]) => {
return shortIndex;
});
}
}
module.exports = Cache;