From 501472f06ba52d46611bd1ffd8bf4fe9de94425d Mon Sep 17 00:00:00 2001 From: Fenix Date: Wed, 4 Jan 2023 00:19:28 +0800 Subject: [PATCH] fix(cli): bundle command support shebang file (#17113) --- cli/tests/bundle_tests.rs | 5 +++++ .../testdata/bundle/shebang_file.bundle.out | 10 +++++++++ cli/tests/testdata/subdir/shebang_file.js | 5 +++++ cli/tools/bundle.rs | 21 +++++++++++++++++-- 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 cli/tests/testdata/bundle/shebang_file.bundle.out create mode 100644 cli/tests/testdata/subdir/shebang_file.js diff --git a/cli/tests/bundle_tests.rs b/cli/tests/bundle_tests.rs index 99144a8664..75b345a9fa 100644 --- a/cli/tests/bundle_tests.rs +++ b/cli/tests/bundle_tests.rs @@ -470,4 +470,9 @@ mod bundle { http_server: true, exit_code: 1, }); + + itest!(bundle_shebang_file { + args: "bundle subdir/shebang_file.js", + output: "bundle/shebang_file.bundle.out", + }); } diff --git a/cli/tests/testdata/bundle/shebang_file.bundle.out b/cli/tests/testdata/bundle/shebang_file.bundle.out new file mode 100644 index 0000000000..1be80b68c3 --- /dev/null +++ b/cli/tests/testdata/bundle/shebang_file.bundle.out @@ -0,0 +1,10 @@ +[WILDCARD] +#!/usr/bin/env -S deno run --allow-read +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +for (const item of Deno.readDirSync(".")){ + console.log(item.name); +} + diff --git a/cli/tests/testdata/subdir/shebang_file.js b/cli/tests/testdata/subdir/shebang_file.js new file mode 100644 index 0000000000..1c81be31cb --- /dev/null +++ b/cli/tests/testdata/subdir/shebang_file.js @@ -0,0 +1,5 @@ +#!/usr/bin/env -S deno run --allow-read + +for (const item of Deno.readDirSync(".")) { + console.log(item.name); +} diff --git a/cli/tools/bundle.rs b/cli/tools/bundle.rs index 375a64088f..a248c03855 100644 --- a/cli/tools/bundle.rs +++ b/cli/tools/bundle.rs @@ -147,12 +147,29 @@ fn bundle_module_graph( } } - deno_emit::bundle_graph( + let mut output = deno_emit::bundle_graph( graph, deno_emit::BundleOptions { bundle_type: deno_emit::BundleType::Module, emit_options: ts_config_result.ts_config.into(), emit_ignore_directives: true, }, - ) + )?; + + // todo(https://github.com/denoland/deno_emit/issues/85): move to deno_emit + if let Some(shebang) = shebang_file(graph) { + output.code = format!("{}\n{}", shebang, output.code); + } + + Ok(output) +} + +fn shebang_file(graph: &deno_graph::ModuleGraph) -> Option { + let source = graph.get(&graph.roots[0].0)?.maybe_source.as_ref()?; + let first_line = source.lines().next()?; + if first_line.starts_with("#!") { + Some(first_line.to_string()) + } else { + None + } }