uv 0.11.12

A Python package and project manager
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
use std::borrow::Cow;
use std::fmt::Write as _;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, io};

use anyhow::{Context, Result};
use owo_colors::OwoColorize;
use thiserror::Error;
use tracing::{debug, instrument};

use uv_build_backend::check_direct_build;
use uv_cache::{Cache, CacheBucket};
use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder};
use uv_configuration::{
    BuildIsolation, BuildKind, BuildOptions, BuildOutput, Concurrency, Constraints,
    DependencyGroupsWithDefaults, HashCheckingMode, IndexStrategy, KeyringProviderType, NoSources,
};
use uv_dispatch::{BuildDispatch, SharedState};
use uv_distribution::LoweredExtraBuildDependencies;
use uv_distribution_filename::{
    DistFilename, SourceDistExtension, SourceDistFilename, WheelFilename,
};
use uv_distribution_types::{
    ConfigSettings, DependencyMetadata, ExtraBuildVariables, Index, IndexLocations,
    PackageConfigSettings, Requirement, SourceDist,
};
use uv_fs::{Simplified, relative_to};
use uv_install_wheel::LinkMode;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_preview::Preview;
use uv_python::{
    EnvironmentPreference, PythonDownloads, PythonEnvironment, PythonInstallation,
    PythonPreference, PythonRequest, PythonVersionFile, VersionFileDiscoveryOptions,
};
use uv_requirements::RequirementsSource;
use uv_resolver::{ExcludeNewer, FlatIndex};
use uv_settings::PythonInstallMirrors;
use uv_types::{AnyErrorBuild, BuildContext, BuildStack, HashStrategy, SourceTreeEditablePolicy};
use uv_workspace::pyproject::ExtraBuildDependencies;
use uv_workspace::{DiscoveryOptions, Workspace, WorkspaceCache, WorkspaceError};

use crate::commands::ExitStatus;
use crate::commands::pip::operations;
use crate::commands::project::{ProjectError, find_requires_python};
use crate::commands::reporters::PythonDownloadReporter;
use crate::printer::Printer;
use crate::settings::ResolverSettings;

