deno 2.1.0

Provides the deno executable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use std::collections::HashMap;
use std::collections::HashSet;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use deno_config::workspace::FolderConfigs;
use deno_config::workspace::TaskDefinition;
use deno_config::workspace::TaskOrScript;
use deno_config::workspace::WorkspaceDirectory;
use deno_config::workspace::WorkspaceTasksConfig;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::bail;
use deno_core::anyhow::Context;
use deno_core::error::AnyError;
use deno_core::futures::future::LocalBoxFuture;
use deno_core::futures::stream::futures_unordered;
use deno_core::futures::FutureExt;
use deno_core::futures::StreamExt;
use deno_core::url::Url;
use deno_path_util::normalize_path;
use deno_runtime::deno_node::NodeResolver;
use deno_task_shell::ShellCommand;
use indexmap::IndexMap;
use regex::Regex;

use crate::args::CliOptions;
use crate::args::Flags;
use crate::args::TaskFlags;
use crate::colors;
use crate::factory::CliFactory;
use crate::npm::CliNpmResolver;
use crate::task_runner;
use crate::util::fs::canonicalize_path;

#[derive(Debug)]
struct PackageTaskInfo {
  matched_tasks: Vec<String>,
  tasks_config: WorkspaceTasksConfig,
}

pub async fn execute_script(
  flags: Arc<Flags>,
  task_flags: TaskFlags,
) -> Result<i32, AnyError> {
  let factory = CliFactory::from_flags(flags);
  let cli_options = factory.cli_options()?;
  let start_dir = &cli_options.start_dir;
  if !start_dir.has_deno_or_pkg_json() && !task_flags.eval {
    bail!("deno task couldn't find deno.json(c). See https://docs.deno.com/go/config")
  }
  let force_use_pkg_json =
    std::env::var_os(crate::task_runner::USE_PKG_JSON_HIDDEN_ENV_VAR_NAME)
      .map(|v| {
        // always remove so sub processes don't inherit this env var
        std::env::remove_var(
          crate::task_runner::USE_PKG_JSON_HIDDEN_ENV_VAR_NAME,
        );
        v == "1"
      })
      .unwrap_or(false);

  fn arg_to_regex(input: &str) -> Result<regex::Regex, regex::Error> {
    let mut regex_str = regex::escape(input);
    regex_str = regex_str.replace("\\*", ".*");

    Regex::new(&regex_str)
  }

  let packages_task_configs: Vec<PackageTaskInfo> = if let Some(filter) =
    &task_flags.filter
  {
    let task_name = task_flags.task.as_ref().unwrap();

    // Filter based on package name
    let package_regex = arg_to_regex(filter)?;
    let task_regex = arg_to_regex(task_name)?;

    let mut packages_task_info: Vec<PackageTaskInfo> = vec![];

    fn matches_package(
      config: &FolderConfigs,
      force_use_pkg_json: bool,
      regex: &Regex,
    ) -> bool {
      if !force_use_pkg_json {
        if let Some(deno_json) = &config.deno_json {
          if let Some(name) = &deno_json.json.name {
            if regex.is_match(name) {
              return true;
            }
          }
        }
      }

      if let Some(package_json) = &config.pkg_json {
        if let Some(name) = &package_json.name {
          if regex.is_match(name) {
            return true;
          }
        }
      }

      false
    }

    let workspace = cli_options.workspace();
    for folder in workspace.config_folders() {
      if !matches_package(folder.1, force_use_pkg_json, &package_regex) {
        continue;
      }

      let member_dir = workspace.resolve_member_dir(folder.0);
      let mut tasks_config = member_dir.to_tasks_config()?;
      if force_use_pkg_json {
        tasks_config = tasks_config.with_only_pkg_json();
      }

      // Any of the matched tasks could be a child task of another matched
      // one. Therefore we need to filter these out to ensure that every
      // task is only run once.
      let mut matched: HashSet<String> = HashSet::new();
      let mut visited: HashSet<String> = HashSet::new();

      fn visit_task(
        tasks_config: &WorkspaceTasksConfig,
        visited: &mut HashSet<String>,
        name: &str,
      ) {
        if visited.contains(name) {
          return;
        }

        visited.insert(name.to_string());

        if let Some((_, TaskOrScript::Task(_, task))) = &tasks_config.task(name)
        {
          for dep in &task.dependencies {
            visit_task(tasks_config, visited, dep);
          }
        }
      }

      // Match tasks in deno.json
      for name in tasks_config.task_names() {
        if task_regex.is_match(name) && !visited.contains(name) {
          matched.insert(name.to_string());
          visit_task(&tasks_config, &mut visited, name);
        }
      }

      packages_task_info.push(PackageTaskInfo {
        matched_tasks: matched
          .iter()
          .map(|s| s.to_string())
          .collect::<Vec<_>>(),
        tasks_config,
      });
    }

    // Logging every task definition would be too spammy. Pnpm only
    // logs a simple message too.
    if packages_task_info
      .iter()
      .all(|config| config.matched_tasks.is_empty())
    {
      log::warn!(
        "{}",
        colors::red(format!(
          "No matching task or script '{}' found in selected packages.",
          task_name
        ))
      );
      return Ok(0);
    }

    // FIXME: Sort packages topologically
    //

    packages_task_info
  } else {
    let mut tasks_config = start_dir.to_tasks_config()?;

    if force_use_pkg_json {
      tasks_config = tasks_config.with_only_pkg_json()
    }

    let Some(task_name) = &task_flags.task else {
      print_available_tasks(
        &mut std::io::stdout(),
        &cli_options.start_dir,
        &tasks_config,
      )?;
      return Ok(0);
    };

    vec![PackageTaskInfo {
      tasks_config,
      matched_tasks: vec![task_name.to_string()],
    }]
  };

  let npm_resolver = factory.npm_resolver().await?;
  let node_resolver = factory.node_resolver().await?;
  let env_vars = task_runner::real_env_vars();

  let no_of_concurrent_tasks = if let Ok(value) = std::env::var("DENO_JOBS") {
    value.parse::<NonZeroUsize>().ok()
  } else {
    std::thread::available_parallelism().ok()
  }
  .unwrap_or_else(|| NonZeroUsize::new(2).unwrap());

  let task_runner = TaskRunner {
    task_flags: &task_flags,
    npm_resolver: npm_resolver.as_ref(),
    node_resolver: node_resolver.as_ref(),
    env_vars,
    cli_options,
    concurrency: no_of_concurrent_tasks.into(),
  };

  if task_flags.eval {
    return task_runner
      .run_deno_task(
        &Url::from_directory_path(cli_options.initial_cwd()).unwrap(),
        "",
        &TaskDefinition {
          command: task_flags.task.as_ref().unwrap().to_string(),
          dependencies: vec![],
          description: None,
        },
      )
      .await;
  }

  for task_config in &packages_task_configs {
    let exit_code = task_runner.run_tasks(task_config).await?;
    if exit_code > 0 {
      return Ok(exit_code);
    }
  }

  Ok(0)
}

