-
Notifications
You must be signed in to change notification settings - Fork 51
/
environment.rs
2382 lines (2053 loc) · 84.6 KB
/
environment.rs
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::borrow::Cow;
use std::collections::HashMap;
#[cfg(target_os = "macos")]
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs::{self, File};
use std::io::{stdin, stdout, Write};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::FromStr;
use std::{env, vec};
use anyhow::{anyhow, bail, Context, Result};
use bpaf::Bpaf;
use crossterm::tty::IsTty;
use flox_rust_sdk::flox::{EnvironmentName, EnvironmentOwner, EnvironmentRef, Flox};
use flox_rust_sdk::models::environment::managed_environment::{
ManagedEnvironment,
ManagedEnvironmentError,
PullResult,
};
use flox_rust_sdk::models::environment::path_environment::{self};
use flox_rust_sdk::models::environment::{
CanonicalPath,
CoreEnvironmentError,
EditResult,
Environment,
EnvironmentError2,
EnvironmentPointer,
ManagedPointer,
PathPointer,
UpdateResult,
DOT_FLOX,
ENVIRONMENT_POINTER_FILENAME,
FLOX_ACTIVE_ENVIRONMENTS_VAR,
FLOX_ENV_CACHE_VAR,
FLOX_ENV_DIRS_VAR,
FLOX_ENV_LIB_DIRS_VAR,
FLOX_ENV_PROJECT_VAR,
FLOX_ENV_VAR,
FLOX_PATH_PATCHED_VAR,
FLOX_PROMPT_ENVIRONMENTS_VAR,
};
use flox_rust_sdk::models::lockfile::{
Input,
InstalledPackage,
LockedManifest,
LockedManifestError,
PackageInfo,
TypedLockedManifest,
};
use flox_rust_sdk::models::manifest::{self, PackageToInstall};
use flox_rust_sdk::models::pkgdb::{self, error_codes, CallPkgDbError, PkgDbError, ScrapeError};
use indexmap::IndexSet;
use indoc::{formatdoc, indoc};
use itertools::Itertools;
use log::{debug, warn};
use toml_edit::Document;
use tracing::instrument;
use url::Url;
use super::{environment_select, EnvironmentSelect};
use crate::commands::{
activated_environments,
ensure_environment_trust,
ensure_floxhub_token,
environment_description,
ConcreteEnvironment,
EnvironmentSelectError,
UninitializedEnvironment,
};
use crate::config::Config;
use crate::utils::dialog::{Confirm, Dialog, Select, Spinner};
use crate::utils::didyoumean::{DidYouMean, InstallSuggestion};
use crate::utils::errors::{
apply_doc_link_for_unsupported_packages,
display_chain,
format_core_error,
format_locked_manifest_error,
};
use crate::utils::openers::Shell;
use crate::utils::{default_nix_env_vars, message};
use crate::{subcommand_metric, utils};
// Edit declarative environment configuration
#[derive(Bpaf, Clone)]
pub struct Edit {
#[bpaf(external(environment_select), fallback(Default::default()))]
environment: EnvironmentSelect,
#[bpaf(external(edit_action), fallback(EditAction::EditManifest{file: None}))]
action: EditAction,
}
#[derive(Bpaf, Clone)]
pub enum EditAction {
EditManifest {
/// Replace environment manifest with that in <file>
#[bpaf(long, short, argument("file"))]
file: Option<PathBuf>,
},
Rename {
/// Rename the environment to <name>
#[bpaf(long, short, argument("name"))]
name: EnvironmentName,
},
}
impl Edit {
#[instrument(name = "edit", skip_all)]
pub async fn handle(self, mut flox: Flox) -> Result<()> {
subcommand_metric!("edit");
let detected_environment = self
.environment
.detect_concrete_environment(&flox, "edit")?;
// Ensure the user is logged in for the following remote operations
if let ConcreteEnvironment::Remote(_) = detected_environment {
ensure_floxhub_token(&mut flox).await?;
};
match self.action {
EditAction::EditManifest { file } => {
// TODO: differentiate between interactive edits and replacement
let span = tracing::info_span!("edit");
let _guard = span.enter();
Self::edit_manifest(&flox, detected_environment, file).await?
},
EditAction::Rename { name } => {
let span = tracing::info_span!("rename");
let _guard = span.enter();
if let ConcreteEnvironment::Path(mut environment) = detected_environment {
let old_name = environment.name();
if name == old_name {
bail!("environment already named {name}");
}
environment.rename(name.clone())?;
message::updated(format!("renamed environment {old_name} to {name}"));
} else {
// todo: handle remote environments in the future
bail!("Cannot rename environments on FloxHub");
}
},
}
Ok(())
}
async fn edit_manifest(
flox: &Flox,
detected_environment: ConcreteEnvironment,
file: Option<PathBuf>,
) -> Result<()> {
let active_environment =
UninitializedEnvironment::from_concrete_environment(&detected_environment)?;
let mut environment = detected_environment.into_dyn_environment();
let result = match Self::provided_manifest_contents(file)? {
// If provided with the contents of a manifest file, either via a path to a file or via
// contents piped to stdin, use those contents to try building the environment.
Some(new_manifest) => environment
.edit(flox, new_manifest)
.map_err(apply_doc_link_for_unsupported_packages)?,
// If not provided with new manifest contents, let the user edit the file directly
// via $EDITOR or $VISUAL (as long as `flox edit` was invoked interactively).
None => Self::interactive_edit(flox, environment.as_mut()).await?,
};
// outside the match to avoid rustfmt falling on its face
let reactivate_required_note = indoc! {"
Your manifest has changes that cannot be automatically applied to your current environment.
Please 'exit' the environment and run 'flox activate' to see these changes.
"};
match result {
EditResult::Unchanged => {
message::warning("No changes made to environment.");
},
EditResult::ReActivateRequired { .. }
if activated_environments().is_active(&active_environment) =>
{
message::warning(reactivate_required_note)
},
EditResult::ReActivateRequired { .. } => {
message::updated("Environment successfully updated.")
},
EditResult::Success { .. } => message::updated("Environment successfully updated."),
}
Ok(())
}
/// Interactively edit the manifest file
async fn interactive_edit(
flox: &Flox,
environment: &mut dyn Environment,
) -> Result<EditResult> {
if !Dialog::can_prompt() {
bail!("Can't edit interactively in non-interactive context")
}
let editor = Self::determine_editor()?;
// Make a copy of the manifest for the user to edit so failed edits aren't left in
// the original manifest. You can't put creation/cleanup inside the `edited_manifest_contents`
// method because the temporary manifest needs to stick around in case the user wants
// or needs to make successive edits without starting over each time.
let tmp_manifest = tempfile::Builder::new()
.prefix("manifest.")
.suffix(".toml")
.tempfile_in(&flox.temp_dir)?;
std::fs::write(&tmp_manifest, environment.manifest_content(flox)?)?;
let should_continue = Dialog {
message: "Continue editing?",
help_message: Default::default(),
typed: Confirm {
default: Some(true),
},
};
// Let the user keep editing the file until the build succeeds or the user
// decides to stop.
loop {
let new_manifest = Edit::edited_manifest_contents(&tmp_manifest, &editor)?;
let result = Dialog {
message: "Building environment to validate edit...",
help_message: None,
typed: Spinner::new(|| environment.edit(flox, new_manifest.clone())),
}
.spin()
.map_err(apply_doc_link_for_unsupported_packages);
match result {
Err(EnvironmentError2::Core(CoreEnvironmentError::LockedManifest(e))) => {
message::error(format_locked_manifest_error(&e));
if !Dialog::can_prompt() {
bail!("Can't prompt to continue editing in non-interactive context");
}
if !should_continue.clone().prompt().await? {
bail!("Environment editing cancelled");
}
},
Err(e) => {
bail!(e)
},
Ok(result) => {
return Ok(result);
},
}
}
}
/// Determines the editor to use for interactive editing
///
/// If $EDITOR or $VISUAL is set, use that. Otherwise, try to find a known editor in $PATH.
/// The known editor selected is the first one found in $PATH from the following list:
///
/// vim, vi, nano, emacs.
fn determine_editor() -> Result<PathBuf> {
let editor = std::env::var("EDITOR").or(std::env::var("VISUAL")).ok();
if let Some(editor) = editor {
return Ok(PathBuf::from(editor));
}
let path_var = env::var("PATH").context("$PATH not set")?;
let (path, editor) = env::split_paths(&path_var)
.cartesian_product(["vim", "vi", "nano", "emacs"])
.find(|(path, editor)| path.join(editor).exists())
.context("no known editor found in $PATH")?;
debug!("Using editor {:?} from {:?}", editor, path);
Ok(path.join(editor))
}
/// Retrieves the new manifest file contents if a new manifest file was provided
fn provided_manifest_contents(file: Option<PathBuf>) -> Result<Option<String>> {
if let Some(ref file) = file {
let mut file: Box<dyn std::io::Read + Send> = if file == Path::new("-") {
Box::new(stdin())
} else {
Box::new(File::open(file).unwrap())
};
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(Some(contents))
} else {
Ok(None)
}
}
/// Gets a new set of manifest contents after a user edits the file
fn edited_manifest_contents(
path: impl AsRef<Path>,
editor: impl AsRef<Path>,
) -> Result<String> {
let mut command = Command::new(editor.as_ref());
command.arg(path.as_ref());
let child = command.spawn().context("editor command failed")?;
let _ = child.wait_with_output().context("editor command failed")?;
let contents = std::fs::read_to_string(path)?;
Ok(contents)
}
}
// Delete an environment
#[derive(Bpaf, Clone)]
pub struct Delete {
/// Delete an environment without confirmation.
#[bpaf(short, long)]
force: bool,
#[bpaf(external(environment_select), fallback(Default::default()))]
environment: EnvironmentSelect,
}
impl Delete {
#[instrument(name = "delete", skip_all)]
pub async fn handle(self, flox: Flox) -> Result<()> {
subcommand_metric!("delete");
let environment = self
.environment
.detect_concrete_environment(&flox, "delete")?;
let description = environment_description(&environment)?;
if matches!(environment, ConcreteEnvironment::Remote(_)) {
let message = formatdoc! {"
Environment {description} was not deleted.
Remote environments on FloxHub can not yet be deleted.
"};
bail!("{message}")
}
let comfirm = Dialog {
message: &format!(
"You are about to delete your environment {description}. Are you sure?"
),
help_message: Some("Use `-f` to force deletion"),
typed: Confirm {
default: Some(false),
},
};
if !self.force && Dialog::can_prompt() && !comfirm.prompt().await? {
bail!("Environment deletion cancelled");
}
match environment {
ConcreteEnvironment::Path(environment) => environment.delete(&flox),
ConcreteEnvironment::Managed(environment) => environment.delete(&flox),
ConcreteEnvironment::Remote(_) => unreachable!(),
}?;
message::deleted(format!("environment {description} deleted"));
Ok(())
}
}
/// When called with no arguments 'flox activate' will look for a '.flox' directory
/// in the current directory. Calling 'flox activate' in your home directory will
/// activate a default environment. Environments in other directories and remote
/// environments are activated with the '-d' and '-r' flags respectively.
#[derive(Bpaf, Clone)]
pub struct Activate {
#[bpaf(external(environment_select), fallback(Default::default()))]
environment: EnvironmentSelect,
/// Trust a remote environment temporarily for this activation
#[bpaf(long, short)]
trust: bool,
/// Print an activation script to stdout instead of spawning a subshell
#[bpaf(long("print-script"), short, hide)]
print_script: bool,
/// Command to run interactively in the context of the environment
#[bpaf(positional("cmd"), strict, many)]
run_args: Vec<String>,
}
impl Activate {
pub async fn handle(self, mut config: Config, flox: Flox) -> Result<()> {
let mode = match self.environment {
EnvironmentSelect::Dir(_) => "dir",
EnvironmentSelect::Remote(_) => "remote",
EnvironmentSelect::Unspecified => "unspecified",
};
let span = tracing::info_span!("activate", mode, shell = tracing::field::Empty);
let _guard = span.enter();
subcommand_metric!("activate");
let mut concrete_environment = self.environment.to_concrete_environment(&flox)?;
// TODO could move this to a pretty print method on the Environment trait?
let prompt_name = match concrete_environment {
// Note that the same environment could show up twice without any
// indication of which comes from which path
ConcreteEnvironment::Path(ref path) => path.name().to_string(),
ConcreteEnvironment::Managed(ref managed) => {
format!("{}/{}", managed.owner(), managed.name())
},
ConcreteEnvironment::Remote(ref remote) => {
format!("{}/{}", remote.owner(), remote.name())
},
};
if let ConcreteEnvironment::Remote(ref env) = concrete_environment {
if !self.trust {
ensure_environment_trust(&mut config, &flox, env).await?;
}
}
let now_active =
UninitializedEnvironment::from_concrete_environment(&concrete_environment)?;
let environment = concrete_environment.dyn_environment_ref_mut();
let in_place = self.print_script || (!stdout().is_tty() && self.run_args.is_empty());
// Don't spin in bashrcs and similar contexts
let activation_path_result = if in_place {
environment.activation_path(&flox)
} else {
Dialog {
message: &format!("Getting ready to use environment {now_active}..."),
help_message: None,
typed: Spinner::new(|| environment.activation_path(&flox)),
}
.spin()
};
let activation_path = match activation_path_result {
Err(EnvironmentError2::Core(CoreEnvironmentError::LockedManifest(
LockedManifestError::BuildEnv(CallPkgDbError::PkgDbError(PkgDbError {
exit_code: error_codes::LOCKFILE_INCOMPATIBLE_SYSTEM,
..
})),
))) => {
let mut message = format!(
"This environment is not yet compatible with your system ({system}).",
system = flox.system
);
if let ConcreteEnvironment::Remote(remote) = &concrete_environment {
message.push_str("\n\n");
message.push_str(&format!(
"Use 'flox pull --force {}/{}' to update and verify this environment on your system.",
remote.owner(),
remote.name()));
}
bail!("{message}")
},
other => other?,
};
// We don't have access to the current PS1 (it's not exported), so we
// can't modify it. Instead set FLOX_PROMPT_ENVIRONMENTS and let the
// activation script set PS1 based on that.
let flox_prompt_environments = env::var(FLOX_PROMPT_ENVIRONMENTS_VAR)
.map_or(prompt_name.clone(), |prompt_environments| {
format!("{prompt_name} {prompt_environments}")
});
let mut flox_active_environments = activated_environments();
// install prefixes of all active environments
let flox_env_install_prefixes = IndexSet::from_iter(env::split_paths(
&env::var(FLOX_ENV_DIRS_VAR).unwrap_or_default(),
));
// on macos: patch the existing PATH
// If this is [Some] the path will be restored from `$FLOX_PATH_PATCHED`
// As part of running $FLOX_ENV/etc/profile.d/0100_common-paths.sh during activation.
//
// NOTE: this does _not_ include any additions to the PATH
// due to the newly activated environment.
// Amending the path is strictly implemented by the activation scripts!
let fixed_up_original_path_joined =
Self::fixup_path(&flox_env_install_prefixes).transpose()?;
// Detect if the current environment is already active
if flox_active_environments.is_active(&now_active) {
if !in_place {
// Error if interactive and already active
bail!("Environment '{now_active}' is already active.");
}
debug!("Environment is already active: environment={now_active}. Ignoring activation (may patch PATH)");
drop(_guard); // don't want to record the time inside the environment
Self::reactivate_in_place(fixed_up_original_path_joined)?;
return Ok(());
}
// Add to _FLOX_ACTIVE_ENVIRONMENTS so we can detect what environments are active.
flox_active_environments.set_last_active(now_active.clone());
// Prepend the new environment to the list of active environments
let flox_env_install_prefixes = {
let mut set = IndexSet::from([activation_path.clone()]);
set.extend(flox_env_install_prefixes);
set
};
// Set FLOX_ENV_DIRS and FLOX_ENV_LIB_DIRS
let (flox_env_dirs_joined, flox_env_lib_dirs_joined) = {
let flox_env_lib_dirs = flox_env_install_prefixes.iter().map(|p| p.join("lib"));
let flox_env_dirs = env::join_paths(&flox_env_install_prefixes).context(
"Cannot activate environment because its path contains an invalid character",
)?;
let flox_env_lib_dirs = env::join_paths(flox_env_lib_dirs).context(
"Cannot activate environment because its path contains an invalid character",
)?;
(flox_env_dirs, flox_env_lib_dirs)
};
let prompt_color_1 = env::var("FLOX_PROMPT_COLOR_1")
.unwrap_or(utils::colors::INDIGO_400.to_ansi256().to_string());
let prompt_color_2 = env::var("FLOX_PROMPT_COLOR_2")
.unwrap_or(utils::colors::INDIGO_300.to_ansi256().to_string());
let mut exports = HashMap::from([
(FLOX_ENV_VAR, activation_path.to_string_lossy().to_string()),
(FLOX_PROMPT_ENVIRONMENTS_VAR, flox_prompt_environments),
(
FLOX_ACTIVE_ENVIRONMENTS_VAR,
flox_active_environments.to_string(),
),
(
FLOX_ENV_DIRS_VAR,
flox_env_dirs_joined.to_string_lossy().to_string(),
),
(
FLOX_ENV_LIB_DIRS_VAR,
flox_env_lib_dirs_joined.to_string_lossy().to_string(),
),
(
FLOX_ENV_CACHE_VAR,
environment.cache_path()?.to_string_lossy().to_string(),
),
(
FLOX_ENV_PROJECT_VAR,
environment.project_path()?.to_string_lossy().to_string(),
),
("FLOX_PROMPT_COLOR_1", prompt_color_1),
("FLOX_PROMPT_COLOR_2", prompt_color_2),
]);
exports.extend(default_nix_env_vars());
if let Some(fixed_up_original_path_joined) = fixed_up_original_path_joined {
exports.insert(
FLOX_PATH_PATCHED_VAR,
fixed_up_original_path_joined.to_string_lossy().to_string(),
);
}
// when output is not a tty, and no command is provided
// we just print an activation script to stdout
//
// That script can then be `eval`ed in the current shell,
// e.g. in a .bashrc or .zshrc file:
//
// eval "$(flox activate)"
if in_place {
let shell = Self::detect_shell_for_in_place()?;
// The shell type isn't known when the span is created, so we fill it in afterwards
span.record("shell", shell.to_string());
Self::activate_in_place(&shell, &exports, &activation_path);
return Ok(());
}
let shell = Self::detect_shell_for_subshell()?;
// The shell type isn't known when the span is created, so we fill it in afterwards
span.record("shell", shell.to_string());
let activate_error = if !self.run_args.is_empty() {
drop(_guard); // don't want to record the time inside the command
Self::activate_command(self.run_args, shell, exports, activation_path)
} else {
drop(_guard); // don't want to record the time inside the environment
Self::activate_interactive(shell, exports, activation_path, now_active)
};
// If we get here, exec failed!
Err(activate_error)
}
/// Used for `flox activate -- run_args`
fn activate_command(
run_args: Vec<String>,
shell: Shell,
exports: HashMap<&str, String>,
activation_path: PathBuf,
) -> anyhow::Error {
let mut command = Command::new(shell.exe_path());
command.envs(exports);
let script = formatdoc! {r#"
# to avoid infinite recursion sourcing bashrc
export FLOX_SOURCED_FROM_SHELL_RC=1
# TODO: this script sets prompt, which isn't necessary
source {activation_path}/activate/{shell}
unset FLOX_SOURCED_FROM_SHELL_RC
{quoted_args}
"#,
activation_path=shell_escape::escape(activation_path.to_string_lossy()),
quoted_args = Self::quote_run_args(&run_args)
};
command.arg("-c");
command.arg(script);
debug!("running activation command: {:?}", command);
// exec should never return
command.exec().into()
}
/// Activate the environment interactively by spawning a new shell
/// and running the respective activation scripts.
///
/// This function should never return as it replaces the current process
fn activate_interactive(
shell: Shell,
exports: HashMap<&str, String>,
activation_path: PathBuf,
now_active: UninitializedEnvironment,
) -> anyhow::Error {
let mut command = Command::new(shell.exe_path());
command.envs(exports);
match shell {
Shell::Bash(_) => {
command
.arg("--rcfile")
.arg(activation_path.join("activate").join("bash"));
},
Shell::Zsh(_) => {
// From man zsh:
// Commands are then read from $ZDOTDIR/.zshenv. If the shell is a
// login shell, commands are read from /etc/zprofile and then
// $ZDOTDIR/.zprofile. Then, if the shell is interactive, commands
// are read from /etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if
// the shell is a login shell, /etc/zlogin and $ZDOTDIR/.zlogin are
// read.
//
// We want to add our customizations as late as possible in the
// initialization process - if, e.g. the user has prompt
// customizations, we want ours to go last. So we put our
// customizations at the end of .zshrc, passing our customizations
// using FLOX_ZSH_INIT_SCRIPT.
// Otherwise, we want initialization to proceed as normal, so the
// files in our ZDOTDIR source global rcs and user rcs.
// We disable global rc files and instead source them manually so we
// can control the ZDOTDIR they are run with - this is important
// since macOS sets
// HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history
// in /etc/zshrc.
if let Ok(zdotdir) = env::var("ZDOTDIR") {
command.env("FLOX_ORIG_ZDOTDIR", zdotdir);
}
command
.env("ZDOTDIR", env!("FLOX_ZDOTDIR"))
.env(
"FLOX_ZSH_INIT_SCRIPT",
activation_path.join("activate").join("zsh"),
)
.arg("--no-globalrcs");
},
};
debug!("running activation command: {:?}", command);
let message = formatdoc! {"
You are now using the environment {now_active}.
To stop using this environment, type 'exit'\n"};
message::updated(message);
// exec should never return
command.exec().into()
}
/// Patch the PATH to undo the effects of `/usr/libexec/path_helper`
///
/// Darwin has a "path_helper" which indiscriminately reorders the path
/// to put the system curated path items first in the `PATH`,
/// which completely breaks the user's ability to manage their `PATH` in subshells,
/// e.g. when using tmux.
///
/// On macos `/usr/libexec/path_helper` is typically invoked from
/// default shell rc files, e.g. `/etc/profile` and `/etc/zprofile`.
///
/// Note: since the "path_helper" i only invoked by login shells,
/// we only need to setup the PATH patching for `flox activate` in shell rc files.
///
/// ## Example
///
/// > User has `eval "$(flox activate)"` in their `.zshrc`.
///
/// Without the path patching, the following happens:
///
/// 1. Open a new terminal (login shell)
/// -> `path_helper` runs (`PATH=<default envs>`)
/// -> `flox activate` runs (`PATH=<flox_env>:<default envs>`)
/// 2. Open a new tmux session (login shell by default)
/// -> `path_helper` runs (`PATH=<default envs>:<flox_env>`)
/// -> `flox activate` runs
/// -> ⚡️ environment already active, activate skipped
/// without path patching: `PATH:<default envs>:<flox_env>` ❌
/// with path patching: `PATH:<flox_env>:<default envs>` ✅ flox env is not shadowed
///
/// ## Implementation
///
/// This function attempts to undo the effects of `/usr/libexec/path_helper`
/// by partitioning the `PATH` into two parts:
/// 1. known paths of activated flox environments
/// and nix store paths (e.g. `/nix/store/...`) -- assumed to be `nix develop` paths
/// 2. everything else
///
/// The `PATH` is then reordered to put the flox environment and nix store paths first.
/// The order within the two partitions is preserved.
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] // on linux `flox_env_dirs` is not used
fn fixup_path(flox_env_dirs: &IndexSet<PathBuf>) -> Option<Result<OsString>> {
#[cfg(not(target_os = "macos"))]
{
None
}
#[cfg(target_os = "macos")]
{
if !Path::new("/usr/libexec/path_helper").exists() {
return None;
}
let path_var = env::var("PATH").unwrap_or_default();
let fixed_up_path = Self::fixup_path_with(path_var, flox_env_dirs);
let fixed_up_path_joined = env::join_paths(fixed_up_path).context(
"Cannot activate environment because its path contains an invalid character",
);
Some(fixed_up_path_joined)
}
}
/// Patch a given PATH value to undo the effects of `/usr/libexec/path_helper`
///
/// See [Self::fixup_path] for more details.
#[cfg(target_os = "macos")]
fn fixup_path_with(
path_var: impl AsRef<OsStr>,
flox_env_dirs: &IndexSet<PathBuf>,
) -> Vec<PathBuf> {
let path_iter = env::split_paths(&path_var);
let (flox_and_nix_path, path) = path_iter.partition::<Vec<_>, _>(|path| {
let is_flox_path = path
.parent()
.map(|path| flox_env_dirs.contains(path))
.unwrap_or_else(|| flox_env_dirs.contains(path));
path.starts_with("/nix/store") || is_flox_path
});
[flox_and_nix_path, path].into_iter().flatten().collect()
}
/// Used when the activated environment is already active
/// and executed non-interactively -- e.g. from a .bashrc.
///
/// In the general case, this function produces a noop shell function
///
/// eval "$(flox activate)" -> eval "true"
///
/// On macOS, we need to patch the PATH
/// to undo the effects of /usr/libexec/path_helper
///
/// eval "$(flox activate)" -> eval "export PATH=<flox_env_dirs>:$PATH"
///
/// See [Self::fixup_path] for more details.
fn reactivate_in_place(fixed_up_path_joined: Option<OsString>) -> Result<(), anyhow::Error> {
if let Some(fixed_up_path_joined) = fixed_up_path_joined {
debug!(
"Patching PATH to {}",
fixed_up_path_joined.to_string_lossy()
);
println!(
"export PATH={}",
shell_escape::escape(fixed_up_path_joined.to_string_lossy())
);
} else {
debug!("No path patching needed");
};
Ok(())
}
/// Used for `eval "$(flox activate)"`
fn activate_in_place(shell: &Shell, exports: &HashMap<&str, String>, activation_path: &Path) {
let exports_rendered = exports
.iter()
.map(|(key, value)| (key, shell_escape::escape(Cow::Borrowed(value))))
.map(|(key, value)| format!("export {key}={value}",))
.join("\n");
let script = formatdoc! {"
# Common flox environment variables
{exports_rendered}
# to avoid infinite recursion sourcing bashrc
export FLOX_SOURCED_FROM_SHELL_RC=1
source {activation_path}/activate/{shell}
unset FLOX_SOURCED_FROM_SHELL_RC
",
activation_path=shell_escape::escape(activation_path.to_string_lossy()),
};
println!("{script}");
}
/// Quote run args so that words don't get split,
/// but don't escape all characters.
///
/// To do this we escape `"`,
/// but we don't escape anything else.
/// We want `$` for example to be expanded by the shell.
fn quote_run_args(run_args: &[String]) -> String {
run_args
.iter()
.map(|arg| format!(r#""{}""#, arg.replace('"', r#"\""#)))
.join(" ")
}
/// Detect the shell to use for activation
///
/// Used to determine shell for
/// `flox activate` and `flox activate -- CMD`
fn detect_shell_for_subshell() -> Result<Shell> {
Shell::detect_from_env("FLOX_SHELL").or_else(|_| Shell::detect_from_env("SHELL"))
}
/// Detect the shell to use for in-place activation
///
/// Used to determine shell for `eval "$(flox activate)"` / `flox activate --print-script`
fn detect_shell_for_in_place() -> Result<Shell> {
Self::detect_shell_for_in_place_with(Shell::detect_from_parent_process)
}
/// Utility method for testing implementing the logic of shell detection
/// for in-place activation, generically over a parent shell detection function.
fn detect_shell_for_in_place_with(
parent_shell_fn: impl Fn() -> Result<Shell>,
) -> Result<Shell> {
Shell::detect_from_env("FLOX_SHELL")
.or_else(|_| parent_shell_fn())
.or_else(|err| {
warn!("Failed to detect shell from environment: {err}");
Shell::detect_from_env("SHELL")
})
}
}
#[cfg(test)]
mod activate_tests {
use super::*;
#[cfg(target_os = "macos")]
const PATH: &str =
"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/flox/env/bin:/nix/store/some/bin";
#[test]
#[cfg(target_os = "macos")]
fn test_fixup_path() {
let flox_env_dirs = IndexSet::from(["/flox/env"].map(PathBuf::from));
let fixed_up_path = Activate::fixup_path_with(PATH, &flox_env_dirs);
let joined = env::join_paths(fixed_up_path).unwrap();
assert_eq!(
joined.to_string_lossy(),
"/flox/env/bin:/nix/store/some/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
"PATH was not reordered correctly"
);
}
const SHELL_SET: (&'_ str, Option<&'_ str>) = ("SHELL", Some("/shell/bash"));
const FLOX_SHELL_SET: (&'_ str, Option<&'_ str>) = ("FLOX_SHELL", Some("/flox_shell/bash"));
const SHELL_UNSET: (&'_ str, Option<&'_ str>) = ("SHELL", None);
const FLOX_SHELL_UNSET: (&'_ str, Option<&'_ str>) = ("FLOX_SHELL", None);
const PARENT_DETECTED: &dyn Fn() -> Result<Shell> = &|| Ok(Shell::Bash("/parent/bash".into()));
const PARENT_UNDETECTED: &dyn Fn() -> Result<Shell> =
&|| Err(anyhow::anyhow!("parent shell detection failed"));
#[test]
fn test_detect_shell_for_subshell() {
temp_env::with_vars([FLOX_SHELL_UNSET, SHELL_SET], || {
let shell = Activate::detect_shell_for_subshell().unwrap();
assert_eq!(shell, Shell::Bash("/shell/bash".into()));
});
temp_env::with_vars([FLOX_SHELL_SET, SHELL_SET], || {
let shell = Activate::detect_shell_for_subshell().unwrap();
assert_eq!(shell, Shell::Bash("/flox_shell/bash".into()));
});
temp_env::with_vars([FLOX_SHELL_UNSET, SHELL_UNSET], || {
let shell = Activate::detect_shell_for_subshell();
assert!(shell.is_err());
});
}
#[test]
fn test_detect_shell_for_in_place() {
// $SHELL is used as a fallback only if parent detection fails
temp_env::with_vars([FLOX_SHELL_UNSET, SHELL_SET], || {
let shell = Activate::detect_shell_for_in_place_with(PARENT_DETECTED).unwrap();
assert_eq!(shell, Shell::Bash("/parent/bash".into()));
// fall back to $SHELL if parent detection fails
let shell = Activate::detect_shell_for_in_place_with(PARENT_UNDETECTED).unwrap();
assert_eq!(shell, Shell::Bash("/shell/bash".into()));
});
// $FLOX_SHELL takes precedence over $SHELL and detected parent shell
temp_env::with_vars([FLOX_SHELL_SET, SHELL_SET], || {
let shell = Activate::detect_shell_for_in_place_with(PARENT_DETECTED).unwrap();
assert_eq!(shell, Shell::Bash("/flox_shell/bash".into()));
let shell = Activate::detect_shell_for_in_place_with(PARENT_UNDETECTED).unwrap();
assert_eq!(shell, Shell::Bash("/flox_shell/bash".into()));
});
// if both $FLOX_SHELL and $SHELL are unset, we should fail iff parent detection fails
temp_env::with_vars([FLOX_SHELL_UNSET, SHELL_UNSET], || {
let shell = Activate::detect_shell_for_in_place_with(PARENT_DETECTED).unwrap();
assert_eq!(shell, Shell::Bash("/parent/bash".into()));
let shell = Activate::detect_shell_for_in_place_with(PARENT_UNDETECTED);
assert!(shell.is_err());
});
}
}
// List packages installed in an environment
#[derive(Bpaf, Clone)]
pub struct List {
#[bpaf(external(environment_select), fallback(Default::default()))]
environment: EnvironmentSelect,
#[bpaf(external(list_mode), fallback(ListMode::Extended))]
list_mode: ListMode,
}
#[derive(Bpaf, Clone, PartialEq, Debug)]
pub enum ListMode {
/// Show the raw contents of the manifest
#[bpaf(long, short)]
Config,
/// Show only the name of each package
#[bpaf(long("name"), short)]
NameOnly,
/// Show the name, pkg-path, and version of each package (default)
#[bpaf(long, short)]
Extended,
/// Show all available package information including priority and license
#[bpaf(long, short)]
All,
}
impl List {
#[instrument(name = "list", fields(mode), skip_all)]
pub async fn handle(self, flox: Flox) -> Result<()> {
subcommand_metric!("list");
let mut env = self
.environment
.detect_concrete_environment(&flox, "list using")?
.into_dyn_environment();
let manifest_contents = env.manifest_content(&flox)?;
if self.list_mode == ListMode::Config {
tracing::Span::current().record("mode", "config");
println!("{}", manifest_contents);