#[derive(Debug, Error)]
enum Error {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error(transparent)]
    FindOrDownloadPython(#[from] uv_python::Error),
    #[error(transparent)]
    HashStrategy(#[from] uv_types::HashStrategyError),
    #[error(transparent)]
    FlatIndex(#[from] uv_client::FlatIndexError),
    #[error(transparent)]
    ClientBuild(#[from] uv_client::ClientBuildError),
    #[error(transparent)]
    BuildPlan(anyhow::Error),
    #[error(transparent)]
    Extract(#[from] uv_extract::Error),
    #[error(transparent)]
    Operations(#[from] operations::Error),
    #[error(transparent)]
    Join(#[from] tokio::task::JoinError),
    #[error(transparent)]
    BuildBackend(#[from] uv_build_backend::Error),
    #[error(transparent)]
    BuildDispatch(AnyErrorBuild),
    #[error(transparent)]
    BuildFrontend(#[from] uv_build_frontend::Error),
    #[error(transparent)]
    Project(#[from] ProjectError),
    #[error("Failed to write message")]
    Fmt(#[from] fmt::Error),
    #[error("Can't use `--force-pep517` with `--list`")]
    ListForcePep517,
    #[error(
        "Can only use `--list` with a compatible uv build backend, but `{name}` is not compatible because {reason}"
    )]
    ListNonUv { name: String, reason: String },
    #[error(
        "`{0}` is not a valid build source. Expected to receive a source directory, or a source \
         distribution ending in one of: {1}."
    )]
    InvalidSourceDistExt(String, uv_distribution_filename::ExtensionError),
    #[error("The built source distribution has an invalid filename")]
    InvalidBuiltSourceDistFilename(#[source] uv_distribution_filename::SourceDistFilenameError),
    #[error("The built wheel has an invalid filename")]
    InvalidBuiltWheelFilename(#[source] uv_distribution_filename::WheelFilenameError),
    #[error("The source distribution declares version {0}, but the wheel declares version {1}")]
    VersionMismatch(Version, Version),
}

/// Build source distributions and wheels.
#[expect(clippy::fn_params_excessive_bools)]
pub(crate) async fn build_frontend(
    project_dir: &Path,
    src: Option<PathBuf>,
    package: Option<PackageName>,
    all_packages: bool,
    output_dir: Option<PathBuf>,
    sdist: bool,
    wheel: bool,
    list: bool,
    build_logs: bool,
    gitignore: bool,
    force_pep517: bool,
    clear: bool,
    build_constraints: Vec<RequirementsSource>,
    build_constraints_from_workspace: Vec<Requirement>,
    hash_checking: Option<HashCheckingMode>,
    python: Option<String>,
    install_mirrors: PythonInstallMirrors,
    settings: &ResolverSettings,
    client_builder: &BaseClientBuilder<'_>,
    no_config: bool,
    python_preference: PythonPreference,
    python_downloads: PythonDownloads,
    concurrency: Concurrency,
    cache: &Cache,
    workspace_cache: &WorkspaceCache,
    printer: Printer,
    preview: Preview,
) -> Result<ExitStatus> {
    let build_result = build_impl(
        project_dir,
        src.as_deref(),
        package.as_ref(),
        all_packages,
        output_dir.as_deref(),
        sdist,
        wheel,
        list,
        build_logs,
        gitignore,
        force_pep517,
        clear,
        &build_constraints,
        &build_constraints_from_workspace,
        hash_checking,
        python.as_deref(),
        install_mirrors,
        settings,
        client_builder,
        no_config,
        python_preference,
        python_downloads,
        &concurrency,
        cache,
        workspace_cache,
        printer,
        preview,
    )
    .await?;

    match build_result {
        BuildResult::Failure => Ok(ExitStatus::Error),
        BuildResult::Success => Ok(ExitStatus::Success),
    }
}

/// Represents the overall result of a build process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BuildResult {
    /// Indicates that at least one of the builds failed.
    Failure,
    /// Indicates that all builds succeeded.
    Success,
}

// https://github.com/rust-lang/rust/issues/147648
#[allow(unused_assignments)]
#[expect(clippy::fn_params_excessive_bools)]
async fn build_impl(
    project_dir: &Path,
    src: Option<&Path>,
    package: Option<&PackageName>,
    all_packages: bool,
    output_dir: Option<&Path>,
    sdist: bool,
    wheel: bool,
    list: bool,
    build_logs: bool,
    gitignore: bool,
    force_pep517: bool,
    clear: bool,
    build_constraints: &[RequirementsSource],
    build_constraints_from_workspace: &[Requirement],
    hash_checking: Option<HashCheckingMode>,
    python_request: Option<&str>,
    install_mirrors: PythonInstallMirrors,
    settings: &ResolverSettings,
    client_builder: &BaseClientBuilder<'_>,
    no_config: bool,
    python_preference: PythonPreference,
    python_downloads: PythonDownloads,
    concurrency: &Concurrency,
    cache: &Cache,
    workspace_cache: &WorkspaceCache,
    printer: Printer,
    preview: Preview,
) -> Result<BuildResult> {
    // Extract the resolver settings.
    let ResolverSettings {
        index_locations,
        index_strategy,
        keyring_provider,
        resolution: _,
        prerelease: _,
        fork_strategy: _,
        dependency_metadata,
        config_setting,
        config_settings_package,
        build_isolation,
        extra_build_dependencies,
        extra_build_variables,
        exclude_newer,
        link_mode,
        upgrade: _,
        build_options,
        sources,
        torch_backend: _,
    } = settings;

    // Determine the source to build.
    let src = if let Some(src) = src {
        let src = std::path::absolute(src)?;
        let metadata = match fs_err::tokio::metadata(&src).await {
            Ok(metadata) => metadata,
            Err(err) if err.kind() == io::ErrorKind::NotFound => {
                return Err(anyhow::anyhow!(
                    "Source `{}` does not exist",
                    src.user_display()
                ));
            }
            Err(err) => return Err(err.into()),
        };
        if metadata.is_file() {
            Source::File(Cow::Owned(src))
        } else {
            Source::Directory(Cow::Owned(src))
        }
    } else {
        Source::Directory(Cow::Borrowed(project_dir))
    };

    // Attempt to discover the workspace; on failure, save the error for later.
    let workspace = Workspace::discover(
        src.directory(),
        &DiscoveryOptions::default(),
        workspace_cache,
    )
    .await;

    // If a `--package` or `--all-packages` was provided, adjust the source directory.
    let packages = if let Some(package) = package {
        if matches!(src, Source::File(_)) {
            return Err(anyhow::anyhow!(
                "Cannot specify `--package` when building from a file"
            ));
        }

        let workspace = match workspace {
            Ok(ref workspace) => workspace,
            Err(err) => {
                return Err(err).context("`--package` was provided, but no workspace was found");
            }
        };

        let package = workspace
            .packages()
            .get(package)
            .ok_or_else(|| anyhow::anyhow!("Package `{package}` not found in workspace"))?;

        if !package.pyproject_toml().is_package(true) {
            let name = &package.project().name;
            let pyproject_toml = package.root().join("pyproject.toml");
            return Err(anyhow::anyhow!(
                "Package `{}` is missing a `{}`. For example, to build with `{}`, add the following to `{}`:\n```toml\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n```",
                name.cyan(),
                "build-system".green(),
                "setuptools".cyan(),
                pyproject_toml.user_display().cyan()
            ));
        }

        vec![AnnotatedSource::from(Source::Directory(Cow::Borrowed(
            package.root(),
        )))]
    } else if all_packages {
        if matches!(src, Source::File(_)) {
            return Err(anyhow::anyhow!(
                "Cannot specify `--all-packages` when building from a file"
            ));
        }

        let workspace = match workspace {
            Ok(ref workspace) => workspace,
            Err(err) => {
                return Err(err)
                    .context("`--all-packages` was provided, but no workspace was found");
            }
        };

        if workspace.packages().is_empty() {
            return Err(anyhow::anyhow!("No packages found in workspace"));
        }

        let packages: Vec<_> = workspace
            .packages()
            .values()
            .filter(|package| package.pyproject_toml().is_package(true))
            .map(|package| AnnotatedSource {
                source: Source::Directory(Cow::Borrowed(package.root())),
                package: Some(package.project().name.clone()),
            })
            .collect();

        if packages.is_empty() {
            let member = workspace.packages().values().next().unwrap();
            let name = &member.project().name;
            let pyproject_toml = member.root().join("pyproject.toml");
            return Err(anyhow::anyhow!(
                "Workspace does not contain any buildable packages. For example, to build `{}` with `{}`, add a `{}` to `{}`:\n```toml\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n```",
                name.cyan(),
                "setuptools".cyan(),
                "build-system".green(),
                pyproject_toml.user_display().cyan()
            ));
        }

        packages
    } else {
        vec![AnnotatedSource::from(src)]
    };

    let results: Vec<_> = futures::future::join_all(packages.into_iter().map(|source| {
        let future = build_package(
            source.clone(),
            output_dir,
            python_request,
            install_mirrors.clone(),
            no_config,
            workspace.as_ref(),
            python_preference,
            python_downloads,
            cache,
            workspace_cache,
            printer,
            index_locations,
            client_builder.clone(),
            hash_checking,
            build_logs,
            gitignore,
            force_pep517,
            clear,
            build_constraints,
            build_constraints_from_workspace,
            build_isolation,
            extra_build_dependencies,
            extra_build_variables,
            *index_strategy,
            *keyring_provider,
            exclude_newer.clone(),
            sources.clone(),
            concurrency,
            build_options,
            sdist,
            wheel,
            list,
            dependency_metadata,
            *link_mode,
            config_setting,
            config_settings_package,
            preview,
        );
        async {
            let result = future.await;
            (source, result)
        }
    }))
    .await;

    let mut success = true;
    for (source, result) in results {
        match result {
            Ok(messages) => {
                for message in messages {
                    message.print(printer)?;
                }
            }
            Err(err) => {
                #[derive(Debug, miette::Diagnostic, thiserror::Error)]
                #[error("Failed to build `{source}`", source = source.cyan())]
                #[diagnostic()]
                struct Diagnostic {
                    source: String,
                    #[source]
                    cause: anyhow::Error,
                    #[help]
                    help: Option<String>,
                }

                let help = if let Error::Extract(uv_extract::Error::Tar(err)) = &err {
                    // TODO(konsti): astral-tokio-tar should use a proper error instead of
                    // encoding everything in strings
                    // NOTE(ww): We check for both messages below because the both indicate
                    // different external extraction scenarios; the first is for any
                    // absolute path outside of the target directory, and the second
                    // is specifically for symlinks that point outside.
                    if err.to_string().contains("/bin/python")
                        && std::error::Error::source(err).is_some_and(|err| {
                            let err = err.to_string();
                            err.ends_with("outside of the target directory")
                                || err.ends_with("external symlinks are not allowed")
                        })
                    {
                        Some(
                            "This file seems to be part of a virtual environment. Virtual environments must be excluded from source distributions."
                                .to_string(),
                        )
                    } else {
                        None
                    }
                } else {
                    None
                };

                let report = miette::Report::new(Diagnostic {
                    source: source.to_string(),
                    cause: err.into(),
                    help,
                });
                anstream::eprint!("{report:?}");

                success = false;
            }
        }
    }

    if success {
        Ok(BuildResult::Success)
    } else {
        Ok(BuildResult::Failure)
    }
}

#[expect(clippy::fn_params_excessive_bools)]
async fn build_package(
    source: AnnotatedSource<'_>,
    output_dir: Option<&Path>,
    python_request: Option<&str>,
    install_mirrors: PythonInstallMirrors,
    no_config: bool,
    workspace: Result<&Workspace, &WorkspaceError>,
    python_preference: PythonPreference,
    python_downloads: PythonDownloads,
    cache: &Cache,
    workspace_cache: &WorkspaceCache,
    printer: Printer,
    index_locations: &IndexLocations,
    client_builder: BaseClientBuilder<'_>,
    hash_checking: Option<HashCheckingMode>,
    build_logs: bool,
    gitignore: bool,
    force_pep517: bool,
    clear: bool,
    build_constraints: &[RequirementsSource],
    build_constraints_from_workspace: &[Requirement],
    build_isolation: &BuildIsolation,
    extra_build_dependencies: &ExtraBuildDependencies,
    extra_build_variables: &ExtraBuildVariables,
    index_strategy: IndexStrategy,
    keyring_provider: KeyringProviderType,
    exclude_newer: ExcludeNewer,
    sources: NoSources,
    concurrency: &Concurrency,
    build_options: &BuildOptions,
    sdist: bool,
    wheel: bool,
    list: bool,
    dependency_metadata: &DependencyMetadata,
    link_mode: LinkMode,
    config_setting: &ConfigSettings,
    config_settings_package: &PackageConfigSettings,
    preview: Preview,
) -> Result<Vec<BuildMessage>, Error> {
    let output_dir = if let Some(output_dir) = output_dir {
        Cow::Owned(std::path::absolute(output_dir)?)
    } else {
        if let Ok(workspace) = workspace {
            Cow::Owned(workspace.install_path().join("dist"))
        } else {
            match &source.source {
                Source::Directory(src) => Cow::Owned(src.join("dist")),
                Source::File(src) => Cow::Borrowed(src.parent().unwrap()),
            }
        }
    };

    // Clear the output directory if requested
    if clear && output_dir.exists() {
        fs_err::remove_dir_all(&*output_dir)?;
    }

    // (1) Explicit request from user
    let mut interpreter_request = python_request.map(PythonRequest::parse);

    // (2) Request from `.python-version`
    if interpreter_request.is_none() {
        interpreter_request = PythonVersionFile::discover(
            source.directory(),
            &VersionFileDiscoveryOptions::default().with_no_config(no_config),
        )
        .await?
        .and_then(PythonVersionFile::into_version);
    }

    // (3) `Requires-Python` in `pyproject.toml`
    if interpreter_request.is_none() {
        if let Ok(workspace) = workspace {
            let groups = DependencyGroupsWithDefaults::none();
            interpreter_request = find_requires_python(workspace, &groups)?
                .and_then(PythonRequest::from_requires_python);
        }
    }

    // Locate the Python interpreter to use in the environment.
    let interpreter = PythonInstallation::find_or_download(
        interpreter_request.as_ref(),
        EnvironmentPreference::Any,
        python_preference,
        python_downloads,
        &client_builder,
        cache,
        Some(&PythonDownloadReporter::single(printer)),
        install_mirrors.python_install_mirror.as_deref(),
        install_mirrors.pypy_install_mirror.as_deref(),
        install_mirrors.python_downloads_json_url.as_deref(),
        preview,
    )
    .await?
    .into_interpreter();

    // Read build constraints.
    let build_constraints =
        operations::read_constraints(build_constraints, &client_builder).await?;

    // Collect the set of required hashes.
    let hasher = if let Some(hash_checking) = hash_checking {
        HashStrategy::from_requirements(
            std::iter::empty(),
            build_constraints
                .iter()
                .map(|entry| (&entry.requirement, entry.hashes.as_slice())),
            Some(&interpreter.resolver_marker_environment()),
            hash_checking,
        )?
    } else {
        HashStrategy::None
    };

    let build_constraints = Constraints::from_requirements(
        build_constraints
            .into_iter()
            .map(|constraint| constraint.requirement)
            .chain(build_constraints_from_workspace.iter().cloned()),
    );

    // Initialize the registry client.
    let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone())
        .index_locations(index_locations.clone())
        .index_strategy(index_strategy)
        .keyring(keyring_provider)
        .markers(interpreter.markers())
        .platform(interpreter.platform())
        .build()?;

    // Determine whether to enable build isolation.
    let environment;
    let types_build_isolation = match build_isolation {
        BuildIsolation::Isolate => uv_types::BuildIsolation::Isolated,
        BuildIsolation::Shared => {
            environment = PythonEnvironment::from_interpreter(interpreter.clone());
            uv_types::BuildIsolation::Shared(&environment)
        }
        BuildIsolation::SharedPackage(packages) => {
            environment = PythonEnvironment::from_interpreter(interpreter.clone());
            uv_types::BuildIsolation::SharedPackage(&environment, packages)
        }
    };

    // Resolve the flat indexes from `--find-links`.
    let flat_index = {
        let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache);
        let entries = client
            .fetch_all(index_locations.flat_indexes().map(Index::url))
            .await?;
        FlatIndex::from_entries(entries, None, &hasher, build_options)
    };

    // Initialize any shared state.
    let state = SharedState::default();

    let extra_build_requires =
        LoweredExtraBuildDependencies::from_non_lowered(extra_build_dependencies.clone())
            .into_inner();

    // Create a build dispatch.
    let build_dispatch = BuildDispatch::new(
        &client,
        cache,
        &build_constraints,
        &interpreter,
        index_locations,
        &flat_index,
        dependency_metadata,
        state.clone(),
        index_strategy,
        config_setting,
        config_settings_package,
        types_build_isolation,
        &extra_build_requires,
        extra_build_variables,
        link_mode,
        build_options,
        &hasher,
        exclude_newer,
        sources.clone(),
        SourceTreeEditablePolicy::Project,
        workspace_cache.clone(),
        concurrency.clone(),
        preview,
    );

    prepare_output_directory(&output_dir, gitignore).await?;

    // Determine the build plan.
    let plan = BuildPlan::determine(&source, sdist, wheel).map_err(Error::BuildPlan)?;

    // Check if the build backend is matching uv version that allows calling in the uv build backend
    // directly.
    let build_action = if list {
        if force_pep517 {
            return Err(Error::ListForcePep517);
        }

        if let Err(reason) = check_direct_build(source.path(), uv_version::version()) {
            return Err(Error::ListNonUv {
                name: source.path().user_display().to_string(),
                reason: reason.to_string(),
            });
        }

        BuildAction::List
    } else if force_pep517 {
        BuildAction::Pep517
    } else {
        match check_direct_build(source.path(), uv_version::version()) {
            Ok(()) => BuildAction::DirectBuild,
            Err(reason) => {
                debug!(
                    "Not using `uv_build` direct build for `{}` because {}",
                    source.path().user_display(),
                    reason
                );
                BuildAction::Pep517
            }
        }
    };

    // Prepare some common arguments for the build.
    let dist = None;
    let subdirectory = None;
    let version_id = source.path().file_name().and_then(|name| name.to_str());

    let build_output = match printer {
        Printer::Default | Printer::NoProgress | Printer::Verbose => {
            if build_logs && !uv_flags::contains(uv_flags::EnvironmentFlags::HIDE_BUILD_OUTPUT) {
                BuildOutput::Stderr
            } else {
                BuildOutput::Quiet
            }
        }
        Printer::Quiet | Printer::Silent => BuildOutput::Quiet,
    };

    let mut build_results = Vec::new();
    match plan {
        BuildPlan::SdistToWheel => {
            // Even when listing files, we still need to build the source distribution for the wheel
            // build.
            if list {
                let sdist_list = build_sdist(
                    source.path(),
                    &output_dir,
                    build_action,
                    &source,
                    printer,
                    "source distribution",
                    &build_dispatch,
                    &sources,
                    dist,
                    subdirectory,
                    version_id,
                    build_output,
                )
                .await?;
                build_results.push(sdist_list);
            }
            let sdist_build = build_sdist(
                source.path(),
                &output_dir,
                build_action.force_build(),
                &source,
                printer,
                "source distribution",
                &build_dispatch,
                &sources,
                dist,
                subdirectory,
                version_id,
                build_output,
            )
            .await?;
            build_results.push(sdist_build.clone());

            // Extract the source distribution into a temporary directory.
            let path = output_dir.join(sdist_build.raw_filename());
            let reader = fs_err::tokio::File::open(&path).await?;
            let ext = SourceDistExtension::from_path(path.as_path())
                .map_err(|err| Error::InvalidSourceDistExt(path.user_display().to_string(), err))?;
            let temp_dir = tempfile::tempdir_in(cache.bucket(CacheBucket::SourceDistributions))?;
            uv_extract::stream::archive(path.display(), reader, ext, temp_dir.path()).await?;

            // Extract the top-level directory from the archive.
            let extracted = match uv_extract::strip_component(temp_dir.path()) {
                Ok(top_level) => top_level,
                Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(),
                Err(err) => return Err(err.into()),
            };

            let wheel_build = build_wheel(
                &extracted,
                &output_dir,
                build_action,
                &source,
                printer,
                "wheel from source distribution",
                &build_dispatch,
                sources,
                dist,
                subdirectory,
                version_id,
                build_output,
                Some(sdist_build.normalized_filename().version()),
            )
            .await?;
            build_results.push(wheel_build);
        }
        BuildPlan::Sdist => {
            let sdist_build = build_sdist(
                source.path(),
                &output_dir,
                build_action,
                &source,
                printer,
                "source distribution",
                &build_dispatch,
                &sources,
                dist,
                subdirectory,
                version_id,
                build_output,
            )
            .await?;
            build_results.push(sdist_build);
        }
        BuildPlan::Wheel => {
            let wheel_build = build_wheel(
                source.path(),
                &output_dir,
                build_action,
                &source,
                printer,
                "wheel",
                &build_dispatch,
                sources,
                dist,
                subdirectory,
                version_id,
                build_output,
                None,
            )
            .await?;
            build_results.push(wheel_build);
        }
        BuildPlan::SdistAndWheel => {
            let sdist_build = build_sdist(
                source.path(),
                &output_dir,
                build_action,
                &source,
                printer,
                "source distribution",
                &build_dispatch,
                &sources,
                dist,
                subdirectory,
                version_id,
                build_output,
            )
            .await?;

            let wheel_build = build_wheel(
                source.path(),
                &output_dir,
                build_action,
                &source,
                printer,
                "wheel",
                &build_dispatch,
                sources,
                dist,
                subdirectory,
                version_id,
                build_output,
                Some(sdist_build.normalized_filename().version()),
            )
            .await?;
            build_results.push(sdist_build);
            build_results.push(wheel_build);
        }
        BuildPlan::WheelFromSdist => {
            // Extract the source distribution into a temporary directory.
            let reader = fs_err::tokio::File::open(source.path()).await?;
            let ext = SourceDistExtension::from_path(source.path()).map_err(|err| {
                Error::InvalidSourceDistExt(source.path().user_display().to_string(), err)
            })?;
            let temp_dir = tempfile::tempdir_in(&output_dir)?;
            uv_extract::stream::archive(source.path().display(), reader, ext, temp_dir.path())
                .await?;

            // If the source distribution has a version in its filename, check the version.
            let version = source
                .path()
                .file_name()
                .and_then(|filename| filename.to_str())
                .and_then(|filename| SourceDistFilename::parsed_normalized_filename(filename).ok())
                .map(|filename| filename.version);

            // Extract the top-level directory from the archive.
            let extracted = match uv_extract::strip_component(temp_dir.path()) {
                Ok(top_level) => top_level,
                Err(uv_extract::Error::NonSingularArchive(_)) => temp_dir.path().to_path_buf(),
                Err(err) => return Err(err.into()),
            };

            let wheel_build = build_wheel(
                &extracted,
                &output_dir,
                build_action,
                &source,
                printer,
                "wheel from source distribution",
                &build_dispatch,
                sources,
                dist,
                subdirectory,
                version_id,
                build_output,
                version.as_ref(),
            )
            .await?;
            build_results.push(wheel_build);
        }
    }

    Ok(build_results)
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum BuildAction {
    /// Only list the files that would be included, don't actually build.
    List,
    /// Build by calling directly into the build backend.
    DirectBuild,
    /// Build through the PEP 517 hooks.
    Pep517,
}

impl BuildAction {
    /// If in list mode, still build the distribution.
    fn force_build(self) -> Self {
        match self {
            // List is only available for the uv build backend
            Self::List => Self::DirectBuild,
            Self::DirectBuild => Self::DirectBuild,
            Self::Pep517 => Self::Pep517,
        }
    }
}

/// Build a source distribution, either through PEP 517 or through a direct build.
#[instrument(skip_all)]
async fn build_sdist(
    source_tree: &Path,
    output_dir: &Path,
    action: BuildAction,
    source: &AnnotatedSource<'_>,
    printer: Printer,
    build_kind_message: &str,
    // Below is only used with PEP 517 builds
    build_dispatch: &BuildDispatch<'_>,
    sources: &NoSources,
    dist: Option<&SourceDist>,
    subdirectory: Option<&Path>,
    version_id: Option<&str>,
    build_output: BuildOutput,
) -> Result<BuildMessage, Error> {
    let build_result = match action {
        BuildAction::List => {
            let source_tree_ = source_tree.to_path_buf();
            let sources_enabled = sources.is_none();
            let (filename, file_list) = tokio::task::spawn_blocking(move || {
                uv_build_backend::list_source_dist(
                    &source_tree_,
                    uv_version::version(),
                    sources_enabled,
                )
            })
            .await??;
            let raw_filename = filename.to_string();
            BuildMessage::List {
                normalized_filename: DistFilename::SourceDistFilename(filename),
                raw_filename,
                source_tree: source_tree.to_path_buf(),
                file_list,
            }
        }
        BuildAction::DirectBuild => {
            writeln!(
                printer.stderr(),
                "{}",
                format!(
                    "{}Building {} (uv build backend)...",
                    source.message_prefix(),
                    build_kind_message
                )
                .bold()
            )?;
            let source_tree = source_tree.to_path_buf();
            let output_dir_ = output_dir.to_path_buf();
            let sources_enabled = sources.is_none();
            let filename = tokio::task::spawn_blocking(move || {
                uv_build_backend::build_source_dist(
                    &source_tree,
                    &output_dir_,
                    uv_version::version(),
                    sources_enabled,
                )
            })
            .await??
            .to_string();

            BuildMessage::Build {
                normalized_filename: DistFilename::SourceDistFilename(
                    SourceDistFilename::parsed_normalized_filename(&filename)
                        .map_err(Error::InvalidBuiltSourceDistFilename)?,
                ),
                raw_filename: filename,
                output_dir: output_dir.to_path_buf(),
            }
        }
        BuildAction::Pep517 => {
            writeln!(
                printer.stderr(),
                "{}",
                format!(
                    "{}Building {}...",
                    source.message_prefix(),
                    build_kind_message
                )
                .bold()
            )?;
            let builder = build_dispatch
                .setup_build(
                    source_tree,
                    subdirectory,
                    source.path(),
                    version_id,
                    dist,
                    sources,
                    BuildKind::Sdist,
                    build_output,
                    BuildStack::default(),
                )
                .await
                .map_err(|err| Error::BuildDispatch(err.into()))?;
            let filename = builder.build(output_dir).await?;
            BuildMessage::Build {
                normalized_filename: DistFilename::SourceDistFilename(
                    SourceDistFilename::parsed_normalized_filename(&filename)
                        .map_err(Error::InvalidBuiltSourceDistFilename)?,
                ),
                raw_filename: filename,
                output_dir: output_dir.to_path_buf(),
            }
        }
    };
    Ok(build_result)
}

/// Build a wheel, either through PEP 517 or through a direct build.
#[instrument(skip_all)]
async fn build_wheel(
    source_tree: &Path,
    output_dir: &Path,
    action: BuildAction,
    source: &AnnotatedSource<'_>,
    printer: Printer,
    build_kind_message: &str,
    // Below is only used with PEP 517 builds
    build_dispatch: &BuildDispatch<'_>,
    sources: NoSources,
    dist: Option<&SourceDist>,
    subdirectory: Option<&Path>,
    version_id: Option<&str>,
    build_output: BuildOutput,
    // Used for checking version consistency
    version: Option<&Version>,
) -> Result<BuildMessage, Error> {
    let build_message = match action {
        BuildAction::List => {
            let source_tree_ = source_tree.to_path_buf();
            let sources_enabled = sources.is_none();
            let (filename, file_list) = tokio::task::spawn_blocking(move || {
                uv_build_backend::list_wheel(&source_tree_, uv_version::version(), sources_enabled)
            })
            .await??;
            let raw_filename = filename.to_string();
            BuildMessage::List {
                normalized_filename: DistFilename::WheelFilename(filename),
                raw_filename,
                source_tree: source_tree.to_path_buf(),
                file_list,
            }
        }
        BuildAction::DirectBuild => {
            writeln!(
                printer.stderr(),
                "{}",
                format!(
                    "{}Building {} (uv build backend)...",
                    source.message_prefix(),
                    build_kind_message
                )
                .bold()
            )?;
            let source_tree = source_tree.to_path_buf();
            let output_dir_ = output_dir.to_path_buf();
            let sources_enabled = sources.is_none();
            let filename = tokio::task::spawn_blocking(move || {
                uv_build_backend::build_wheel(
                    &source_tree,
                    &output_dir_,
                    None,
                    uv_version::version(),
                    sources_enabled,
                )
            })
            .await??;

            let raw_filename = filename.to_string();
            BuildMessage::Build {
                normalized_filename: DistFilename::WheelFilename(filename),
                raw_filename,
                output_dir: output_dir.to_path_buf(),
            }
        }
        BuildAction::Pep517 => {
            writeln!(
                printer.stderr(),
                "{}",
                format!(
                    "{}Building {}...",
                    source.message_prefix(),
                    build_kind_message
                )
                .bold()
            )?;
            let builder = build_dispatch
                .setup_build(
                    source_tree,
                    subdirectory,
                    source.path(),
                    version_id,
                    dist,
                    &sources,
                    BuildKind::Wheel,
                    build_output,
                    BuildStack::default(),
                )
                .await
                .map_err(|err| Error::BuildDispatch(err.into()))?;
            let filename = builder.build(output_dir).await?;
            BuildMessage::Build {
                normalized_filename: DistFilename::WheelFilename(
                    WheelFilename::from_str(&filename).map_err(Error::InvalidBuiltWheelFilename)?,
                ),
                raw_filename: filename,
                output_dir: output_dir.to_path_buf(),
            }
        }
    };
    if let Some(expected) = version {
        let actual = build_message.normalized_filename().version();
        if expected != actual {
            return Err(Error::VersionMismatch(expected.clone(), actual.clone()));
        }
    }
    Ok(build_message)
}

/// Create the output directory and add a `.gitignore`.
async fn prepare_output_directory(output_dir: &Path, gitignore: bool) -> Result<(), Error> {
    // Create the output directory.
    fs_err::tokio::create_dir_all(&output_dir).await?;

    // Add a .gitignore.
    if gitignore {
        match fs_err::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(output_dir.join(".gitignore"))
        {
            Ok(mut file) => file.write_all(b"*")?,
            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
            Err(err) => return Err(err.into()),
        }
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AnnotatedSource<'a> {
    /// The underlying [`Source`] to build.
    source: Source<'a>,
    /// The package name, if known.
    package: Option<PackageName>,
}

impl AnnotatedSource<'_> {
    fn path(&self) -> &Path {
        self.source.path()
    }

    fn directory(&self) -> &Path {
        self.source.directory()
    }

    fn message_prefix(&self) -> Cow<'_, str> {
        if let Some(package) = &self.package {
            Cow::Owned(format!("[{}] ", package.cyan()))
        } else {
            Cow::Borrowed("")
        }
    }
}

impl<'a> From<Source<'a>> for AnnotatedSource<'a> {
    fn from(source: Source<'a>) -> Self {
        Self {
            source,
            package: None,
        }
    }
}

impl fmt::Display for AnnotatedSource<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(package) = &self.package {
            write!(f, "{} @ {}", package, self.path().simplified_display())
        } else {
            write!(f, "{}", self.path().simplified_display())
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Source<'a> {
    /// The input source is a file (i.e., a source distribution in a `.tar.gz` or `.zip` file).
    File(Cow<'a, Path>),
    /// The input source is a directory.
    Directory(Cow<'a, Path>),
}

impl Source<'_> {
    fn path(&self) -> &Path {
        match self {
            Self::File(path) => path.as_ref(),
            Self::Directory(path) => path.as_ref(),
        }
    }

    fn directory(&self) -> &Path {
        match self {
            Self::File(path) => path.parent().unwrap(),
            Self::Directory(path) => path,
        }
    }
}

/// We run all builds in parallel, so we wait until all builds are done to show the success messages
/// in order.
#[derive(Debug, Clone)]
enum BuildMessage {
    /// A built wheel or source distribution.
    Build {
        /// The normalized name of the built distribution.
        normalized_filename: DistFilename,
        /// The name of the built distribution before parsing and normalization.
        raw_filename: String,
        /// The location of the built distribution.
        output_dir: PathBuf,
    },
    /// Show the list of files that would be included in a distribution.
    List {
        /// The normalized name of the build distribution.
        normalized_filename: DistFilename,
        /// The name of the built distribution before parsing and normalization.
        raw_filename: String,
        // All source files are relative to the source tree.
        source_tree: PathBuf,
        // Included file and source file, if not generated.
        file_list: Vec<(String, Option<PathBuf>)>,
    },
}

impl BuildMessage {
    /// The normalized filename of the wheel or source distribution.
    fn normalized_filename(&self) -> &DistFilename {
        match self {
            Self::Build {
                normalized_filename: name,
                ..
            } => name,
            Self::List {
                normalized_filename: name,
                ..
            } => name,
        }
    }

    /// The filename of the wheel or source distribution before normalization.
    fn raw_filename(&self) -> &str {
        match self {
            Self::Build {
                raw_filename: name, ..
            } => name,
            Self::List {
                raw_filename: name, ..
            } => name,
        }
    }

    fn print(&self, printer: Printer) -> Result<()> {
        match self {
            Self::Build {
                raw_filename,
                output_dir,
                ..
            } => {
                writeln!(
                    printer.stderr(),
                    "Successfully built {}",
                    output_dir.join(raw_filename).user_display().bold().cyan()
                )?;
            }
            Self::List {
                raw_filename,
                file_list,
                source_tree,
                ..
            } => {
                writeln!(
                    printer.stdout(),
                    "{}",
                    format!("Building {raw_filename} will include the following files:").bold()
                )?;
                for (file, source) in file_list {
                    if let Some(source) = source {
                        writeln!(
                            printer.stdout(),
                            "{file} ({})",
                            relative_to(source, source_tree)
                                .context("Included files must be relative to source tree")?
                                .display()
                        )?;
                    } else {
                        writeln!(printer.stdout(), "{file} (generated)")?;
                    }
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum BuildPlan {
    /// Build a source distribution from source, then build the wheel from the source distribution.
    SdistToWheel,

    /// Build a source distribution from source.
    Sdist,

    /// Build a wheel from source.
    Wheel,

    /// Build a source distribution and a wheel from source.
    SdistAndWheel,

    /// Build a wheel from a source distribution.
    WheelFromSdist,
}

impl BuildPlan {
    fn determine(source: &AnnotatedSource, sdist: bool, wheel: bool) -> Result<Self> {
        Ok(match &source.source {
            Source::File(_) => {
                // We're building from a file, which must be a source distribution.
                match (sdist, wheel) {
                    (false, true) => Self::WheelFromSdist,
                    (false, false) => {
                        return Err(anyhow::anyhow!(
                            "Pass `--wheel` explicitly to build a wheel from a source distribution"
                        ));
                    }
                    (true, _) => {
                        return Err(anyhow::anyhow!(
                            "Building an `--sdist` from a source distribution is not supported"
                        ));
                    }
                }
            }
            Source::Directory(_) => {
                // We're building from a directory.
                match (sdist, wheel) {
                    (false, false) => Self::SdistToWheel,
                    (false, true) => Self::Wheel,
                    (true, false) => Self::Sdist,
                    (true, true) => Self::SdistAndWheel,
                }
            }
        })
    }
}