AnWeber / vscode-statusbar-command

MIT License
16 stars 4 forks source link

Use module such as 'fs' within a script? #21

Closed dandavison closed 2 years ago

dandavison commented 2 years ago

I'd like to create a statusbar command that displays some text returned by a function in the node fs module. Specifically, I'm trying:

"script": "statusBarItem.text = require('fs').readlinkSync('/tmp/mylink.txt')"

However, from experimenting, I believe that fs is not available in the script context and that require('fs') doesn't work (although I failed to catch the error when I tried using try...catch in the script).

Is it possible to do what I'm trying to do here, or what would it take to make it possible?

AnWeber commented 2 years ago

I currently use vm.runInNewContext. Here no access to the local scope or require is possible. I change it, but only within Trusted Workspaces.

dandavison commented 2 years ago

Fantastic, thanks again for the quick and very helpful response.

AnWeber commented 2 years ago

I have integrated an OutputChannel that would output errors in the script area. Did you find the channel outputchannel

Also, it would be possible to debug that script. For this I have created a howto for vscode-httpyac. The principle is the same. .

dandavison commented 2 years ago

Hi @AnWeber, I don't think this is working for me. I've installed from a .vsix built on master c7ed250a71ccfaa1f66f2613f0fa9801a16c7712, and I'm doing the following experiments:

"script": "console.log(vscode.workspace.isTrusted); statusBarItem.text = 'hello'"

I see true in the developer tools JS console, and hello appears in the status bar.

"script": "console.log(vscode.workspace.isTrusted); require('fs'); statusBarItem.text = 'hello'",

I still see true in the dev tools console, but the status bar text is now whatever I have set in the "text" field of the "statusbar_command.commands" config entry.

dandavison commented 2 years ago

The output channel is emitting lines that look like "empty JS object" syntax. Thanks for your debugging tips above; I haven't looked into any of this properly yet! I'll try to follow your suggestions above when I get a bit more time.

image
AnWeber commented 2 years ago

@dandavison There were still a few small errors in the code. I have now created a test case (read package version) and tested it.

{
      "alignment": "left",
      "command": "workbench.action.terminal.toggleTerminal",
      "id": "sbc.packageVersion",
      "text": "Package Version",
      "scriptEvents": ["vscode.workspace.onDidChangeConfiguration", "vscode.window.onDidChangeActiveTextEditor"],
      "script": "workspaceFolder && (statusBarItem.text = (JSON.parse(require('fs').readFileSync(`${workspaceFolder.fsPath}/package.json`, 'utf8'))).version)"
    }
dandavison commented 2 years ago

Thank you very much, this is working perfectly for me now.