Skip to content

Commit

Permalink
mega-linter-runner: Improve check if running as script or module (#3233)
Browse files Browse the repository at this point in the history
  • Loading branch information
echoix authored Dec 28, 2023
1 parent 40eb95c commit 461a6e9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Note: Can be used with `oxsecurity/megalinter@beta` in your GitHub Action mega-l
- mega-linter-runner: Remove container by default, except of `no-remove-container` option is sent
- Upgrade base image from python:3.11.6-alpine3.18 to python:3.11.7-alpine3.18, by @echoix in [#3212](https://github.com/oxsecurity/megalinter/pull/3212)
- Upgrade actions/upload-artifact@v3 to actions/upload-artifact@v4 in default workflows
- mega-linter-runner: Improve check if running as script or module, by @echoix in [#3233](https://github.com/oxsecurity/megalinter/pull/3233)

- Media

Expand Down
19 changes: 17 additions & 2 deletions mega-linter-runner/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,26 @@
import { MegaLinterRunner } from "./runner.js";
import { MegaLinterRunnerCli } from "./cli.js";

import { realpathSync } from "fs";
import { pathToFileURL } from "url";

// Run only if called by script
const runningAsScript = (this === undefined);
// This check handles symlinks as well
// See https://stackoverflow.com/a/71925565 and
// https://exploringjs.com/nodejs-shell-scripting/ch_nodejs-path.html#detecting-if-module-is-main
function wasCalledAsScript() {
// We use realpathSync to resolve symlinks, as cli scripts will often
// be executed from symlinks in the `node_modules/.bin`-folder
const realPath = realpathSync(process.argv[1]);

// Convert the file-path to a file-url before comparing it
const realPathAsUrl = pathToFileURL(realPath).href;

return import.meta.url === realPathAsUrl;
}

// Run asynchronously to use the returned status for process.exit
if (runningAsScript) {
if (wasCalledAsScript()) {
(async () => {
await new MegaLinterRunnerCli().run(process.argv);
})();
Expand Down

0 comments on commit 461a6e9

Please sign in to comment.