forked from sindresorhus/shell-history
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (54 loc) · 1.47 KB
/
Copy pathindex.js
File metadata and controls
69 lines (54 loc) · 1.47 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
61
62
63
64
65
66
67
68
69
import os from 'os';
import fs from 'fs';
import path from 'path';
import childProcess from 'child_process';
export function parseShellHistory(string) {
const reBashHistory = /^: \d+:0;/;
return string.trim().split('\n').map(line => {
if (reBashHistory.test(line)) {
return line.split(';').slice(1).join(';');
}
// ZSH just places one command on each line
return line;
});
}
export function shellHistoryPath({extraPaths = []} = {}) {
if (process.env.HISTFILE) {
return process.env.HISTFILE;
}
const homeDir = os.homedir();
const paths = new Set([
path.join(homeDir, '.bash_history'),
path.join(homeDir, '.zsh_history'),
path.join(homeDir, '.history')
]);
for (const path of extraPaths) {
paths.add(path);
}
const filterdHistoryPath = () => {
let largestFile;
let size = 0;
for (const path of paths) {
if (!fs.existsSync(path)) {
continue;
}
if (fs.statSync(path).size > size) {
size = fs.statSync(path).size;
largestFile = path;
}
}
return largestFile;
};
return filterdHistoryPath();
}
export function shellHistory(options = {}) {
if (process.platform === 'win32') {
const historyPath = shellHistoryPath(options);
if (historyPath) {
return parseShellHistory(fs.readFileSync(historyPath, 'utf8'));
}
const {stdout} = childProcess.spawnSync('doskey', ['/history'], {encoding: 'utf8'});
return stdout.trim().split('\r\n');
}
return parseShellHistory(fs.readFileSync(shellHistoryPath(options), 'utf8'));
}