-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathexecute.rs
More file actions
1086 lines (971 loc) · 39.8 KB
/
execute.rs
File metadata and controls
1086 lines (971 loc) · 39.8 KB
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::hash_map::Entry,
env::{join_paths, split_paths},
ffi::{OsStr, OsString},
path::PathBuf,
process::{ExitStatus, Stdio},
sync::{Arc, LazyLock, Mutex},
time::{Duration, Instant},
};
use bincode::{Decode, Encode};
use fspy::AccessMode;
use futures_util::future::try_join3;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use supports_color::{Stream, on};
use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
use vite_glob::GlobPatternSet;
use vite_path::{AbsolutePath, RelativePathBuf};
use vite_str::Str;
use wax::Glob;
use crate::{
Error,
collections::{HashMap, HashSet},
config::{ResolvedTask, ResolvedTaskCommand, ResolvedTaskConfig, TaskCommand},
maybe_str::MaybeString,
};
#[derive(Debug, PartialEq, Eq, Clone, Copy, Encode, Decode, Serialize, Deserialize)]
pub enum OutputKind {
StdOut,
StdErr,
}
#[derive(Debug, Encode, Decode, Serialize)]
pub struct StdOutput {
pub kind: OutputKind,
pub content: MaybeString,
}
#[derive(Debug, Clone, Copy)]
pub struct PathRead {
pub read_dir_entries: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct PathWrite;
/// Contains info that is available after executing the task
#[derive(Debug)]
pub struct ExecutedTask {
pub std_outputs: Arc<[StdOutput]>,
pub exit_status: ExitStatus,
pub path_reads: HashMap<RelativePathBuf, PathRead>,
pub path_writes: HashMap<RelativePathBuf, PathWrite>,
pub duration: Duration,
}
/// Collects stdout/stderr into `outputs` and at the same time writes them to the real stdout/stderr
async fn collect_std_outputs(
outputs: &Mutex<Vec<StdOutput>>,
mut stream: impl AsyncRead + Unpin,
kind: OutputKind,
) -> Result<(), Error> {
let mut buf = [0u8; 8192];
let mut parent_output_handle: Box<dyn AsyncWrite + Unpin + Send> = match kind {
OutputKind::StdOut => Box::new(tokio::io::stdout()),
OutputKind::StdErr => Box::new(tokio::io::stderr()),
};
loop {
let n = stream.read(&mut buf).await?;
if n == 0 {
return Ok(());
}
let content = &buf[..n];
parent_output_handle.write_all(content).await?;
parent_output_handle.flush().await?;
let mut outputs = outputs.lock().unwrap();
if let Some(last) = outputs.last_mut()
&& last.kind == kind
{
last.content.extend_from_slice(content);
} else {
outputs.push(StdOutput { kind, content: content.to_vec().into() });
}
}
}
/// Environment variables for task execution.
///
/// # How Environment Variables Affect Caching
///
/// Vite-plus distinguishes between two types of environment variables:
///
/// 1. **Declared envs** (in task config's `envs` array):
/// - Explicitly declared as dependencies of the task
/// - Included in `envs_without_pass_through`
/// - Changes to these invalidate the cache
/// - Example: `NODE_ENV`, `API_URL`, `BUILD_MODE`
///
/// 2. **Pass-through envs** (in task config's `pass_through_envs` or defaults like PATH):
/// - Available to the task but don't affect caching
/// - Only in `all_envs`, NOT in `envs_without_pass_through`
/// - Changes to these don't invalidate cache
/// - Example: PATH, HOME, USER, CI
///
/// ## Cache Key Generation
/// - Only `envs_without_pass_through` is included in the cache key
/// - This ensures tasks are re-run when important envs change
/// - But allows cache reuse when only incidental envs change
///
/// ## Common Issues
/// - If a built-in resolver provides different envs, cache will be polluted
/// - Missing important envs from `envs` array = stale cache on env changes
/// - Including volatile envs in `envs` array = unnecessary cache misses
#[derive(Debug)]
pub struct TaskEnvs {
/// All environment variables available to the task (declared + pass-through)
pub all_envs: HashMap<Str, Arc<OsStr>>,
/// Only declared envs that affect the cache key (excludes pass-through)
pub envs_without_pass_through: HashMap<Str, Str>,
}
fn resolve_envs_with_patterns(
env_vars: impl Iterator<Item = (OsString, OsString)>,
patterns: &[&str],
) -> Result<HashMap<Str, Arc<OsStr>>, Error> {
let patterns = GlobPatternSet::new(patterns.iter().filter(|pattern| {
if pattern.starts_with('!') {
// FIXME: use better way to print warning log
// Or parse and validate TaskConfig in command parsing phase
tracing::warn!(
"env pattern starts with '!' is not supported, will be ignored: {}",
pattern
);
false
} else {
true
}
}))?;
let envs: HashMap<Str, Arc<OsStr>> = env_vars
.filter_map(|(name, value)| {
let Some(name) = name.to_str() else {
return None;
};
if patterns.is_match(name) {
Some((Str::from(name), Arc::<OsStr>::from(value)))
} else {
None
}
})
.collect();
Ok(envs)
}
// Exact matches for common environment variables
// Referenced from Turborepo's implementation:
// https://github.com/vercel/turborepo/blob/26d309f073ca3ac054109ba0c29c7e230e7caac3/crates/turborepo-lib/src/task_hash.rs#L439
const DEFAULT_PASSTHROUGH_ENVS: &[&str] = &[
// System and shell
"HOME",
"USER",
"TZ",
"LANG",
"SHELL",
"PWD",
"PATH",
// CI/CD environments
"CI",
// Node.js specific
"NODE_OPTIONS",
"COREPACK_HOME",
"NPM_CONFIG_STORE_DIR",
"PNPM_HOME",
// Library paths
"LD_LIBRARY_PATH",
"DYLD_FALLBACK_LIBRARY_PATH",
"LIBPATH",
// Terminal/display
"COLORTERM",
"TERM",
"TERM_PROGRAM",
"DISPLAY",
"FORCE_COLOR",
"NO_COLOR",
// Temporary directories
"TMP",
"TEMP",
// Vercel specific
"VERCEL",
"VERCEL_*",
"NEXT_*",
"USE_OUTPUT_FOR_EDGE_FUNCTIONS",
"NOW_BUILDER",
// Windows specific
"APPDATA",
"PROGRAMDATA",
"SYSTEMROOT",
"SYSTEMDRIVE",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
// IDE specific (exact matches)
"ELECTRON_RUN_AS_NODE",
"JB_INTERPRETER",
"_JETBRAINS_TEST_RUNNER_RUN_SCOPE_TYPE",
"JB_IDE_*",
// VSCode specific
"VSCODE_*",
// Docker specific
"DOCKER_*",
"BUILDKIT_*",
"COMPOSE_*",
// Token patterns
"*_TOKEN",
// oxc specific
"OXLINT_*",
];
const SENSITIVE_PATTERNS: &[&str] = &[
"*_KEY",
"*_SECRET",
"*_TOKEN",
"*_PASSWORD",
"*_PASS",
"*_PWD",
"*_CREDENTIAL*",
"*_API_KEY",
"*_PRIVATE_*",
"AWS_*",
"GITHUB_*",
"NPM_*TOKEN",
"DATABASE_URL",
"MONGODB_URI",
"REDIS_URL",
"*_CERT*",
// Exact matches for known sensitive names
"PASSWORD",
"SECRET",
"TOKEN",
];
impl TaskEnvs {
pub fn resolve(
current_envs: impl Iterator<Item = (OsString, OsString)>,
base_dir: &AbsolutePath,
task: &ResolvedTaskConfig,
) -> Result<Self, Error> {
// All envs that are passed to the task
let all_patterns: Vec<&str> = DEFAULT_PASSTHROUGH_ENVS
.iter()
.copied()
.chain(task.config.pass_through_envs.iter().map(std::convert::AsRef::as_ref))
.chain(task.config.envs.iter().map(std::convert::AsRef::as_ref))
.collect();
let mut all_envs = resolve_envs_with_patterns(current_envs, &all_patterns)?;
// envs need to calculate fingerprint
let mut envs_without_pass_through = HashMap::<Str, Str>::new();
if !task.config.envs.is_empty() {
let envs_without_pass_through_patterns =
GlobPatternSet::new(task.config.envs.iter().filter(|s| !s.starts_with('!')))?;
let sensitive_patterns = GlobPatternSet::new(SENSITIVE_PATTERNS)?;
for (name, value) in &all_envs {
if !envs_without_pass_through_patterns.is_match(name) {
continue;
}
let Some(value) = value.to_str() else {
return Err(Error::EnvValueIsNotValidUnicode {
key: name.clone(),
value: value.to_os_string(),
});
};
let value: Str = if sensitive_patterns.is_match(name) {
let mut hasher = Sha256::new();
hasher.update(value.as_bytes());
format!("sha256:{:x}", hasher.finalize()).into()
} else {
value.into()
};
envs_without_pass_through.insert(name.clone(), value);
}
}
// Automatically add FORCE_COLOR environment variable if not already set
// This enables color output in subprocesses when color is supported
// TODO: will remove this temporarily until we have a better solution
if !all_envs.contains_key("FORCE_COLOR")
&& !all_envs.contains_key("NO_COLOR")
&& let Some(support) = on(Stream::Stdout)
{
let force_color_value = if support.has_16m {
"3" // True color (16 million colors)
} else if support.has_256 {
"2" // 256 colors
} else if support.has_basic {
"1" // Basic ANSI colors
} else {
"0" // No color support
};
all_envs
.insert("FORCE_COLOR".into(), Arc::<OsStr>::from(OsStr::new(force_color_value)));
}
// Add VITE_TASK_EXECUTION_ENV to indicate we're running inside vite_task
// This prevents nested auto-install execution
all_envs.insert("VITE_TASK_EXECUTION_ENV".into(), Arc::<OsStr>::from(OsStr::new("1")));
// Add node_modules/.bin to PATH
// On Windows, environment variable names are case-insensitive (e.g., "PATH", "Path", "path" are all the same)
// However, Rust's HashMap keys are case-sensitive, so we need to find the existing PATH variable
// regardless of its casing to avoid creating duplicate PATH entries with different casings.
// For example, if the system has "Path", we should use that instead of creating a new "PATH" entry.
let env_path = {
if cfg!(windows)
&& let Some(existing_path) = all_envs.iter_mut().find_map(|(name, value)| {
if name.eq_ignore_ascii_case("path") { Some(value) } else { None }
})
{
// Found existing PATH variable (with any casing), use it
existing_path
} else {
// On Unix or no existing PATH on Windows, create/get "PATH" entry
all_envs.entry("PATH".into()).or_insert_with(|| Arc::<OsStr>::from(OsStr::new("")))
}
};
let paths = split_paths(env_path).filter(|path| !path.as_os_str().is_empty());
const NODE_MODULES_DOT_BIN: &str =
if cfg!(windows) { "node_modules\\.bin" } else { "node_modules/.bin" };
let node_modules_bin_paths = [
base_dir.join(&task.config.cwd).join(NODE_MODULES_DOT_BIN).into_path_buf(),
base_dir.join(&task.config_dir).join(NODE_MODULES_DOT_BIN).into_path_buf(),
];
*env_path = join_paths(node_modules_bin_paths.into_iter().chain(paths))?.into();
Ok(Self { all_envs, envs_without_pass_through })
}
}
pub static CURRENT_EXECUTION_ID: LazyLock<Option<String>> =
LazyLock::new(|| std::env::var("VITE_TASK_EXECUTION_ID").ok());
pub static EXECUTION_SUMMARY_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
std::env::var("VITE_TASK_EXECUTION_DIR")
.map_or_else(|_| tempfile::tempdir().unwrap().keep(), PathBuf::from)
});
pub async fn execute_task(
execution_id: &str,
resolved_command: &ResolvedTaskCommand,
base_dir: &AbsolutePath,
) -> Result<ExecutedTask, Error> {
let mut cmd = match &resolved_command.fingerprint.command {
TaskCommand::ShellScript(script) => {
let mut cmd = if cfg!(windows) {
let mut cmd = fspy::Command::new("cmd.exe");
// https://github.com/nodejs/node/blob/dbd24b165128affb7468ca42f69edaf7e0d85a9a/lib/child_process.js#L633
cmd.args(["/d", "/s", "/c"]);
cmd
} else {
let mut cmd = fspy::Command::new("sh");
cmd.args(["-c"]);
cmd
};
cmd.arg(script);
cmd.envs(&resolved_command.all_envs);
cmd
}
TaskCommand::Parsed(task_parsed_command) => {
// handle shell built-ins
match task_parsed_command.program.as_str() {
"echo" => {
let mut prints_new_line = true;
let mut args = task_parsed_command.args.as_slice();
if let Some(first_arg) = args.first()
&& first_arg == "-n"
{
prints_new_line = false;
args = &args[1..];
}
let mut output = args.iter().map(|arg| arg.as_str()).join(" ");
if prints_new_line {
output.push('\n');
}
print!("{output}");
return Ok(ExecutedTask {
std_outputs: vec![StdOutput {
kind: OutputKind::StdOut,
content: Vec::<u8>::from(output).into(),
}]
.into(),
exit_status: ExitStatus::default(),
path_reads: Default::default(),
path_writes: Default::default(),
duration: Duration::ZERO,
});
}
_ => {}
}
if resolved_command.fingerprint.command.need_skip_cache() {
let mut child = tokio::process::Command::new(&task_parsed_command.program)
.args(&task_parsed_command.args)
.envs(&resolved_command.all_envs)
.envs(&task_parsed_command.envs)
.env(
"VITE_OUTER_COMMAND",
if resolved_command.fingerprint.command.has_inner_runner() {
resolved_command.fingerprint.command.to_string()
} else {
String::new()
},
)
.env("VITE_TASK_EXECUTION_ID", execution_id)
.env("VITE_TASK_EXECUTION_DIR", EXECUTION_SUMMARY_DIR.as_os_str())
.current_dir(base_dir.join(&resolved_command.fingerprint.cwd))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let child_stdout = child.stdout.take().unwrap();
let child_stderr = child.stderr.take().unwrap();
let outputs = Mutex::new(Vec::<StdOutput>::new());
let ((), (), (exit_status, duration)) = try_join3(
collect_std_outputs(&outputs, child_stdout, OutputKind::StdOut),
collect_std_outputs(&outputs, child_stderr, OutputKind::StdErr),
async move {
let start = Instant::now();
let exit_status = child.wait().await?;
Ok((exit_status, start.elapsed()))
},
)
.await?;
return Ok(ExecutedTask {
std_outputs: outputs.into_inner().unwrap().into(),
exit_status,
path_reads: HashMap::new(),
path_writes: HashMap::new(),
duration,
});
}
let mut cmd = fspy::Command::new(&task_parsed_command.program);
cmd.args(&task_parsed_command.args);
cmd.envs(&resolved_command.all_envs);
cmd.envs(&task_parsed_command.envs);
cmd
}
};
cmd.current_dir(base_dir.join(&resolved_command.fingerprint.cwd))
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().await?;
let child_stdout = child.stdout.take().unwrap();
let child_stderr = child.stderr.take().unwrap();
let outputs = Mutex::new(Vec::<StdOutput>::new());
let ((), (), (termination, duration)) = try_join3(
collect_std_outputs(&outputs, child_stdout, OutputKind::StdOut),
collect_std_outputs(&outputs, child_stderr, OutputKind::StdErr),
async move {
let start = Instant::now();
let exit_status = child.wait_handle.await?;
Ok((exit_status, start.elapsed()))
},
)
.await?;
let mut path_reads = HashMap::<RelativePathBuf, PathRead>::new();
let mut path_writes = HashMap::<RelativePathBuf, PathWrite>::new();
for access in termination.path_accesses.iter() {
let relative_path = access
.path
.strip_path_prefix(base_dir, |strip_result| {
let Ok(stripped_path) = strip_result else {
return None;
};
Some(RelativePathBuf::new(stripped_path).map_err(|err| {
Error::InvalidRelativePath { path: stripped_path.into(), reason: err }
}))
})
.transpose()?;
let Some(relative_path) = relative_path else {
// ignore accesses outside the workspace
continue;
};
if relative_path.as_path().strip_prefix(".git").is_ok() {
// temp workaround for oxlint reading inside .git
continue;
}
match access.mode {
AccessMode::Read => {
path_reads.entry(relative_path).or_insert(PathRead { read_dir_entries: false });
}
AccessMode::Write => {
path_writes.insert(relative_path, PathWrite);
}
AccessMode::ReadWrite => {
path_reads
.entry(relative_path.clone())
.or_insert(PathRead { read_dir_entries: false });
path_writes.insert(relative_path, PathWrite);
}
AccessMode::ReadDir => match path_reads.entry(relative_path) {
Entry::Occupied(mut occupied) => occupied.get_mut().read_dir_entries = true,
Entry::Vacant(vacant) => {
vacant.insert(PathRead { read_dir_entries: true });
}
},
}
}
let outputs = outputs.into_inner().unwrap();
tracing::debug!(
"executed task finished, path_reads: {}, path_writes: {}, outputs: {}, exit_status: {}",
path_reads.len(),
path_writes.len(),
outputs.len(),
termination.status,
);
// let input_paths = gather_inputs(task, base_dir)?;
Ok(ExecutedTask {
std_outputs: outputs.into(),
exit_status: termination.status,
path_reads,
path_writes,
duration,
})
}
#[expect(dead_code)]
fn gather_inputs(
task: &ResolvedTask,
base_dir: &AbsolutePath,
) -> Result<HashSet<Arc<OsStr>>, Error> {
// Task inferring to be implemented here
let inputs = &task.resolved_config.config.inputs;
if inputs.is_empty() {
return Ok(HashSet::new());
}
let glob = format!("{{{}}}", itertools::Itertools::join(&mut inputs.iter(), ",")); // TODO: handle "," inside globs
let glob = Glob::new(&glob)?;
let mut paths: HashSet<Arc<OsStr>> = HashSet::new();
for entry in glob.walk(base_dir.join(&task.resolved_config.config_dir)) {
let entry = entry?;
paths.insert(entry.into_path().into_os_string().into());
}
Ok(paths)
}
#[cfg(test)]
mod tests {
use vite_path::relative::RelativePathBuf;
use super::*;
#[test]
fn test_force_color_auto_detection() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs: HashSet::new(),
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved_task_config =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
let base_dir = if cfg!(windows) {
AbsolutePath::new("C:\\workspace").unwrap()
} else {
AbsolutePath::new("/workspace").unwrap()
};
// Test when FORCE_COLOR is not already set
let mock_envs = vec![("PATH".into(), "/usr/bin".into())];
let result =
TaskEnvs::resolve(mock_envs.into_iter(), base_dir, &resolved_task_config).unwrap();
// FORCE_COLOR should be automatically added if color is supported
// Note: This test might vary based on the test environment
let force_color_present = result.all_envs.contains_key("FORCE_COLOR");
if force_color_present {
let force_color_value = result.all_envs.get("FORCE_COLOR").unwrap();
let force_color_str = force_color_value.to_str().unwrap();
// Should be a valid FORCE_COLOR level
assert!(matches!(force_color_str, "0" | "1" | "2" | "3"));
}
// Test when FORCE_COLOR is already set - should not be overridden
let mock_envs =
vec![("PATH".into(), "/usr/bin".into()), ("FORCE_COLOR".into(), "2".into())];
let result2 =
TaskEnvs::resolve(mock_envs.into_iter(), base_dir, &resolved_task_config).unwrap();
// Should contain the original FORCE_COLOR value
assert!(result2.all_envs.contains_key("FORCE_COLOR"));
let force_color_value = result2.all_envs.get("FORCE_COLOR").unwrap();
assert_eq!(force_color_value.to_str().unwrap(), "2");
// FORCE_COLOR should not be in envs_without_pass_through since it's a passthrough env
assert!(!result2.envs_without_pass_through.contains_key("FORCE_COLOR"));
// Test when NO_COLOR is already set - FORCE_COLOR should not be automatically added
let mock_envs = vec![("PATH".into(), "/usr/bin".into()), ("NO_COLOR".into(), "1".into())];
let result3 =
TaskEnvs::resolve(mock_envs.into_iter(), base_dir, &resolved_task_config).unwrap();
assert!(result3.all_envs.contains_key("NO_COLOR"));
let no_color_value = result3.all_envs.get("NO_COLOR").unwrap();
assert_eq!(no_color_value.to_str().unwrap(), "1");
// FORCE_COLOR should not be automatically added since NO_COLOR is set
assert!(!result3.all_envs.contains_key("FORCE_COLOR"));
}
#[test]
#[cfg(unix)]
fn test_task_envs_stable_ordering() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
// Create a task config with multiple envs in a HashSet
let mut envs = HashSet::new();
envs.insert("ZEBRA_VAR".into());
envs.insert("ALPHA_VAR".into());
envs.insert("MIDDLE_VAR".into());
envs.insert("BETA_VAR".into());
envs.insert("NOT_EXISTS_VAR".into());
envs.insert("APP?_*".into());
// will auto ignore ! prefix
envs.insert("!APP*".into());
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs,
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved_task_config =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
let base_dir = AbsolutePath::new("/workspace").unwrap();
// Create mock environment variables
let mock_envs = vec![
("ZEBRA_VAR".into(), "zebra_value".into()),
("ALPHA_VAR".into(), "alpha_value".into()),
("MIDDLE_VAR".into(), "middle_value".into()),
("BETA_VAR".into(), "beta_value".into()),
("VSCODE_VAR".into(), "vscode_value".into()),
("APP1_TOKEN".into(), "app1_token".into()),
("APP2_TOKEN".into(), "app2_token".into()),
("APP1_NAME".into(), "app1_value".into()),
("APP2_NAME".into(), "app2_value".into()),
("APP1_PASSWORD".into(), "app1_password".into()),
("OXLINT_TSGOLINT_PATH".into(), "/path/to/oxlint_tsgolint".into()),
("PATH".into(), "/usr/bin".into()),
("HOME".into(), "/home/user".into()),
];
// Resolve envs multiple times
let result1 =
TaskEnvs::resolve(mock_envs.clone().into_iter(), base_dir, &resolved_task_config)
.unwrap();
let result2 =
TaskEnvs::resolve(mock_envs.clone().into_iter(), base_dir, &resolved_task_config)
.unwrap();
let result3 =
TaskEnvs::resolve(mock_envs.clone().into_iter(), base_dir, &resolved_task_config)
.unwrap();
// Convert to sorted vecs for comparison
let mut envs1: Vec<_> = result1.envs_without_pass_through.iter().collect();
let mut envs2: Vec<_> = result2.envs_without_pass_through.iter().collect();
let mut envs3: Vec<_> = result3.envs_without_pass_through.iter().collect();
envs1.sort();
envs2.sort();
envs3.sort();
// Verify all resolutions produce the same result
assert_eq!(envs1, envs2);
assert_eq!(envs2, envs3);
// Verify all expected variables are present
assert_eq!(envs1.len(), 9);
assert!(envs1.iter().any(|(k, _)| k.as_str() == "ALPHA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "BETA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "MIDDLE_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "ZEBRA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "APP1_NAME"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "APP2_NAME"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "APP1_PASSWORD"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "APP1_TOKEN"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "APP2_TOKEN"));
// APP1_PASSWORD should be hashed
let password = result1.envs_without_pass_through.get("APP1_PASSWORD").unwrap();
assert_eq!(
password,
"sha256:17f1ef795d5663faa129f6fe3e5335e67ac7a701d1a70533a5f4b1635413a1aa"
);
// Verify default pass-through envs are present
let all_envs = result1.all_envs;
assert!(all_envs.contains_key("VSCODE_VAR"));
assert!(all_envs.contains_key("PATH"));
assert!(all_envs.contains_key("HOME"));
assert!(all_envs.contains_key("APP1_NAME"));
assert!(all_envs.contains_key("APP2_NAME"));
assert!(all_envs.contains_key("APP1_PASSWORD"));
assert!(all_envs.contains_key("APP1_TOKEN"));
assert!(all_envs.contains_key("APP2_TOKEN"));
assert!(all_envs.contains_key("OXLINT_TSGOLINT_PATH"));
// VITE_TASK_EXECUTION_ENV should always be added automatically
assert!(all_envs.contains_key("VITE_TASK_EXECUTION_ENV"));
let env_value = all_envs.get("VITE_TASK_EXECUTION_ENV").unwrap();
assert_eq!(env_value.to_str().unwrap(), "1");
// VITE_TASK_EXECUTION_ENV should not be in envs_without_pass_through since it's not declared
assert!(!result1.envs_without_pass_through.contains_key("VITE_TASK_EXECUTION_ENV"));
}
#[test]
#[cfg(unix)]
fn test_unix_env_case_sensitive() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
// Test that Unix environment variable matching is case-sensitive
// Unix env vars are case-sensitive, so PATH and path are different
// Create a task config with envs in different cases
let mut envs = HashSet::new();
envs.insert("TEST_VAR".into());
envs.insert("test_var".into()); // Different variable on Unix
envs.insert("Test_Var".into()); // Different variable on Unix
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs,
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved_task_config =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
// Create mock environment variables with different cases
let mock_envs = vec![
("TEST_VAR".into(), "uppercase".into()),
("test_var".into(), "lowercase".into()),
("Test_Var".into(), "mixed".into()),
];
// Resolve envs
let result = TaskEnvs::resolve(
mock_envs.into_iter(),
AbsolutePath::new("/tmp").unwrap(),
&resolved_task_config,
)
.unwrap();
let envs_without_pass_through = result.envs_without_pass_through;
// On Unix, all three should be treated as separate variables
assert_eq!(
envs_without_pass_through.len(),
3,
"Unix should treat different cases as different variables"
);
assert_eq!(
envs_without_pass_through.get("TEST_VAR").map(vite_str::Str::as_str),
Some("uppercase")
);
assert_eq!(
envs_without_pass_through.get("test_var").map(vite_str::Str::as_str),
Some("lowercase")
);
assert_eq!(
envs_without_pass_through.get("Test_Var").map(vite_str::Str::as_str),
Some("mixed")
);
}
#[test]
#[cfg(windows)]
fn test_windows_env_case_insensitive() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
// Create a task config with multiple envs in a HashSet
let mut envs = HashSet::new();
envs.insert("ZEBRA_VAR".into());
envs.insert("ALPHA_VAR".into());
envs.insert("MIDDLE_VAR".into());
envs.insert("BETA_VAR".into());
envs.insert("NOT_EXISTS_VAR".into());
envs.insert("APP?_*".into());
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs,
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved_task_config =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
// Create mock environment variables
let mock_envs = vec![
("ZEBRA_VAR".into(), "zebra_value".into()),
("ALPHA_VAR".into(), "alpha_value".into()),
("MIDDLE_VAR".into(), "middle_value".into()),
("BETA_VAR".into(), "beta_value".into()),
("VSCODE_VAR".into(), "vscode_value".into()),
("app1_name".into(), "app1_value".into()),
("app2_name".into(), "app2_value".into()),
("Path".into(), "C:\\Windows\\System32".into()),
];
// Resolve envs multiple times
let result1 = TaskEnvs::resolve(
mock_envs.clone().into_iter(),
AbsolutePath::new("C:\\tmp").unwrap(),
&resolved_task_config,
)
.unwrap();
let result2 = TaskEnvs::resolve(
mock_envs.clone().into_iter(),
AbsolutePath::new("C:\\tmp").unwrap(),
&resolved_task_config,
)
.unwrap();
let result3 = TaskEnvs::resolve(
mock_envs.clone().into_iter(),
AbsolutePath::new("C:\\tmp").unwrap(),
&resolved_task_config,
)
.unwrap();
// Convert to sorted vecs for comparison
let mut envs1: Vec<_> = result1.envs_without_pass_through.iter().collect();
let mut envs2: Vec<_> = result2.envs_without_pass_through.iter().collect();
let mut envs3: Vec<_> = result3.envs_without_pass_through.iter().collect();
envs1.sort();
envs2.sort();
envs3.sort();
// Verify all resolutions produce the same result
assert_eq!(envs1, envs2);
assert_eq!(envs2, envs3);
// Verify all expected variables are present
assert_eq!(envs1.len(), 6);
assert!(envs1.iter().any(|(k, _)| k.as_str() == "ALPHA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "BETA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "MIDDLE_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "ZEBRA_VAR"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "app1_name"));
assert!(envs1.iter().any(|(k, _)| k.as_str() == "app1_name"));
// Verify default pass-through envs are present
let all_envs = result1.all_envs;
assert!(all_envs.contains_key("VSCODE_VAR"));
assert!(all_envs.contains_key("Path") || all_envs.contains_key("PATH"));
assert!(all_envs.contains_key("app1_name"));
assert!(all_envs.contains_key("app2_name"));
}
#[test]
#[cfg(windows)]
fn test_windows_path_case_insensitive_mixed_case() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs: HashSet::new(),
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
// Mock environment with mixed case "Path" (common on Windows)
let mock_envs = vec![
(OsString::from("Path"), OsString::from("C:\\existing\\path")),
(OsString::from("OTHER_VAR"), OsString::from("value")),
];
let base_dir = AbsolutePath::new("C:\\workspace\\packages\\app").unwrap();
let result = TaskEnvs::resolve(mock_envs.into_iter(), &base_dir, &resolved).unwrap();
let all_envs = result.all_envs;
// Verify that the original "Path" casing is preserved, not "PATH"
assert!(all_envs.contains_key("Path"));
assert!(!all_envs.contains_key("PATH"));
// Verify the complete PATH value matches expected
let path_value = all_envs.get("Path").unwrap();
assert_eq!(
path_value.as_ref(),
OsStr::new(
"C:\\workspace\\packages\\app\\node_modules\\.bin;C:\\workspace\\packages\\app\\node_modules\\.bin;C:\\existing\\path"
)
);
// Verify no duplicate PATH entry was created
let path_like_keys: Vec<_> =
all_envs.keys().filter(|k| k.eq_ignore_ascii_case("path")).collect();
assert_eq!(path_like_keys.len(), 1);
}
#[test]
#[cfg(windows)]
fn test_windows_path_case_insensitive_uppercase() {
use crate::{
collections::HashSet,
config::{ResolvedTaskConfig, TaskCommand, TaskConfig},
};
let task_config = TaskConfig {
command: TaskCommand::ShellScript("echo test".into()),
cwd: RelativePathBuf::default(),
cacheable: true,
inputs: HashSet::new(),
envs: HashSet::new(),
pass_through_envs: HashSet::new(),
fingerprint_ignores: None,
};
let resolved =
ResolvedTaskConfig { config_dir: RelativePathBuf::default(), config: task_config };
// Mock environment with uppercase "PATH"
let mock_envs = vec![
(OsString::from("PATH"), OsString::from("C:\\existing\\path")),
(OsString::from("OTHER_VAR"), OsString::from("value")),
];
let base_dir = AbsolutePath::new("C:\\workspace\\packages\\app").unwrap();
let result = TaskEnvs::resolve(mock_envs.into_iter(), &base_dir, &resolved).unwrap();
let all_envs = result.all_envs;
// Verify the complete PATH value matches expected
let path_value = all_envs.get("PATH").unwrap();
assert_eq!(
path_value.as_ref(),
OsStr::new(
"C:\\workspace\\packages\\app\\node_modules\\.bin;C:\\workspace\\packages\\app\\node_modules\\.bin;C:\\existing\\path"
)
);
}