-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
environment.rs
776 lines (687 loc) · 27.3 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
use super::environment_impl::{
colon_split, uvars, EnvMutex, EnvMutexGuard, EnvScopedImpl, EnvStackImpl, ModResult,
UVAR_SCOPE_IS_GLOBAL,
};
use super::{ConfigPaths, ElectricVar};
use crate::abbrs::{abbrs_get_set, Abbreviation, Position};
use crate::common::{str2wcstring, unescape_string, wcs2zstring, UnescapeStringStyle};
use crate::env::{EnvMode, EnvStackSetResult, EnvVar, Statuses};
use crate::env_dispatch::{env_dispatch_init, env_dispatch_var_change};
use crate::event::Event;
use crate::ffi::{self, env_universal_t, universal_notifier_t};
use crate::flog::FLOG;
use crate::global_safety::RelaxedAtomicBool;
use crate::null_terminated_array::OwningNullTerminatedArray;
use crate::path::{
path_emit_config_directory_messages, path_get_config, path_get_data, path_make_canonical,
paths_are_same_file,
};
use crate::termsize;
use crate::wchar::prelude::*;
use crate::wchar_ffi::{AsWstr, WCharFromFFI};
use crate::wcstringutil::join_strings;
use crate::wutil::{fish_wcstol, wgetcwd, wgettext};
use autocxx::WithinUniquePtr;
use cxx::UniquePtr;
use lazy_static::lazy_static;
use libc::c_int;
use once_cell::sync::OnceCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::mem::MaybeUninit;
use std::os::unix::prelude::*;
use std::sync::{Arc, Mutex};
/// TODO: migrate to history once ported.
const DFLT_FISH_HISTORY_SESSION_ID: &wstr = L!("fish");
// Universal variables instance.
lazy_static! {
static ref UVARS: Mutex<UniquePtr<env_universal_t>> = Mutex::new(env_universal_t::new_unique());
}
/// Set when a universal variable has been modified but not yet been written to disk via sync().
static UVARS_LOCALLY_MODIFIED: RelaxedAtomicBool = RelaxedAtomicBool::new(false);
/// Convert an EnvVar to an FFI env_var_t.
pub fn env_var_to_ffi(var: Option<EnvVar>) -> cxx::UniquePtr<ffi::env_var_t> {
if let Some(var) = var {
ffi::env_var_t::new_ffi(Box::into_raw(Box::from(var)).cast()).within_unique_ptr()
} else {
cxx::UniquePtr::null()
}
}
/// An environment is read-only access to variable values.
pub trait Environment {
/// Get a variable by name using default flags.
fn get(&self, name: &wstr) -> Option<EnvVar> {
self.getf(name, EnvMode::default())
}
/// Get a variable by name using the specified flags.
fn getf(&self, name: &wstr, mode: EnvMode) -> Option<EnvVar>;
/// Return the list of variable names.
fn get_names(&self, flags: EnvMode) -> Vec<WString>;
/// Returns PWD with a terminating slash.
fn get_pwd_slash(&self) -> WString {
// Return "/" if PWD is missing.
// See https://github.com/fish-shell/fish-shell/issues/5080
let Some(var) = self.get(L!("PWD")) else {
return WString::from("/");
};
let mut pwd = WString::new();
if var.is_empty() {
pwd = var.as_string();
}
if !pwd.ends_with('/') {
pwd.push('/');
}
pwd
}
/// Get a variable by name using default flags, unless it is empty.
fn get_unless_empty(&self, name: &wstr) -> Option<EnvVar> {
self.getf_unless_empty(name, EnvMode::default())
}
/// Get a variable by name using the given flags, unless it is empty.
fn getf_unless_empty(&self, name: &wstr, mode: EnvMode) -> Option<EnvVar> {
let var = self.getf(name, mode)?;
if !var.is_empty() {
return Some(var);
}
None
}
}
/// The null environment contains nothing.
pub struct EnvNull;
impl EnvNull {
pub fn new() -> EnvNull {
EnvNull
}
}
impl Environment for EnvNull {
fn getf(&self, _name: &wstr, _mode: EnvMode) -> Option<EnvVar> {
None
}
fn get_names(&self, _flags: EnvMode) -> Vec<WString> {
Vec::new()
}
}
/// An immutable environment, used in snapshots.
pub struct EnvScoped {
inner: EnvMutex<EnvScopedImpl>,
}
impl EnvScoped {
fn from_impl(inner: EnvMutex<EnvScopedImpl>) -> EnvScoped {
EnvScoped { inner }
}
fn lock(&self) -> EnvMutexGuard<EnvScopedImpl> {
self.inner.lock()
}
}
/// A mutable environment which allows scopes to be pushed and popped.
/// This backs the parser's "vars".
pub struct EnvStack {
inner: EnvMutex<EnvStackImpl>,
}
impl EnvStack {
fn new() -> EnvStack {
EnvStack {
inner: EnvStackImpl::new(),
}
}
fn lock(&self) -> EnvMutexGuard<EnvStackImpl> {
self.inner.lock()
}
/// \return whether we are the principal stack.
pub fn is_principal(&self) -> bool {
self as *const Self == Arc::as_ptr(&*PRINCIPAL_STACK)
}
/// Helpers to get and set the proc statuses.
/// These correspond to $status and $pipestatus.
pub fn get_last_statuses(&self) -> Statuses {
self.lock().base.get_last_statuses().clone()
}
pub fn get_last_status(&self) -> c_int {
self.lock().base.get_last_statuses().status
}
pub fn set_last_statuses(&self, statuses: Statuses) {
self.lock().base.set_last_statuses(statuses);
}
/// Sets the variable with the specified name to the given values.
pub fn set(&self, key: &wstr, mode: EnvMode, mut vals: Vec<WString>) -> EnvStackSetResult {
// Historical behavior.
if vals.len() == 1 && (key == "PWD" || key == "HOME") {
path_make_canonical(vals.first_mut().unwrap());
}
// Hacky stuff around PATH and CDPATH: #3914.
// Not MANPATH; see #4158.
// Replace empties with dot. Note we ignore pathvar here.
if key == "PATH" || key == "CDPATH" {
// Split on colons.
let mut munged_vals = colon_split(&vals);
// Replace empties with dots.
for val in munged_vals.iter_mut() {
if val.is_empty() {
val.push('.');
}
}
vals = munged_vals;
}
let ret: ModResult = self.lock().set(key, mode, vals);
if ret.status == EnvStackSetResult::ENV_OK {
// If we modified the global state, or we are principal, then dispatch changes.
// Important to not hold the lock here.
if ret.global_modified || self.is_principal() {
env_dispatch_var_change(key, self);
}
}
// Mark if we modified a uvar.
if ret.uvar_modified {
UVARS_LOCALLY_MODIFIED.store(true);
}
ret.status
}
/// Sets the variable with the specified name to a single value.
pub fn set_one(&self, key: &wstr, mode: EnvMode, val: WString) -> EnvStackSetResult {
self.set(key, mode, vec![val])
}
/// Sets the variable with the specified name to no values.
pub fn set_empty(&self, key: &wstr, mode: EnvMode) -> EnvStackSetResult {
self.set(key, mode, Vec::new())
}
/// Update the PWD variable based on the result of getcwd.
pub fn set_pwd_from_getcwd(&self) {
let cwd = wgetcwd();
if cwd.is_empty() {
FLOG!(
error,
wgettext!(
"Could not determine current working directory. Is your locale set correctly?"
)
);
}
self.set_one(L!("PWD"), EnvMode::EXPORT | EnvMode::GLOBAL, cwd);
}
/// Remove environment variable.
///
/// \param key The name of the variable to remove
/// \param mode should be ENV_USER if this is a remove request from the user, 0 otherwise. If
/// this is a user request, read-only variables can not be removed. The mode may also specify
/// the scope of the variable that should be erased.
///
/// \return the set result.
pub fn remove(&self, key: &wstr, mode: EnvMode) -> EnvStackSetResult {
let ret = self.lock().remove(key, mode);
#[allow(clippy::collapsible_if)]
if ret.status == EnvStackSetResult::ENV_OK {
if ret.global_modified || self.is_principal() {
// Important to not hold the lock here.
env_dispatch_var_change(key, self);
}
}
if ret.uvar_modified {
UVARS_LOCALLY_MODIFIED.store(true);
}
ret.status
}
/// Push the variable stack. Used for implementing local variables for functions and for-loops.
pub fn push(&self, new_scope: bool) {
let mut imp = self.lock();
if new_scope {
imp.push_shadowing();
} else {
imp.push_nonshadowing();
}
}
/// Pop the variable stack. Used for implementing local variables for functions and for-loops.
pub fn pop(&self) {
let popped = self.lock().pop();
// Only dispatch variable changes if we are the principal environment.
if self.is_principal() {
// TODO: we would like to coalesce locale / curses changes, so that we only re-initialize
// once.
for key in popped {
env_dispatch_var_change(&key, self);
}
}
}
/// Returns an array containing all exported variables in a format suitable for execv.
pub fn export_array(&self) -> Arc<OwningNullTerminatedArray> {
self.lock().base.export_array()
}
/// Snapshot this environment. This means returning a read-only copy. Local variables are copied
/// but globals are shared (i.e. changes to global will be visible to this snapshot).
pub fn snapshot(&self) -> Box<dyn Environment> {
let scoped = EnvScoped::from_impl(self.lock().base.snapshot());
Box::new(scoped)
}
/// Synchronizes universal variable changes.
/// If \p always is set, perform synchronization even if there's no pending changes from this
/// instance (that is, look for changes from other fish instances).
/// \return a list of events for changed variables.
#[allow(clippy::vec_box)]
pub fn universal_sync(&self, always: bool) -> Vec<Box<Event>> {
if UVAR_SCOPE_IS_GLOBAL.load() {
return Vec::new();
}
if !always && !UVARS_LOCALLY_MODIFIED.load() {
return Vec::new();
}
UVARS_LOCALLY_MODIFIED.store(false);
let mut unused = autocxx::c_int(0);
let sync_res_ptr = uvars().as_mut().unwrap().sync_ffi().within_unique_ptr();
let sync_res = sync_res_ptr.as_ref().unwrap();
if sync_res.get_changed() {
universal_notifier_t::default_notifier_ffi(std::pin::Pin::new(&mut unused))
.post_notification();
}
// React internally to changes to special variables like LANG, and populate on-variable events.
let mut result = Vec::new();
#[allow(unreachable_code)]
for idx in 0..sync_res.count() {
let name = sync_res.get_key(idx).from_ffi();
env_dispatch_var_change(&name, self);
let evt = if sync_res.get_is_erase(idx) {
Event::variable_erase(name)
} else {
Event::variable_set(name)
};
result.push(Box::new(evt));
}
result
}
/// A variable stack that only represents globals.
/// Do not push or pop from this.
pub fn globals() -> &'static EnvStackRef {
&GLOBALS
}
/// Access the principal variable stack, associated with the principal parser.
pub fn principal() -> &'static EnvStackRef {
&PRINCIPAL_STACK
}
}
impl Environment for EnvScoped {
fn getf(&self, key: &wstr, mode: EnvMode) -> Option<EnvVar> {
self.lock().getf(key, mode)
}
fn get_names(&self, flags: EnvMode) -> Vec<WString> {
self.lock().get_names(flags)
}
fn get_pwd_slash(&self) -> WString {
self.lock().get_pwd_slash()
}
}
/// Necessary for Arc<EnvStack> to be sync.
/// Safety: again, the global lock.
unsafe impl Send for EnvStack {}
impl Environment for EnvStack {
fn getf(&self, key: &wstr, mode: EnvMode) -> Option<EnvVar> {
self.lock().getf(key, mode)
}
fn get_names(&self, flags: EnvMode) -> Vec<WString> {
self.lock().get_names(flags)
}
fn get_pwd_slash(&self) -> WString {
self.lock().get_pwd_slash()
}
}
pub type EnvStackRef = Arc<EnvStack>;
// A variable stack that only represents globals.
// Do not push or pop from this.
lazy_static! {
static ref GLOBALS: EnvStackRef = Arc::new(EnvStack::new());
}
// Our singleton "principal" stack.
lazy_static! {
static ref PRINCIPAL_STACK: EnvStackRef = Arc::new(EnvStack::new());
}
/// Some configuration path environment variables.
const FISH_DATADIR_VAR: &wstr = L!("__fish_data_dir");
const FISH_SYSCONFDIR_VAR: &wstr = L!("__fish_sysconf_dir");
const FISH_HELPDIR_VAR: &wstr = L!("__fish_help_dir");
const FISH_BIN_DIR: &wstr = L!("__fish_bin_dir");
const FISH_CONFIG_DIR: &wstr = L!("__fish_config_dir");
const FISH_USER_DATA_DIR: &wstr = L!("__fish_user_data_dir");
/// Maximum length of hostname. Longer hostnames are truncated.
const HOSTNAME_LEN: usize = 255;
/// Function to get an identifier based on the hostname.
fn get_hostname_identifier() -> Option<WString> {
// The behavior of gethostname if the buffer size is insufficient differs by implementation and
// libc version Work around this by using a "guaranteed" sufficient buffer size then truncating
// the result.
let mut b = [0 as libc::c_char; HOSTNAME_LEN + 1];
if unsafe { libc::gethostname(b.as_mut_ptr(), b.len()) } == 0 {
let cstr = unsafe { CStr::from_ptr(b.as_ptr()) };
let res = str2wcstring(cstr.to_bytes());
if res.is_empty() {
None
} else {
Some(res)
}
} else {
None
}
}
/// Set up the USER and HOME variable.
fn setup_user(vars: &EnvStack) {
let uid = unsafe { libc::geteuid() };
let user_var = vars.get_unless_empty(L!("USER"));
let mut userinfo: MaybeUninit<libc::passwd> = MaybeUninit::uninit();
let mut result: *mut libc::passwd = std::ptr::null_mut();
let mut buf = [0 as libc::c_char; 8192];
// If we have a $USER, we try to get the passwd entry for the name.
// If that has the same UID that we use, we assume the data is correct.
if let Some(user_var) = user_var {
let unam_narrow = wcs2zstring(&user_var.as_string());
let retval = unsafe {
libc::getpwnam_r(
unam_narrow.as_ptr(),
userinfo.as_mut_ptr(),
buf.as_mut_ptr(),
buf.len(),
&mut result,
)
};
if retval == 0 && !result.is_null() {
let userinfo = unsafe { userinfo.assume_init() };
if unsafe { *result }.pw_uid == uid {
// The uid matches but we still might need to set $HOME.
if vars.get_unless_empty(L!("HOME")).is_none() {
if !userinfo.pw_dir.is_null() {
let s = unsafe { CStr::from_ptr(userinfo.pw_dir) };
vars.set_one(
L!("HOME"),
EnvMode::GLOBAL | EnvMode::EXPORT,
str2wcstring(s.to_bytes()),
);
} else {
vars.set_empty(L!("HOME"), EnvMode::GLOBAL | EnvMode::EXPORT);
}
}
return;
}
}
}
// Either we didn't have a $USER or it had a different uid.
// We need to get the data *again* via the uid.
let retval = unsafe {
libc::getpwuid_r(
uid,
userinfo.as_mut_ptr(),
buf.as_mut_ptr(),
buf.len(),
&mut result,
)
};
if retval == 0 && !result.is_null() {
let userinfo = unsafe { userinfo.assume_init() };
let s = unsafe { CStr::from_ptr(userinfo.pw_name) };
let uname = str2wcstring(s.to_bytes());
vars.set_one(L!("USER"), EnvMode::GLOBAL | EnvMode::EXPORT, uname);
// Only change $HOME if it's empty, so we allow e.g. `HOME=(mktemp -d)`.
// This is okay with common `su` and `sudo` because they set $HOME.
if vars.get_unless_empty(L!("HOME")).is_none() {
if !userinfo.pw_dir.is_null() {
let s = unsafe { CStr::from_ptr(userinfo.pw_dir) };
vars.set_one(
L!("HOME"),
EnvMode::GLOBAL | EnvMode::EXPORT,
str2wcstring(s.to_bytes()),
);
} else {
// We cannot get $HOME. This triggers warnings for history and config.fish already,
// so it isn't necessary to warn here as well.
vars.set_empty(L!("HOME"), EnvMode::GLOBAL | EnvMode::EXPORT);
}
}
} else if vars.get_unless_empty(L!("HOME")).is_none() {
// If $USER is empty as well (which we tried to set above), we can't get $HOME.
vars.set_empty(L!("HOME"), EnvMode::GLOBAL | EnvMode::EXPORT);
}
}
/// Make sure the PATH variable contains something.
fn setup_path() {
use crate::compat::{confstr, _CS_PATH};
let vars = &GLOBALS;
let path = vars.get_unless_empty(L!("PATH"));
if path.is_none() {
// _CS_PATH: colon-separated paths to find POSIX utilities
let buf_size = unsafe { confstr(_CS_PATH(), std::ptr::null_mut(), 0) };
let path = if buf_size > 0 {
let mut buf = vec![b'\0' as libc::c_char; buf_size];
unsafe { confstr(_CS_PATH(), buf.as_mut_ptr(), buf_size) };
let buf = buf;
// safety: buf should contain a null-byte, and is not mutable unless we move ownership
let cstr = unsafe { CStr::from_ptr(buf.as_ptr()) };
str2wcstring(cstr.to_bytes())
} else {
// the above should really not fail
join_strings(crate::path::DEFAULT_PATH.as_ref(), ':')
};
vars.set_one(L!("PATH"), EnvMode::GLOBAL | EnvMode::EXPORT, path);
}
}
/// The originally inherited variables and their values.
/// This is a simple key->value map and not e.g. cut into paths.
pub static INHERITED_VARS: OnceCell<HashMap<WString, WString>> = OnceCell::new();
pub fn env_init(paths: Option<&ConfigPaths>, do_uvars: bool, default_paths: bool) {
let vars = &PRINCIPAL_STACK;
let env_iter: Vec<_> = std::env::vars_os()
.map(|(k, v)| (str2wcstring(k.as_bytes()), str2wcstring(v.as_bytes())))
.collect();
let mut inherited_vars = HashMap::new();
// Import environment variables. Walk backwards so that the first one out of any duplicates wins
// (See issue #2784).
// PORTING: this should behave like in C++ in regards to the above comment, but that might be
// with assumptions on the standard library's behavior (is it okay for them to remove duplicates?).
for (key, val) in env_iter.into_iter().rev() {
// PORTING: This is making assumptions that env::vars_os set val to empty if no equal sign
// PORTING: That assumption appears to be wrong https://github.com/rust-lang/rust/blob/2ceed0b6cb9e9866225d7cfcfcbb4a62db047163/library/std/src/sys/unix/os.rs#L584C30-L584C30
// it appears they allow names starting with =, but do not turn malformed lines
// into the variable name with an empty value
if ElectricVar::for_name(&key).is_none() {
// fish_user_paths should not be exported; attempting to re-import it from
// a value we previously (due to user error) exported will cause impossibly
// difficult to debug PATH problems.
if key != "fish_user_paths" {
vars.set(&key, EnvMode::EXPORT | EnvMode::GLOBAL, vec![val.clone()]);
}
inherited_vars.insert(key, val);
}
}
INHERITED_VARS
.set(inherited_vars)
.expect("env_init is being called multiple times");
ffi::set_inheriteds_ffi();
if let Some(paths) = paths {
vars.set_one(
FISH_DATADIR_VAR,
EnvMode::GLOBAL,
str2wcstring(paths.data.as_os_str().as_bytes()),
);
vars.set_one(
FISH_SYSCONFDIR_VAR,
EnvMode::GLOBAL,
str2wcstring(paths.sysconf.as_os_str().as_bytes()),
);
vars.set_one(
FISH_HELPDIR_VAR,
EnvMode::GLOBAL,
str2wcstring(paths.doc.as_os_str().as_bytes()),
);
vars.set_one(
FISH_BIN_DIR,
EnvMode::GLOBAL,
str2wcstring(paths.bin.as_os_str().as_bytes()),
);
if default_paths {
let mut scstr = paths.data.clone();
scstr.push("functions");
vars.set_one(
L!("fish_function_path"),
EnvMode::GLOBAL,
str2wcstring(scstr.as_os_str().as_bytes()),
);
}
}
// Set $USER, $HOME and $EUID
// This involves going to passwd and stuff.
vars.set_one(
L!("EUID"),
EnvMode::GLOBAL,
unsafe { libc::geteuid() }.to_wstring(),
);
setup_user(vars);
let user_config_dir = path_get_config();
vars.set_one(
FISH_CONFIG_DIR,
EnvMode::GLOBAL,
user_config_dir.unwrap_or_default(),
);
let user_data_dir = path_get_data();
vars.set_one(
FISH_USER_DATA_DIR,
EnvMode::GLOBAL,
user_data_dir.unwrap_or_default(),
);
// Set up a default PATH
setup_path();
// Set up $IFS - this used to be in share/config.fish, but really breaks if it isn't done.
vars.set_one(L!("IFS"), EnvMode::GLOBAL, "\n \t".into());
// Ensure this var is present even before an interactive command is run so that if it is used
// in a function like `fish_prompt` or `fish_right_prompt` it is defined at the time the first
// prompt is written.
vars.set_one(L!("CMD_DURATION"), EnvMode::UNEXPORT, "0".into());
// Set up the version variable.
let version = str2wcstring(crate::BUILD_VERSION.as_bytes());
vars.set_one(L!("version"), EnvMode::GLOBAL, version.clone());
vars.set_one(L!("FISH_VERSION"), EnvMode::GLOBAL, version);
// Set the $fish_pid variable.
vars.set_one(
L!("fish_pid"),
EnvMode::GLOBAL,
unsafe { libc::getpid() }.to_wstring(),
);
// Set the $hostname variable
let hostname: WString = get_hostname_identifier().unwrap_or("fish".into());
vars.set_one(L!("hostname"), EnvMode::GLOBAL, hostname);
// Set up SHLVL variable. Not we can't use vars.get() because SHLVL is read-only, and therefore
// was not inherited from the environment.
if ffi::is_interactive_session() {
let nshlvl_str = if let Some(shlvl_var) = std::env::var_os("SHLVL") {
// TODO: Figure out how to handle invalid numbers better. Shouldn't we issue a
// diagnostic?
match fish_wcstol(&str2wcstring(shlvl_var.as_os_str().as_bytes())) {
Ok(shlvl_i) if shlvl_i >= 0 => (shlvl_i + 1).to_wstring(),
_ => L!("1").to_owned(),
}
} else {
L!("1").to_owned()
};
vars.set_one(L!("SHLVL"), EnvMode::GLOBAL | EnvMode::EXPORT, nshlvl_str);
} else {
// If we're not interactive, simply pass the value along.
if let Some(shlvl_var) = std::env::var_os("SHLVL") {
vars.set_one(
L!("SHLVL"),
EnvMode::GLOBAL | EnvMode::EXPORT,
str2wcstring(shlvl_var.as_os_str().as_bytes()),
);
}
}
// initialize the PWD variable if necessary
// Note we may inherit a virtual PWD that doesn't match what getcwd would return; respect that
// if and only if it matches getcwd (#5647). Note we treat PWD as read-only so it was not set in
// vars.
//
// Also reject all paths that don't start with "/", this includes windows paths like "F:\foo".
// (see #7636)
let incoming_pwd_cstr = std::env::var_os("PWD");
let incoming_pwd = incoming_pwd_cstr
.map(|s| str2wcstring(s.as_os_str().as_bytes()))
.unwrap_or_default();
if !incoming_pwd.is_empty()
&& incoming_pwd.char_at(0) == '/'
&& paths_are_same_file(&incoming_pwd, L!("."))
{
vars.set_one(L!("PWD"), EnvMode::EXPORT | EnvMode::GLOBAL, incoming_pwd);
} else {
vars.set_pwd_from_getcwd();
}
// Initialize termsize variables.
// PORTING: 3x deref is weird
let termsize = termsize::SHARED_CONTAINER.initialize(&***vars as &dyn Environment);
if vars.get_unless_empty(L!("COLUMNS")).is_none() {
vars.set_one(L!("COLUMNS"), EnvMode::GLOBAL, termsize.width.to_wstring());
}
if vars.get_unless_empty(L!("LINES")).is_none() {
vars.set_one(L!("LINES"), EnvMode::GLOBAL, termsize.height.to_wstring());
}
// Set fish_bind_mode to "default".
// FIXME: this was a constant FISH_BIND_MODE_VAR from input.cpp
vars.set_one(L!("fish_bind_mode"), EnvMode::GLOBAL, "default".into());
// Allow changes to variables to produce events.
env_dispatch_init(vars);
ffi::init_input();
// Complain about invalid config paths.
// HACK: Assume the defaults are correct (in practice this is only --no-config anyway).
if !default_paths {
path_emit_config_directory_messages(vars);
}
if !do_uvars {
UVAR_SCOPE_IS_GLOBAL.store(true);
} else {
// Set up universal variables using the default path.
let callbacks = uvars()
.as_mut()
.unwrap()
.initialize_ffi()
.within_unique_ptr();
let vars = EnvStack::principal();
let callbacks = callbacks.as_ref().unwrap();
for idx in 0..callbacks.count() {
let name = callbacks.get_key(idx).from_ffi();
env_dispatch_var_change(&name, vars);
}
// Do not import variables that have the same name and value as
// an exported universal variable. See issues #5258 and #5348.
let mut table = uvars()
.as_ref()
.unwrap()
.get_table_ffi()
.within_unique_ptr();
for idx in 0..table.count() {
// autocxx gets confused when a value goes Rust -> Cxx -> Rust.
let uvar = table.as_mut().unwrap().get_var(idx).from_ffi();
if !uvar.exports() {
continue;
}
let name: &wstr = table.get_name(idx).as_wstr();
// Look for a global exported variable with the same name.
let global = EnvStack::globals().getf(name, EnvMode::GLOBAL | EnvMode::EXPORT);
if global.is_some() && global.unwrap().as_string() == uvar.as_string() {
EnvStack::globals().remove(name, EnvMode::GLOBAL | EnvMode::EXPORT);
}
}
// Import any abbreviations from uvars.
// Note we do not dynamically react to changes.
let prefix = L!("_fish_abbr_");
let prefix_len = prefix.char_count();
let from_universal = true;
let mut abbrs = abbrs_get_set();
for idx in 0..table.count() {
let name: &wstr = table.get_name(idx).as_wstr();
if !name.starts_with(prefix) {
continue;
}
let escaped_name = name.slice_from(prefix_len);
if let Some(name) = unescape_string(escaped_name, UnescapeStringStyle::Var) {
let key = name.clone();
let uvar = table.get_var(idx).from_ffi();
let replacement: WString = join_strings(uvar.as_list(), ' ');
abbrs.add(Abbreviation::new(
name,
key,
replacement,
Position::Command,
from_universal,
));
}
}
}
}