Skip to main content

uv_preview/
lib.rs

1use std::sync::{Mutex, OnceLock};
2use std::{
3    fmt::{Debug, Display, Formatter},
4    ops::BitOr,
5    str::FromStr,
6};
7
8use enumflags2::{BitFlags, bitflags};
9use thiserror::Error;
10use uv_warnings::warn_user_once;
11
12/// Indicates if the preview state has been finalized yet or not.
13enum PreviewState {
14    Provisional(Preview),
15    Final(Preview),
16}
17
18/// Indicates how the preview was initialised, to distinguish between normal
19/// code and unit tests.
20enum PreviewMode {
21    /// Initialised by a call to [`init`].
22    Normal(Mutex<PreviewState>),
23    /// Initialised by a call to [`test::with_features`].
24    #[cfg(feature = "testing")]
25    Test(std::sync::RwLock<Option<Preview>>),
26}
27
28static PREVIEW: OnceLock<PreviewMode> = OnceLock::new();
29
30/// Error type for global preview state initialization related errors
31#[derive(Debug, Error)]
32pub enum PreviewError {
33    /// Returned when [`set`] or [`finalize`] are called on a finalized state.
34    #[error("The preview configuration has already been finalized")]
35    AlreadyFinalized,
36
37    /// Returned when [`finalize`] is called on an uninitialized state.
38    #[error("The preview configuration has not been initialized yet")]
39    NotInitialized,
40
41    /// Returned when [`set`] or [`finalize`] are called on a test state.
42    #[cfg(feature = "testing")]
43    #[error("The preview configuration is in test mode and {}::{} cannot be used", module_path!(), .0)]
44    InTest(&'static str),
45}
46
47/// Initialize the global preview configuration.
48///
49/// This should be called once at startup with the resolved preview settings.
50pub fn set(preview: Preview) -> Result<(), PreviewError> {
51    let mode = PREVIEW.get_or_init(|| {
52        PreviewMode::Normal(Mutex::new(PreviewState::Provisional(Preview::default())))
53    });
54    match mode {
55        PreviewMode::Normal(mutex) => {
56            // Calling `set` in a test context is already disallowed, so a panic if
57            // the mutex is poisoned is fine.
58            let mut state = mutex.lock().unwrap();
59            match &*state {
60                PreviewState::Provisional(_) => {
61                    *state = PreviewState::Provisional(preview);
62                    Ok(())
63                }
64                PreviewState::Final(_) => Err(PreviewError::AlreadyFinalized),
65            }
66        }
67        #[cfg(feature = "testing")]
68        PreviewMode::Test(_) => Err(PreviewError::InTest("set")),
69    }
70}
71
72pub fn finalize() -> Result<(), PreviewError> {
73    match PREVIEW.get().ok_or(PreviewError::NotInitialized)? {
74        PreviewMode::Normal(mutex) => {
75            // Calling `set` in a test context is already disallowed, so a panic if
76            // the mutex is poisoned is fine.
77            let mut state = mutex.lock().unwrap();
78            match &*state {
79                PreviewState::Provisional(preview) => {
80                    *state = PreviewState::Final(*preview);
81                    Ok(())
82                }
83                PreviewState::Final(_) => Err(PreviewError::AlreadyFinalized),
84            }
85        }
86        #[cfg(feature = "testing")]
87        PreviewMode::Test(_) => Err(PreviewError::InTest("finalize")),
88    }
89}
90
91/// Error returned when [`finalize`] is called on an uninitialized state.
92#[derive(Debug, Error)]
93#[error("The preview configuration has already been finalized")]
94pub struct SetError;
95
96/// Get the current global preview configuration.
97///
98/// # Panics
99///
100/// When called before [`init`] or (with the `testing` feature) when the
101/// current thread does not hold a [`test::with_features`] guard.
102pub fn get() -> Preview {
103    match PREVIEW.get() {
104        Some(PreviewMode::Normal(mutex)) => match *mutex.lock().unwrap() {
105            PreviewState::Provisional(preview) => preview,
106            PreviewState::Final(preview) => preview,
107        },
108        #[cfg(feature = "testing")]
109        Some(PreviewMode::Test(rwlock)) => {
110            assert!(
111                test::HELD.get(),
112                "The preview configuration is in test mode but the current thread does not hold a `FeaturesGuard`\nHint: Use `{}::test::with_features` to get a `FeaturesGuard` and hold it when testing functions which rely on the global preview state",
113                module_path!()
114            );
115            // The unwrap may panic only if the current thread had panicked
116            // while attempting to write the value and then recovered with
117            // `catch_unwind`. This seems unlikely.
118            rwlock
119                .read()
120                .unwrap()
121                .expect("FeaturesGuard is held but preview value is not set")
122        }
123        #[cfg(feature = "testing")]
124        None => panic!(
125            "The preview configuration has not been initialized\nHint: Use `{}::init` or `{}::test::with_features` to initialize it",
126            module_path!(),
127            module_path!()
128        ),
129        #[cfg(not(feature = "testing"))]
130        None => panic!("The preview configuration has not been initialized"),
131    }
132}
133
134/// Check if a specific preview feature is enabled globally.
135pub fn is_enabled(flag: PreviewFeature) -> bool {
136    get().is_enabled(flag)
137}
138
139/// Functions for unit tests, do not use from normal code!
140#[cfg(feature = "testing")]
141pub mod test {
142    use super::{PREVIEW, Preview, PreviewMode};
143    use std::cell::Cell;
144    use std::sync::{Mutex, MutexGuard, RwLock};
145
146    /// The global preview state test mutex. It does not guard any data but is
147    /// simply used to ensure tests which rely on the global preview state are
148    /// ran serially.
149    static MUTEX: Mutex<()> = Mutex::new(());
150
151    thread_local! {
152        /// Whether the current thread holds the global mutex.
153        ///
154        /// This is used to catch situations where a test forgets to set the
155        /// global test state but happens to work anyway because of another test
156        /// setting the state.
157        pub(crate) static HELD: Cell<bool> = const { Cell::new(false) };
158    }
159
160    /// A scope guard which ensures that the global preview state is configured
161    /// and consistent for the duration of its lifetime.
162    #[derive(Debug)]
163    #[expect(unused)]
164    pub struct FeaturesGuard(MutexGuard<'static, ()>);
165
166    /// Temporarily set the state of preview features for the duration of the
167    /// lifetime of the returned guard.
168    ///
169    /// Calls cannot be nested, and this function must be used to set the global
170    /// preview features when testing functionality which uses it, otherwise
171    /// that functionality will panic.
172    ///
173    /// The preview state will only be valid for the thread which calls this
174    /// function, it will not be valid for any other thread. This is a
175    /// consequence of how `HELD` is used to check for tests which are missing
176    /// the guard.
177    pub fn with_features(features: &[super::PreviewFeature]) -> FeaturesGuard {
178        assert!(
179            !HELD.get(),
180            "Additional calls to `{}::with_features` are not allowed while holding a `FeaturesGuard`",
181            module_path!()
182        );
183
184        let guard = match MUTEX.lock() {
185            Ok(guard) => guard,
186            // This is okay because the mutex isn't guarding any data, so when
187            // it gets poisoned, it just means a test thread died while holding
188            // it, so it's safe to just re-grab it from the PoisonError, there's
189            // no chance of any corruption.
190            Err(err) => err.into_inner(),
191        };
192
193        HELD.set(true);
194
195        let state = PREVIEW.get_or_init(|| PreviewMode::Test(RwLock::new(None)));
196        match state {
197            PreviewMode::Test(rwlock) => {
198                *rwlock.write().unwrap() = Some(Preview::new(features));
199            }
200            PreviewMode::Normal(_) => {
201                panic!(
202                    "Cannot use `{}::with_features` after `uv_preview::init` has been called",
203                    module_path!()
204                );
205            }
206        }
207        FeaturesGuard(guard)
208    }
209
210    impl Drop for FeaturesGuard {
211        fn drop(&mut self) {
212            HELD.set(false);
213
214            match PREVIEW.get().unwrap() {
215                PreviewMode::Test(rwlock) => {
216                    *rwlock.write().unwrap() = None;
217                }
218                PreviewMode::Normal(_) => {
219                    unreachable!("FeaturesGuard should not exist when in Normal mode");
220                }
221            }
222        }
223    }
224}
225
226#[bitflags]
227#[repr(u32)]
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum PreviewFeature {
230    PythonInstallDefault = 1 << 0,
231    PythonUpgrade = 1 << 1,
232    JsonOutput = 1 << 2,
233    Pylock = 1 << 3,
234    AddBounds = 1 << 4,
235    PackageConflicts = 1 << 5,
236    ExtraBuildDependencies = 1 << 6,
237    DetectModuleConflicts = 1 << 7,
238    Format = 1 << 8,
239    NativeAuth = 1 << 9,
240    S3Endpoint = 1 << 10,
241    CacheSize = 1 << 11,
242    InitProjectFlag = 1 << 12,
243    WorkspaceMetadata = 1 << 13,
244    WorkspaceDir = 1 << 14,
245    WorkspaceList = 1 << 15,
246    SbomExport = 1 << 16,
247    AuthHelper = 1 << 17,
248    DirectPublish = 1 << 18,
249    TargetWorkspaceDiscovery = 1 << 19,
250    MetadataJson = 1 << 20,
251    GcsEndpoint = 1 << 21,
252    AdjustUlimit = 1 << 22,
253    SpecialCondaEnvNames = 1 << 23,
254    RelocatableEnvsDefault = 1 << 24,
255    PublishRequireNormalized = 1 << 25,
256    Audit = 1 << 26,
257    ProjectDirectoryMustExist = 1 << 27,
258    IndexExcludeNewer = 1 << 28,
259}
260
261impl PreviewFeature {
262    /// Returns the string representation of a single preview feature flag.
263    fn as_str(self) -> &'static str {
264        match self {
265            Self::PythonInstallDefault => "python-install-default",
266            Self::PythonUpgrade => "python-upgrade",
267            Self::JsonOutput => "json-output",
268            Self::Pylock => "pylock",
269            Self::AddBounds => "add-bounds",
270            Self::PackageConflicts => "package-conflicts",
271            Self::ExtraBuildDependencies => "extra-build-dependencies",
272            Self::DetectModuleConflicts => "detect-module-conflicts",
273            Self::Format => "format",
274            Self::NativeAuth => "native-auth",
275            Self::S3Endpoint => "s3-endpoint",
276            Self::CacheSize => "cache-size",
277            Self::InitProjectFlag => "init-project-flag",
278            Self::WorkspaceMetadata => "workspace-metadata",
279            Self::WorkspaceDir => "workspace-dir",
280            Self::WorkspaceList => "workspace-list",
281            Self::SbomExport => "sbom-export",
282            Self::AuthHelper => "auth-helper",
283            Self::DirectPublish => "direct-publish",
284            Self::TargetWorkspaceDiscovery => "target-workspace-discovery",
285            Self::MetadataJson => "metadata-json",
286            Self::GcsEndpoint => "gcs-endpoint",
287            Self::AdjustUlimit => "adjust-ulimit",
288            Self::SpecialCondaEnvNames => "special-conda-env-names",
289            Self::RelocatableEnvsDefault => "relocatable-envs-default",
290            Self::PublishRequireNormalized => "publish-require-normalized",
291            Self::Audit => "audit",
292            Self::ProjectDirectoryMustExist => "project-directory-must-exist",
293            Self::IndexExcludeNewer => "index-exclude-newer",
294        }
295    }
296}
297
298impl Display for PreviewFeature {
299    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
300        write!(f, "{}", self.as_str())
301    }
302}
303
304#[derive(Debug, Error, Clone)]
305#[error("Unknown feature flag")]
306pub struct PreviewFeatureParseError;
307
308impl FromStr for PreviewFeature {
309    type Err = PreviewFeatureParseError;
310
311    fn from_str(s: &str) -> Result<Self, Self::Err> {
312        Ok(match s {
313            "python-install-default" => Self::PythonInstallDefault,
314            "python-upgrade" => Self::PythonUpgrade,
315            "json-output" => Self::JsonOutput,
316            "pylock" => Self::Pylock,
317            "add-bounds" => Self::AddBounds,
318            "package-conflicts" => Self::PackageConflicts,
319            "extra-build-dependencies" => Self::ExtraBuildDependencies,
320            "detect-module-conflicts" => Self::DetectModuleConflicts,
321            "format" => Self::Format,
322            "native-auth" => Self::NativeAuth,
323            "s3-endpoint" => Self::S3Endpoint,
324            "gcs-endpoint" => Self::GcsEndpoint,
325            "cache-size" => Self::CacheSize,
326            "init-project-flag" => Self::InitProjectFlag,
327            "workspace-metadata" => Self::WorkspaceMetadata,
328            "workspace-dir" => Self::WorkspaceDir,
329            "workspace-list" => Self::WorkspaceList,
330            "sbom-export" => Self::SbomExport,
331            "auth-helper" => Self::AuthHelper,
332            "direct-publish" => Self::DirectPublish,
333            "target-workspace-discovery" => Self::TargetWorkspaceDiscovery,
334            "metadata-json" => Self::MetadataJson,
335            "adjust-ulimit" => Self::AdjustUlimit,
336            "special-conda-env-names" => Self::SpecialCondaEnvNames,
337            "relocatable-envs-default" => Self::RelocatableEnvsDefault,
338            "publish-require-normalized" => Self::PublishRequireNormalized,
339            "audit" => Self::Audit,
340            "project-directory-must-exist" => Self::ProjectDirectoryMustExist,
341            "index-exclude-newer" => Self::IndexExcludeNewer,
342            _ => return Err(PreviewFeatureParseError),
343        })
344    }
345}
346
347#[derive(Clone, Copy, PartialEq, Eq, Default)]
348pub struct Preview {
349    flags: BitFlags<PreviewFeature>,
350}
351
352impl Debug for Preview {
353    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
354        let flags: Vec<_> = self.flags.iter().collect();
355        f.debug_struct("Preview").field("flags", &flags).finish()
356    }
357}
358
359impl Preview {
360    pub fn new(flags: &[PreviewFeature]) -> Self {
361        Self {
362            flags: flags.iter().copied().fold(BitFlags::empty(), BitOr::bitor),
363        }
364    }
365
366    pub fn all() -> Self {
367        Self {
368            flags: BitFlags::all(),
369        }
370    }
371
372    pub fn from_args(preview: bool, no_preview: bool, preview_features: &[PreviewFeature]) -> Self {
373        if no_preview {
374            return Self::default();
375        }
376
377        if preview {
378            return Self::all();
379        }
380
381        Self::new(preview_features)
382    }
383
384    /// Check if a single feature is enabled.
385    pub fn is_enabled(&self, flag: PreviewFeature) -> bool {
386        self.flags.contains(flag)
387    }
388
389    /// Check if all preview feature rae enabled.
390    pub fn all_enabled(&self) -> bool {
391        self.flags.is_all()
392    }
393
394    /// Check if any preview feature is enabled.
395    pub fn any_enabled(&self) -> bool {
396        !self.flags.is_empty()
397    }
398}
399
400impl Display for Preview {
401    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
402        if self.flags.is_empty() {
403            write!(f, "disabled")
404        } else if self.flags.is_all() {
405            write!(f, "enabled")
406        } else {
407            write!(
408                f,
409                "{}",
410                itertools::join(self.flags.iter().map(PreviewFeature::as_str), ",")
411            )
412        }
413    }
414}
415
416#[derive(Debug, Error, Clone)]
417pub enum PreviewParseError {
418    #[error("Empty string in preview features: {0}")]
419    Empty(String),
420}
421
422impl FromStr for Preview {
423    type Err = PreviewParseError;
424
425    fn from_str(s: &str) -> Result<Self, Self::Err> {
426        let mut flags = BitFlags::empty();
427
428        for part in s.split(',') {
429            let part = part.trim();
430            if part.is_empty() {
431                return Err(PreviewParseError::Empty(
432                    "Empty string in preview features".to_string(),
433                ));
434            }
435
436            match PreviewFeature::from_str(part) {
437                Ok(flag) => flags |= flag,
438                Err(_) => {
439                    warn_user_once!("Unknown preview feature: `{part}`");
440                }
441            }
442        }
443
444        Ok(Self { flags })
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    #[test]
453    fn test_preview_feature_from_str() {
454        let features = PreviewFeature::from_str("python-install-default").unwrap();
455        assert_eq!(features, PreviewFeature::PythonInstallDefault);
456    }
457
458    #[test]
459    fn test_preview_from_str() {
460        // Test single feature
461        let preview = Preview::from_str("python-install-default").unwrap();
462        assert_eq!(preview.flags, PreviewFeature::PythonInstallDefault);
463
464        // Test multiple features
465        let preview = Preview::from_str("python-upgrade,json-output").unwrap();
466        assert!(preview.is_enabled(PreviewFeature::PythonUpgrade));
467        assert!(preview.is_enabled(PreviewFeature::JsonOutput));
468        assert_eq!(preview.flags.bits().count_ones(), 2);
469
470        // Test with whitespace
471        let preview = Preview::from_str("pylock , add-bounds").unwrap();
472        assert!(preview.is_enabled(PreviewFeature::Pylock));
473        assert!(preview.is_enabled(PreviewFeature::AddBounds));
474
475        // Test empty string error
476        assert!(Preview::from_str("").is_err());
477        assert!(Preview::from_str("pylock,").is_err());
478        assert!(Preview::from_str(",pylock").is_err());
479
480        // Test unknown feature (should be ignored with warning)
481        let preview = Preview::from_str("unknown-feature,pylock").unwrap();
482        assert!(preview.is_enabled(PreviewFeature::Pylock));
483        assert_eq!(preview.flags.bits().count_ones(), 1);
484    }
485
486    #[test]
487    fn test_preview_display() {
488        // Test disabled
489        let preview = Preview::default();
490        assert_eq!(preview.to_string(), "disabled");
491        let preview = Preview::new(&[]);
492        assert_eq!(preview.to_string(), "disabled");
493
494        // Test enabled (all features)
495        let preview = Preview::all();
496        assert_eq!(preview.to_string(), "enabled");
497
498        // Test single feature
499        let preview = Preview::new(&[PreviewFeature::PythonInstallDefault]);
500        assert_eq!(preview.to_string(), "python-install-default");
501
502        // Test multiple features
503        let preview = Preview::new(&[PreviewFeature::PythonUpgrade, PreviewFeature::Pylock]);
504        assert_eq!(preview.to_string(), "python-upgrade,pylock");
505    }
506
507    #[test]
508    fn test_preview_from_args() {
509        // Test no preview and no no_preview, and no features
510        let preview = Preview::from_args(false, false, &[]);
511        assert_eq!(preview.to_string(), "disabled");
512
513        // Test no_preview
514        let preview = Preview::from_args(true, true, &[]);
515        assert_eq!(preview.to_string(), "disabled");
516
517        // Test preview (all features)
518        let preview = Preview::from_args(true, false, &[]);
519        assert_eq!(preview.to_string(), "enabled");
520
521        // Test specific features
522        let features = vec![PreviewFeature::PythonUpgrade, PreviewFeature::JsonOutput];
523        let preview = Preview::from_args(false, false, &features);
524        assert!(preview.is_enabled(PreviewFeature::PythonUpgrade));
525        assert!(preview.is_enabled(PreviewFeature::JsonOutput));
526        assert!(!preview.is_enabled(PreviewFeature::Pylock));
527    }
528
529    #[test]
530    fn test_preview_feature_as_str() {
531        assert_eq!(
532            PreviewFeature::PythonInstallDefault.as_str(),
533            "python-install-default"
534        );
535        assert_eq!(PreviewFeature::PythonUpgrade.as_str(), "python-upgrade");
536        assert_eq!(PreviewFeature::JsonOutput.as_str(), "json-output");
537        assert_eq!(PreviewFeature::Pylock.as_str(), "pylock");
538        assert_eq!(PreviewFeature::AddBounds.as_str(), "add-bounds");
539        assert_eq!(
540            PreviewFeature::PackageConflicts.as_str(),
541            "package-conflicts"
542        );
543        assert_eq!(
544            PreviewFeature::ExtraBuildDependencies.as_str(),
545            "extra-build-dependencies"
546        );
547        assert_eq!(
548            PreviewFeature::DetectModuleConflicts.as_str(),
549            "detect-module-conflicts"
550        );
551        assert_eq!(PreviewFeature::Format.as_str(), "format");
552        assert_eq!(PreviewFeature::NativeAuth.as_str(), "native-auth");
553        assert_eq!(PreviewFeature::S3Endpoint.as_str(), "s3-endpoint");
554        assert_eq!(PreviewFeature::CacheSize.as_str(), "cache-size");
555        assert_eq!(
556            PreviewFeature::InitProjectFlag.as_str(),
557            "init-project-flag"
558        );
559        assert_eq!(
560            PreviewFeature::WorkspaceMetadata.as_str(),
561            "workspace-metadata"
562        );
563        assert_eq!(PreviewFeature::WorkspaceDir.as_str(), "workspace-dir");
564        assert_eq!(PreviewFeature::WorkspaceList.as_str(), "workspace-list");
565        assert_eq!(PreviewFeature::SbomExport.as_str(), "sbom-export");
566        assert_eq!(PreviewFeature::AuthHelper.as_str(), "auth-helper");
567        assert_eq!(PreviewFeature::DirectPublish.as_str(), "direct-publish");
568        assert_eq!(
569            PreviewFeature::TargetWorkspaceDiscovery.as_str(),
570            "target-workspace-discovery"
571        );
572        assert_eq!(PreviewFeature::MetadataJson.as_str(), "metadata-json");
573        assert_eq!(PreviewFeature::GcsEndpoint.as_str(), "gcs-endpoint");
574        assert_eq!(PreviewFeature::AdjustUlimit.as_str(), "adjust-ulimit");
575        assert_eq!(
576            PreviewFeature::SpecialCondaEnvNames.as_str(),
577            "special-conda-env-names"
578        );
579        assert_eq!(
580            PreviewFeature::RelocatableEnvsDefault.as_str(),
581            "relocatable-envs-default"
582        );
583        assert_eq!(
584            PreviewFeature::PublishRequireNormalized.as_str(),
585            "publish-require-normalized"
586        );
587        assert_eq!(
588            PreviewFeature::ProjectDirectoryMustExist.as_str(),
589            "project-directory-must-exist"
590        );
591        assert_eq!(
592            PreviewFeature::IndexExcludeNewer.as_str(),
593            "index-exclude-newer"
594        );
595    }
596
597    #[test]
598    fn test_global_preview() {
599        {
600            let _guard =
601                test::with_features(&[PreviewFeature::Pylock, PreviewFeature::WorkspaceMetadata]);
602            assert!(!is_enabled(PreviewFeature::InitProjectFlag));
603            assert!(is_enabled(PreviewFeature::Pylock));
604            assert!(is_enabled(PreviewFeature::WorkspaceMetadata));
605            assert!(!is_enabled(PreviewFeature::AuthHelper));
606        }
607        {
608            let _guard =
609                test::with_features(&[PreviewFeature::InitProjectFlag, PreviewFeature::AuthHelper]);
610            assert!(is_enabled(PreviewFeature::InitProjectFlag));
611            assert!(!is_enabled(PreviewFeature::Pylock));
612            assert!(!is_enabled(PreviewFeature::WorkspaceMetadata));
613            assert!(is_enabled(PreviewFeature::AuthHelper));
614        }
615    }
616
617    #[test]
618    #[should_panic(
619        expected = "Additional calls to `uv_preview::test::with_features` are not allowed while holding a `FeaturesGuard`"
620    )]
621    fn test_global_preview_panic_nested() {
622        let _guard =
623            test::with_features(&[PreviewFeature::Pylock, PreviewFeature::WorkspaceMetadata]);
624        let _guard2 =
625            test::with_features(&[PreviewFeature::InitProjectFlag, PreviewFeature::AuthHelper]);
626    }
627
628    #[test]
629    #[should_panic(expected = "uv_preview::test::with_features")]
630    fn test_global_preview_panic_uninitialized() {
631        let _preview = get();
632    }
633}