Skip to content

Commit

Permalink
[Lara-JS] Adds System.getCurrentFile() and .getCurrentFolder()
Browse files Browse the repository at this point in the history
  • Loading branch information
joaobispo committed Aug 8, 2024
1 parent bb0f624 commit 5d094f8
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 0 deletions.
80 changes: 80 additions & 0 deletions Lara-JS/src-api/lara/System.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,84 @@ export default class System {
static getNumLogicalCores(): number {
return JavaTypes.Runtime.getRuntime().availableProcessors();
}

static getCurrentFile(): string | undefined {
return this.getCurrentFilePrivate(3);
}

static getCurrentFolder(): string | undefined {
const filepath = this.getCurrentFilePrivate(3);

if (filepath === undefined) {
return undefined;
}

return Io.getPath(filepath).getParentFile().getAbsolutePath();
}

private static getCurrentFilePrivate(depth: number): string | undefined {
// Store originakl stack trace limit
const originalStackTraceLimit = Error.stackTraceLimit;

// Set to the depth we want to go
Error.stackTraceLimit = depth;

// Create an Error to capture the stack trace
const err = new Error();

// Restore original stack trace limit
Error.stackTraceLimit = originalStackTraceLimit;

// Process the stack trace
const stackTrace = err.stack;

// Return if no stack trace was obtained
if (stackTrace === undefined) {
return undefined;
}

// Split the stack trace into lines
const stackLines = stackTrace.split("\n");

// The stack trace format is usually:
// at FunctionName (filePath:lineNumber)
// Go to the depth we are interested in

let stackline;
let currentDepth = 0;
for (let i = 0; i < stackLines.length; i++) {
console.log("Line " + i + ": " + stackLines[i]);
const match = stackLines[i].match(/\(([^)]+)\)/);
if (match && match[1]) {
currentDepth++;
stackline = match[1];

if (currentDepth === depth) {
break;
}
}
}

// Could not find a stack line at the required depth
if (stackline === undefined) {
return undefined;
}

// Extract file path
const lastColonIndex = stackline.lastIndexOf(":");
const filePathTemp =
lastColonIndex == -1 ? stackline : stackline.substring(0, lastColonIndex);

console.log("Potential Path: " + filePathTemp);

let file = Io.getPath(filePathTemp);

if (!file.isAbsolute()) {
console.log("Base dir: " + __dirname);
file = Io.getPath(Io.getPath(__dirname), file.getPath());
}

const absolutePath = file.getAbsolutePath();
return absolutePath;
}
}
52 changes: 52 additions & 0 deletions LaraApi/src-lara/lara/System.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5d094f8

Please sign in to comment.