struct RunSingleOptions<'a> {
  task_name: &'a str,
  script: &'a str,
  cwd: &'a Path,
  custom_commands: HashMap<String, Rc<dyn ShellCommand>>,
}

struct TaskRunner<'a> {
  task_flags: &'a TaskFlags,
  npm_resolver: &'a dyn CliNpmResolver,
  node_resolver: &'a NodeResolver,
  env_vars: HashMap<String, String>,
  cli_options: &'a CliOptions,
  concurrency: usize,
}

impl<'a> TaskRunner<'a> {
  pub async fn run_tasks(
    &self,
    pkg_tasks_config: &PackageTaskInfo,
  ) -> Result<i32, deno_core::anyhow::Error> {
    match sort_tasks_topo(pkg_tasks_config) {
      Ok(sorted) => {
        self
          .run_tasks_in_parallel(&pkg_tasks_config.tasks_config, sorted)
          .await
      }
      Err(err) => match err {
        TaskError::NotFound(name) => {
          if self.task_flags.is_run {
            return Err(anyhow!("Task not found: {}", name));
          }

          log::error!("Task not found: {}", name);
          if log::log_enabled!(log::Level::Error) {
            self.print_available_tasks(&pkg_tasks_config.tasks_config)?;
          }
          Ok(1)
        }
        TaskError::TaskDepCycle { path } => {
          log::error!("Task cycle detected: {}", path.join(" -> "));
          Ok(1)
        }
      },
    }
  }

  pub fn print_available_tasks(
    &self,
    tasks_config: &WorkspaceTasksConfig,
  ) -> Result<(), std::io::Error> {
    print_available_tasks(
      &mut std::io::stderr(),
      &self.cli_options.start_dir,
      tasks_config,
    )
  }

