Skip to content

Fix more uncaught errors #1625

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export class AtelierAPI {
if (
parts.length === 2 &&
(config("intersystems.servers").has(parts[0].toLowerCase()) ||
vscode.workspace.workspaceFolders.find(
vscode.workspace.workspaceFolders?.find(
(ws) => ws.uri.scheme === "file" && ws.name.toLowerCase() === parts[0].toLowerCase()
))
) {
Expand Down
32 changes: 18 additions & 14 deletions src/commands/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export async function importFile(
ignoreConflict?: boolean,
skipDeplCheck = false
): Promise<any> {
if (!file) return;
const api = new AtelierAPI(file.uri);
if (!api.active) return;
if (file.name.split(".").pop().toLowerCase() === "cls" && !skipDeplCheck) {
Expand Down Expand Up @@ -261,6 +262,8 @@ export async function loadChanges(files: (CurrentTextFile | CurrentBinaryFile)[]
}

export async function compile(docs: (CurrentTextFile | CurrentBinaryFile)[], flags?: string): Promise<any> {
docs = docs.filter(notNull);
if (!docs.length) return;
const wsFolder = vscode.workspace.getWorkspaceFolder(docs[0].uri);
const conf = vscode.workspace.getConfiguration("objectscript", wsFolder || docs[0].uri);
flags = flags || conf.get("compileFlags");
Expand Down Expand Up @@ -379,9 +382,7 @@ export async function compileOnly(askFlags = false, document?: vscode.TextDocume
export async function namespaceCompile(askFlags = false): Promise<any> {
const api = new AtelierAPI();
const fileTypes = ["*.CLS", "*.MAC", "*.INC", "*.BAS"];
if (!config("conn").active) {
throw new Error(`No Active Connection`);
}
if (!api.active) return;
const confirm = await vscode.window.showWarningMessage(
`Compiling all files in namespace ${api.ns} might be expensive. Are you sure you want to proceed?`,
"Cancel",
Expand Down Expand Up @@ -437,18 +438,20 @@ async function importFiles(files: vscode.Uri[], noCompile = false) {
rateLimiter.call(async () => {
return vscode.workspace.fs
.readFile(uri)
.then((contentBytes) => {
if (isText(uri.path.split("/").pop(), Buffer.from(contentBytes))) {
const textFile = currentFileFromContent(uri, new TextDecoder().decode(contentBytes));
toCompile.push(textFile);
return textFile;
} else {
return currentFileFromContent(uri, Buffer.from(contentBytes));
.then((contentBytes) =>
currentFileFromContent(
uri,
isText(uri.path.split("/").pop(), Buffer.from(contentBytes))
? new TextDecoder().decode(contentBytes)
: Buffer.from(contentBytes)
)
)
.then((curFile) => {
if (curFile) {
if (typeof curFile.content == "string") toCompile.push(curFile); // Only compile text files
return importFile(curFile).then(() => outputChannel.appendLine("Imported file: " + curFile.fileName));
}
})
.then((curFile) =>
importFile(curFile).then(() => outputChannel.appendLine("Imported file: " + curFile.fileName))
);
});
})
)
);
Expand All @@ -460,6 +463,7 @@ async function importFiles(files: vscode.Uri[], noCompile = false) {
}

export async function importFolder(uri: vscode.Uri, noCompile = false): Promise<any> {
if (!(uri instanceof vscode.Uri)) return;
if (filesystemSchemas.includes(uri.scheme)) return; // Not for server-side URIs
if ((await vscode.workspace.fs.stat(uri)).type != vscode.FileType.Directory) {
return importFiles([uri], noCompile);
Expand Down
1 change: 1 addition & 0 deletions src/commands/connectFolderToServerNamespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export async function connectFolderToServerNamespace(): Promise<void> {
items.length === 1 && !items[0].detail
? items[0]
: await vscode.window.showQuickPick(items, { title: "Pick a folder" });
if (!pick) return;
const folder = vscode.workspace.workspaceFolders.find((el) => el.name === pick.label);
// Get user's choice of server
const options: vscode.QuickPickOptions = {};
Expand Down
97 changes: 58 additions & 39 deletions src/commands/studio.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from "vscode";
import { AtelierAPI } from "../api";
import { iscIcon } from "../extension";
import { outputChannel, outputConsole, notIsfs, handleError, openLowCodeEditors } from "../utils";
import { outputChannel, outputConsole, notIsfs, handleError, openLowCodeEditors, stringifyError } from "../utils";
import { DocumentContentProvider } from "../providers/DocumentContentProvider";
import { UserAction } from "../api/atelier";
import { isfsDocumentName } from "../providers/FileSystemProvider/FileSystemProvider";
Expand Down Expand Up @@ -113,7 +113,7 @@ export class StudioActions {
);
}

public processUserAction(userAction: UserAction): Thenable<any> {
public async processUserAction(userAction: UserAction): Promise<any> {
const serverAction = userAction.action;
const { target, errorText } = userAction;
if (errorText !== "") {
Expand All @@ -128,7 +128,22 @@ export class StudioActions {
return vscode.window
.showWarningMessage(target, { modal: true }, "Yes", "No")
.then((answer) => (answer === "Yes" ? "1" : answer === "No" ? "0" : "2"));
case 2: // Run a CSP page/Template. The Target is the full path of CSP page/template on the connected server
case 2: {
// Run a CSP page/Template. The Target is the full path of CSP page/template on the connected server

// Do this ourself instead of using our new getCSPToken wrapper function, because that function reuses tokens which causes issues with
// webview when server is 2020.1.1 or greater, as session cookie scope is typically Strict, meaning that the webview
// cannot store the cookie. Consequence is web sessions may build up (they get a 900 second timeout)
const cspchd = await this.api
.actionQuery("select %Atelier_v1_Utils.General_GetCSPToken(?) token", [target])
.then((data) => data.result.content[0].token)
.catch((error) => {
outputChannel.appendLine(
`Failed to construct a CSP session for server-side source control User Action 2 (show a CSP page) on page '${target}': ${stringifyError(error)}\nReturning answer 2 (Cancel)`
);
outputChannel.show(true);
});
if (!cspchd) return "2";
return new Promise((resolve) => {
let answer = "2";
const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
Expand Down Expand Up @@ -157,16 +172,10 @@ export class StudioActions {
const url = new URL(
`${config.https ? "https" : "http"}://${config.host}:${config.port}${config.pathPrefix}${target}`
);

// Do this ourself instead of using our new getCSPToken wrapper function, because that function reuses tokens which causes issues with
// webview when server is 2020.1.1 or greater, as session cookie scope is typically Strict, meaning that the webview
// cannot store the cookie. Consequence is web sessions may build up (they get a 900 second timeout)
this.api.actionQuery("select %Atelier_v1_Utils.General_GetCSPToken(?) token", [target]).then((tokenObj) => {
const csptoken = tokenObj.result.content[0].token;
url.searchParams.set("CSPCHD", csptoken);
url.searchParams.set("CSPSHARE", "1");
url.searchParams.set("Namespace", this.api.config.ns);
panel.webview.html = `
url.searchParams.set("CSPCHD", cspchd);
url.searchParams.set("CSPSHARE", "1");
url.searchParams.set("Namespace", this.api.ns);
panel.webview.html = `
<!DOCTYPE html>
<html lang="en">
<head>
Expand Down Expand Up @@ -194,18 +203,21 @@ export class StudioActions {
</body>
</html>
`;
});
});
}
case 3: {
// Run an EXE on the client.
const urlRegex = /^(ht|f)tp(s?):\/\//gim;
if (target.search(urlRegex) === 0) {
if (/^(ht|f)tps?:\/\//i.test(target)) {
// Allow target that is a URL to be opened in an external browser
vscode.env.openExternal(vscode.Uri.parse(target));
break;
} else {
throw new Error("processUserAction: Run EXE (Action=3) not supported");
// Anything else is not supported
outputChannel.appendLine(
`Server-side source control User Action 3 (run an EXE on the client) is not supported for target '${target}'`
);
outputChannel.show(true);
}
break;
}
case 4: {
// Insert the text in Target in the current document at the current selection point
Expand All @@ -219,39 +231,45 @@ export class StudioActions {
}
case 5: // Studio will open the documents listed in Target
target.split(",").forEach((element) => {
let classname: string = element;
let fileName: string = element;
let method: string;
let offset = 0;
if (element.includes(":")) {
[classname, method] = element.split(":");
[fileName, method] = element.split(":");
if (method.includes("+")) {
offset = +method.split("+")[1];
method = method.split("+")[0];
}
}

const splitClassname = classname.split(".");
const filetype = splitClassname[splitClassname.length - 1];
const fileExt = fileName.split(".").pop().toLowerCase();
const isCorrectMethod = (text: string) =>
filetype === "cls" ? text.match("Method " + method) : text.startsWith(method);

const uri = DocumentContentProvider.getUri(classname);
vscode.window.showTextDocument(uri, { preview: false }).then((newEditor) => {
if (method) {
const document = newEditor.document;
for (let i = 0; i < document.lineCount; i++) {
const line = document.lineAt(i);
if (isCorrectMethod(line.text)) {
if (!line.text.endsWith("{")) offset++;
const targetLine = document.lineAt(i + offset);
const range = new vscode.Range(targetLine.range.start, targetLine.range.start);
newEditor.selection = new vscode.Selection(range.start, range.start);
newEditor.revealRange(range, vscode.TextEditorRevealType.InCenter);
break;
fileExt === "cls" ? text.match("Method " + method) : text.startsWith(method);

vscode.window.showTextDocument(DocumentContentProvider.getUri(fileName), { preview: false }).then(
(newEditor) => {
if (method) {
const document = newEditor.document;
for (let i = 0; i < document.lineCount; i++) {
const line = document.lineAt(i);
if (isCorrectMethod(line.text)) {
if (!line.text.endsWith("{")) offset++;
const targetLine = document.lineAt(i + offset);
const range = new vscode.Range(targetLine.range.start, targetLine.range.start);
newEditor.selection = new vscode.Selection(range.start, range.start);
newEditor.revealRange(range, vscode.TextEditorRevealType.InCenter);
break;
}
}
}
},
(error) => {
outputChannel.appendLine(
`Server-side source control User Action 5 failed to show '${element}': ${stringifyError(error)}`
);
outputChannel.show(true);
}
});
);
});
break;
case 6: // Display an alert dialog in Studio with the text from the Target variable.
Expand All @@ -268,7 +286,8 @@ export class StudioActions {
};
});
default:
throw new Error(`processUserAction: ${userAction} not supported`);
outputChannel.appendLine(`Unknown server-side source control User Action ${serverAction} is not supported`);
outputChannel.show(true);
}
return Promise.resolve();
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/viewOthers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export async function viewOthers(forceEditable = false): Promise<void> {
const methodlinetext: string = doc.lineAt(methodlinenum).text.trim();
if (methodlinetext.endsWith("{")) {
// This is the last line of the method definition, so count from here
const selectionline: number = methodlinenum + +loc.slice(loc.lastIndexOf("+") + 1);
const selectionline: number = methodlinenum + (+loc.slice(loc.lastIndexOf("+") + 1) || 0);
options.selection = new vscode.Range(selectionline, 0, selectionline, 0);
break;
}
Expand All @@ -68,7 +68,7 @@ export async function viewOthers(forceEditable = false): Promise<void> {
loc = loc.slice(0, loc.lastIndexOf("+"));
}
// Locations in INT routines are of the format +offset
const linenum: number = +loc.slice(1);
const linenum: number = +loc.slice(1) || 0;
options.selection = new vscode.Range(linenum, 0, linenum, 0);
}
vscode.window.showTextDocument(uri, options);
Expand Down
Loading