-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathmanager.ts
More file actions
195 lines (174 loc) · 5.81 KB
/
Copy pathmanager.ts
File metadata and controls
195 lines (174 loc) · 5.81 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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import * as util from '../util';
import * as vscode from 'vscode';
import * as cp from 'child_process';
import path = require('path');
export enum KnitWorkingDirectory {
documentDirectory = 'document directory',
workspaceRoot = 'workspace root',
}
export type DisposableProcess = cp.ChildProcessWithoutNullStreams & vscode.Disposable;
export interface IKnitRejection {
cp: DisposableProcess;
wasCancelled: boolean;
}
const rMarkdownOutput: vscode.OutputChannel = vscode.window.createOutputChannel('R Markdown');
interface IKnitArgs {
workingDirectory: string;
filePath: string;
fileName: string;
scriptArgs: Record<string, string>;
scriptPath: string;
rCmd?: string;
rOutputFormat?: string;
callback: (...args: unknown[]) => boolean;
onRejection?: (...args: unknown[]) => unknown;
}
export abstract class RMarkdownManager {
protected rPath: string = undefined;
protected rMarkdownOutput: vscode.OutputChannel = rMarkdownOutput;
// uri that are in the process of knitting
// so that we can't spam the knit/preview button
protected busyUriStore: Set<string> = new Set<string>();
protected getKnitDir(knitDir: string, docPath: string): string {
switch (knitDir) {
// the directory containing the R Markdown document
case KnitWorkingDirectory.documentDirectory: {
return path.dirname(docPath).replace(/\\/g, '/').replace(/['"]/g, '\\"');
}
// the root of the current workspace
case KnitWorkingDirectory.workspaceRoot: {
const currentDocumentWorkspace = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(docPath) ?? vscode.window.activeTextEditor?.document?.uri)?.uri?.fsPath ?? undefined;
return currentDocumentWorkspace.replace(/\\/g, '/').replace(/['"]/g, '\\"');
}
// the working directory of the attached terminal, NYI
// case 'current directory': {
// return NULL
// }
default: return undefined;
}
}
protected async knitDocument(args: IKnitArgs, token?: vscode.CancellationToken, progress?: vscode.Progress<unknown>): Promise<DisposableProcess | IKnitRejection> {
// vscode.Progress auto-increments progress, so we use this
// variable to set progress to a specific number
let currentProgress = 0;
let printOutput = true;
return await new Promise<DisposableProcess>(
(resolve, reject) => {
const scriptArgs = args.scriptArgs;
const scriptPath = args.scriptPath;
const fileName = args.fileName;
const processArgs = [
`--silent`,
`--slave`,
`--no-save`,
`--no-restore`,
`-f`,
`${scriptPath}`
];
const processOptions: cp.SpawnOptions = {
env: {
...process.env,
...scriptArgs
},
cwd: args.workingDirectory,
};
let childProcess: DisposableProcess;
try {
childProcess = util.asDisposable(
cp.spawn(
`${this.rPath}`,
processArgs,
processOptions
),
() => {
if (childProcess.kill('SIGKILL')) {
rMarkdownOutput.appendLine('[VSC-R] terminating R process');
printOutput = false;
}
}
);
progress.report({
increment: 0,
message: '0%'
});
} catch (e: unknown) {
console.warn(`[VSC-R] error: ${e as string}`);
reject({ cp: childProcess, wasCancelled: false });
}
this.rMarkdownOutput.appendLine(`[VSC-R] ${fileName} process started`);
if (args.rCmd) {
this.rMarkdownOutput.appendLine(`==> ${args.rCmd}`);
}
childProcess.stdout.on('data',
(data: Buffer) => {
const dat = data.toString('utf8');
if (printOutput) {
this.rMarkdownOutput.appendLine(dat);
}
const percentRegex = /[0-9]+(?=%)/g;
const percentRegOutput = dat.match(percentRegex);
if (percentRegOutput) {
for (const item of percentRegOutput) {
const perc = Number(item);
progress.report(
{
increment: perc - currentProgress,
message: `${perc}%`
}
);
currentProgress = perc;
}
}
if (token?.isCancellationRequested) {
resolve(childProcess);
} else {
if (args.callback(dat, childProcess)) {
resolve(childProcess);
}
}
}
);
childProcess.stderr.on('data', (data: Buffer) => {
const dat = data.toString('utf8');
if (printOutput) {
this.rMarkdownOutput.appendLine(dat);
}
// for some reason, some knitting formats have the output
// of the file url in the stderr stream
if (args.callback(dat, childProcess)) {
resolve(childProcess);
}
});
childProcess.on('exit', (code, signal) => {
this.rMarkdownOutput.appendLine(`[VSC-R] ${fileName} process exited ` +
(signal ? `from signal '${signal}'` : `with exit code ${code}`));
if (code !== 0) {
reject({ cp: childProcess, wasCancelled: false });
}
});
token?.onCancellationRequested(() => {
reject({ cp: childProcess, wasCancelled: true });
});
}
);
}
protected async knitWithProgress(args: IKnitArgs): Promise<DisposableProcess> {
let childProcess: DisposableProcess = undefined;
await util.doWithProgress(async (token: vscode.CancellationToken, progress: vscode.Progress<unknown>) => {
childProcess = await this.knitDocument(args, token, progress) as DisposableProcess;
},
vscode.ProgressLocation.Notification,
`Knitting ${args.fileName} ${args.rOutputFormat ? 'to ' + args.rOutputFormat : ''} `,
true
).catch((rejection: IKnitRejection) => {
if (!rejection.wasCancelled) {
void vscode.window.showErrorMessage('There was an error in knitting the document. Please check the R Markdown output stream.');
this.rMarkdownOutput.show(true);
}
// this can occur when a successfuly knitted document is later altered (while still being previewed) and subsequently fails to knit
args?.onRejection?.(args.filePath, rejection);
rejection.cp?.dispose();
});
return childProcess;
}
}