forked from siddharthvp/SDZeroBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
164 lines (142 loc) · 3.85 KB
/
utils.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import { bot, fs, log } from "./botbase";
import { spawn } from "child_process";
import { ENWIKI_DB_HOST, TOOLS_DB_HOST } from "./db";
import { REDIS_HOST } from "./redis";
export function readFile(file) {
try {
return fs.readFileSync(file).toString();
} catch (e) {
return null;
}
}
export function writeFile(file, text) {
return fs.writeFileSync(file, text);
}
export function createLogStream(file: string) {
let stream = fs.createWriteStream(file, {
flags: 'a',
encoding: 'utf8'
});
var logger = function (msg) {
let ts = new bot.date().format('YYYY-MM-DD HH:mm:ss');
let stringified;
if (typeof msg === 'string') {
stream.write(`[${ts}] ${msg}\n`);
} else if (stringified = stringifyObject(msg)) {
stream.write(`[${ts}] ${stringified}\n`);
} else {
stream.write(`[${ts}] [Non-stringifiable object!]\n`);
}
}
return function (...args) {
args.forEach(arg => logger(arg));
};
}
let runningInToolforge;
export function onToolforge(): boolean {
if (runningInToolforge !== undefined) {
return runningInToolforge;
}
// See https://phabricator.wikimedia.org/T192244
return runningInToolforge = fs.existsSync('/etc/wmcs-project');
}
/**
* Expand ~ to /data/project/sdzerobot
* or if running locally to current directory.
* This is asymmetric!
* @param path
*/
export function mapPath(path: string): string {
if (onToolforge()) {
return path.replace(/^~/, '/data/project/sdzerobot');
} else {
return path.replace(/^~/, __dirname);
}
}
const runningTunnels = [];
export async function createLocalSSHTunnel(host: string, localPort?: number, remotePort?: number) {
if (!onToolforge()) {
log(`[i] Spawning local SSH tunnel for ${host} ...`);
localPort = localPort || (
host === ENWIKI_DB_HOST ? 4711 :
host === TOOLS_DB_HOST ? 4712 :
host === REDIS_HOST ? 4713 :
null
);
remotePort = remotePort || (
host === ENWIKI_DB_HOST ? 3306 :
host === TOOLS_DB_HOST ? 3306 :
host === REDIS_HOST ? 6379 :
null
);
// relies on "ssh toolforge" command connecting successfully
runningTunnels.push(
spawn('ssh', ['-L', `${localPort}:${host}:${remotePort}`, 'toolforge'], {
detached: true
})
);
await bot.sleep(5000);
}
}
export function closeTunnels() {
runningTunnels.forEach(tunnel => tunnel.kill());
}
export function saveObject(filename, obj) {
fs.writeFileSync('./' + filename + '.json', JSON.stringify(obj, null, 2));
}
export function logObject(obj) {
return console.log(JSON.stringify(obj, null, 2));
}
// JSON.stringify throws on a cyclic object
export function stringifyObject(obj) {
try {
return JSON.stringify(obj, null, 2);
} catch (e) {
return null;
}
}
export function makeSentence(list: string[]) {
var text = '';
for (let i = 0; i < list.length; i++) {
text += list[i];
if (list.length - 2 === i) {
text += " and ";
} else if (list.length - 1 !== i) {
text += ", ";
}
}
return text;
}
export function arrayChunk(arr, size) {
var numChunks = Math.ceil(arr.length / size);
var result = new Array(numChunks);
for(var i = 0; i < numChunks; i++) {
result[i] = arr.slice(i * size, (i + 1) * size);
}
return result;
}
export function withIndices<T>(arr: Array<T>): Array<[number, T]> {
return arr.map((item, idx) => [idx, item]);
}
export function len(obj: Record<any, any> | Array<any>) {
if (Array.isArray(obj)) {
return obj.length;
} else {
return Object.keys(obj).length;
}
}
export function lowerFirst(str: string) {
return str[0].toLowerCase() + str.slice(1);
}
export function upperFirst(str: string) {
return str[0].toLowerCase() + str.slice(1);
}
export function setIntersection<T>(a: Set<T>, b: Set<T>): Set<T> {
return new Set([...a].filter(x => b.has(x)));
}
export function setUnion<T>(a: Set<T>, b: Set<T>): Set<T> {
return new Set([...a, ...b]);
}
export function setDifference<T>(a: Set<T>, b: Set<T>): Set<T> {
return new Set([...a].filter(x => !b.has(x)));
}