  async fn run_tasks_in_parallel(
    &self,
    tasks_config: &WorkspaceTasksConfig,
    task_names: Vec<String>,
  ) -> Result<i32, deno_core::anyhow::Error> {
    struct PendingTasksContext {
      completed: HashSet<String>,
      running: HashSet<String>,
      task_names: Vec<String>,
    }

    impl PendingTasksContext {
      fn has_remaining_tasks(&self) -> bool {
        self.completed.len() < self.task_names.len()
      }

      fn mark_complete(&mut self, task_name: String) {
        self.running.remove(&task_name);
        self.completed.insert(task_name);
      }

      fn get_next_task<'a>(
        &mut self,
        runner: &'a TaskRunner<'a>,
        tasks_config: &'a WorkspaceTasksConfig,
      ) -> Option<LocalBoxFuture<'a, Result<(i32, String), AnyError>>> {
        for name in &self.task_names {
          if self.completed.contains(name) || self.running.contains(name) {
            continue;
          }

          let Some((folder_url, task_or_script)) = tasks_config.task(name)
          else {
            continue;
          };
          let should_run = match task_or_script {
            TaskOrScript::Task(_, def) => def
              .dependencies
              .iter()
              .all(|dep| self.completed.contains(dep)),
            TaskOrScript::Script(_, _) => true,
          };

          if !should_run {
            continue;
          }

          self.running.insert(name.clone());
          let name = name.clone();
          return Some(
            async move {
              match task_or_script {
                TaskOrScript::Task(_, def) => {
                  runner.run_deno_task(folder_url, &name, def).await
                }
                TaskOrScript::Script(scripts, _) => {
                  runner.run_npm_script(folder_url, &name, scripts).await
                }
              }
              .map(|exit_code| (exit_code, name))
            }
            .boxed_local(),
          );
        }
        None
      }
    }

    let mut context = PendingTasksContext {
      completed: HashSet::with_capacity(task_names.len()),
      running: HashSet::with_capacity(self.concurrency),
      task_names,
    };

    let mut queue = futures_unordered::FuturesUnordered::new();

    while context.has_remaining_tasks() {
      while queue.len() < self.concurrency {
        if let Some(task) = context.get_next_task(self, tasks_config) {
          queue.push(task);
        } else {
          break;
        }
      }

      // If queue is empty at this point, then there are no more tasks in the queue.
      let Some(result) = queue.next().await else {
        debug_assert_eq!(context.task_names.len(), 0);
        break;
      };

      let (exit_code, name) = result?;
      if exit_code > 0 {
        return Ok(exit_code);
      }

      context.mark_complete(name);
    }

    Ok(0)
  }

  pub async fn run_deno_task(
    &self,
    dir_url: &Url,
    task_name: &str,
    definition: &TaskDefinition,
  ) -> Result<i32, deno_core::anyhow::Error> {
    let cwd = match &self.task_flags.cwd {
      Some(path) => canonicalize_path(&PathBuf::from(path))
        .context("failed canonicalizing --cwd")?,
      None => normalize_path(dir_url.to_file_path().unwrap()),
    };

    let custom_commands = task_runner::resolve_custom_commands(
      self.npm_resolver,
      self.node_resolver,
    )?;
    self
      .run_single(RunSingleOptions {
        task_name,
        script: &definition.command,
        cwd: &cwd,
        custom_commands,
      })
      .await
  }

  pub async fn run_npm_script(
    &self,
    dir_url: &Url,
    task_name: &str,
    scripts: &IndexMap<String, String>,
  ) -> Result<i32, deno_core::anyhow::Error> {
    // ensure the npm packages are installed if using a managed resolver
    if let Some(npm_resolver) = self.npm_resolver.as_managed() {
      npm_resolver.ensure_top_level_package_json_install().await?;
    }

    let cwd = match &self.task_flags.cwd {
      Some(path) => canonicalize_path(&PathBuf::from(path))?,
      None => normalize_path(dir_url.to_file_path().unwrap()),
    };

    // At this point we already checked if the task name exists in package.json.
    // We can therefore check for "pre" and "post" scripts too, since we're only
    // dealing with package.json here and not deno.json
    let task_names = vec![
      format!("pre{}", task_name),
      task_name.to_string(),
      format!("post{}", task_name),
    ];
    let custom_commands = task_runner::resolve_custom_commands(
      self.npm_resolver,
      self.node_resolver,
    )?;
    for task_name in &task_names {
      if let Some(script) = scripts.get(task_name) {
        let exit_code = self
          .run_single(RunSingleOptions {
            task_name,
            script,
            cwd: &cwd,
            custom_commands: custom_commands.clone(),
          })
          .await?;
        if exit_code > 0 {
          return Ok(exit_code);
        }
      }
    }

    Ok(0)
  }

  async fn run_single(
    &self,
    opts: RunSingleOptions<'_>,
  ) -> Result<i32, AnyError> {
    let RunSingleOptions {
      task_name,
      script,
      cwd,
      custom_commands,
    } = opts;

    output_task(
      opts.task_name,
      &task_runner::get_script_with_args(script, self.cli_options.argv()),
    );

    Ok(
      task_runner::run_task(task_runner::RunTaskOptions {
        task_name,
        script,
        cwd,
        env_vars: self.env_vars.clone(),
        custom_commands,
        init_cwd: self.cli_options.initial_cwd(),
        argv: self.cli_options.argv(),
        root_node_modules_dir: self.npm_resolver.root_node_modules_path(),
        stdio: None,
      })
      .await?
      .exit_code,
    )
  }
}

#[derive(Debug)]
enum TaskError {
  NotFound(String),
  TaskDepCycle { path: Vec<String> },
}

fn sort_tasks_topo(
  pkg_task_config: &PackageTaskInfo,
) -> Result<Vec<String>, TaskError> {
  fn sort_visit<'a>(
    name: &'a str,
    sorted: &mut Vec<String>,
    mut path: Vec<&'a str>,
    tasks_config: &'a WorkspaceTasksConfig,
  ) -> Result<(), TaskError> {
    // Already sorted
    if sorted.iter().any(|sorted_name| sorted_name == name) {
      return Ok(());
    }

    // Graph has a cycle
    if path.contains(&name) {
      path.push(name);
      return Err(TaskError::TaskDepCycle {
        path: path.iter().map(|s| s.to_string()).collect(),
      });
    }

    let Some((_, task_or_script)) = tasks_config.task(name) else {
      return Err(TaskError::NotFound(name.to_string()));
    };

    if let TaskOrScript::Task(_, task) = task_or_script {
      for dep in &task.dependencies {
        let mut path = path.clone();
        path.push(name);
        sort_visit(dep, sorted, path, tasks_config)?
      }
    }

    sorted.push(name.to_string());

    Ok(())
  }

  let mut sorted: Vec<String> = vec![];

  for name in &pkg_task_config.matched_tasks {
    sort_visit(name, &mut sorted, Vec::new(), &pkg_task_config.tasks_config)?;
  }

  Ok(sorted)
}

fn output_task(task_name: &str, script: &str) {
  log::info!(
    "{} {} {}",
    colors::green("Task"),
    colors::cyan(task_name),
    script,
  );
}

fn print_available_tasks(
  writer: &mut dyn std::io::Write,
  workspace_dir: &Arc<WorkspaceDirectory>,
  tasks_config: &WorkspaceTasksConfig,
) -> Result<(), std::io::Error> {
  writeln!(writer, "{}", colors::green("Available tasks:"))?;
  let is_cwd_root_dir = tasks_config.root.is_none();

  if tasks_config.is_empty() {
    writeln!(
      writer,
      "  {}",
      colors::red("No tasks found in configuration file")
    )?;
    return Ok(());
  }

  struct AvailableTaskDescription {
    is_root: bool,
    is_deno: bool,
    name: String,
    task: TaskDefinition,
  }
  let mut seen_task_names = HashSet::with_capacity(tasks_config.tasks_count());
  let mut task_descriptions = Vec::with_capacity(tasks_config.tasks_count());

  for maybe_config in [&tasks_config.member, &tasks_config.root] {
    let Some(config) = maybe_config else {
      continue;
    };

    if let Some(config) = config.deno_json.as_ref() {
      let is_root = !is_cwd_root_dir
        && config.folder_url == *workspace_dir.workspace.root_dir().as_ref();

      for (name, definition) in &config.tasks {
        if !seen_task_names.insert(name) {
          continue; // already seen
        }
        task_descriptions.push(AvailableTaskDescription {
          is_root,
          is_deno: true,
          name: name.to_string(),
          task: definition.clone(),
        });
      }
    }

    if let Some(config) = config.package_json.as_ref() {
      let is_root = !is_cwd_root_dir
        && config.folder_url == *workspace_dir.workspace.root_dir().as_ref();
      for (name, script) in &config.tasks {
        if !seen_task_names.insert(name) {
          continue; // already seen
        }

        task_descriptions.push(AvailableTaskDescription {
          is_root,
          is_deno: false,
          name: name.to_string(),
          task: deno_config::deno_json::TaskDefinition {
            command: script.to_string(),
            dependencies: vec![],
            description: None,
          },
        });
      }
    }
  }

  for desc in task_descriptions {
    writeln!(
      writer,
      "- {}{}",
      colors::cyan(desc.name),
      if desc.is_root {
        if desc.is_deno {
          format!(" {}", colors::italic_gray("(workspace)"))
        } else {
          format!(" {}", colors::italic_gray("(workspace package.json)"))
        }
      } else if desc.is_deno {
        "".to_string()
      } else {
        format!(" {}", colors::italic_gray("(package.json)"))
      }
    )?;
    if let Some(description) = &desc.task.description {
      let slash_slash = colors::italic_gray("//");
      writeln!(
        writer,
        "    {slash_slash} {}",
        colors::italic_gray(description)
      )?;
    }
    writeln!(writer, "    {}", desc.task.command)?;
    if !desc.task.dependencies.is_empty() {
      writeln!(
        writer,
        "    {} {}",
        colors::gray("depends on:"),
        colors::cyan(desc.task.dependencies.join(", "))
      )?;
    }
  }

  Ok(())
}