kawauso-project 0.3.0

Projects for Kawauso applications
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
//! The project that an application runs in
//!
//! A project is a directory that a marker identifies. This module holds the
//! project, the walk that finds it, and the data directory that the project
//! gives an application outside the repository.

pub mod application_name;
pub mod configuration_file;
pub mod configuration_path;
pub mod data_directory;
pub mod no_configuration;
pub mod project_identifier;
pub mod project_root;

// A caller never names the directory of a platform: the data directory of a
// project wraps it, and no error reports it. The rules of a name are shared
// by two types and belong to neither. These modules are therefore private,
// which keeps them out of the public API.
mod local_data_directory;
mod portable_name;

use std::error::Error;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;

use bon::bon;
use kawauso_config::Loader;
use serde::Serialize;
use serde::de::DeserializeOwned;

pub use self::application_name::ApplicationName;
pub use self::configuration_file::ConfigurationFile;
pub use self::configuration_path::ConfigurationPath;
pub use self::data_directory::DataDirectory;
use self::local_data_directory::LocalDataDirectory;
pub use self::no_configuration::NoConfiguration;
pub use self::project_identifier::ProjectIdentifier;
pub use self::project_root::ProjectRoot;
use crate::error::CreateDataDirectoryError;
use crate::error::DiscoverProjectError;
use crate::error::LoadProjectError;
use crate::error::discover::Markers;
use crate::search::Fallback;
use crate::search::Marker;
use crate::search::Search;
use crate::search::StartDirectory;
use crate::search::state::Marked;

/// The project that an application runs in
///
/// A project is the directory in which a marker of the search matched. An
/// application anchors the relative paths of its resources at this directory,
/// and it writes the files that it creates there.
///
/// The search observed the directory during the walk. No application derives
/// it from the path of a file, because such a calculation repeats the
/// convention of the search and breaks when the convention changes.
///
/// The type parameter is the configuration of the project. An application
/// that reads a configuration writes the type that its file deserializes
/// into, such as `Project<Configuration>`.
///
/// The parameter defaults to [`NoConfiguration`] for an application that
/// never reads its configuration file. Without the default, such an
/// application would still have to name a type that it never uses, because
/// nothing else in its code would say what the parameter is. It writes
/// `Project` instead.
///
/// Every project of an application is one type, whether or not a file exists
/// at its configuration path, so a caller can hold more than one project in a
/// collection.
///
/// # Examples
///
/// ```
/// use kawauso_project::Project;
/// use kawauso_project::Search;
///
/// let directory = tempfile::tempdir()?;
/// let root = directory.path().join("project");
/// std::fs::create_dir_all(root.join("src"))?;
/// std::fs::write(root.join("Cargo.toml"), "")?;
///
/// let search = Search::start(root.join("src")).marker("Cargo.toml");
/// let project: Project = Project::builder()
///     .application("example".parse()?)
///     .load(&search)?;
///
/// // The project reports the canonical path of the directory
/// assert_eq!(project.root().get(), std::fs::canonicalize(&root)?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Project<T = NoConfiguration> {
    /// The directory of the project
    root: ProjectRoot,

    /// The application that the project belongs to
    ///
    /// The name decides the location of the configuration file, and the
    /// directory of the application in the local data directory of the user.
    application: ApplicationName,

    /// The marker that identified the project
    ///
    /// `None` when no marker matched and the search fell back to the start
    /// directory.
    marker: Option<Marker>,

    /// The configuration that the project holds
    ///
    /// `None` when no file exists at the configuration path of the project.
    configuration: Option<T>,

    /// The path at which the project keeps its configuration file
    ///
    /// The path is known whether or not a file exists at it, so that an
    /// application can tell its user where to put the file.
    configuration_path: ConfigurationPath,
}

#[bon]
impl<T> Project<T>
where
    T: DeserializeOwned,
{
    /// Describes a project, then finds it and loads its configuration
    ///
    /// The developer describes the project once: which file holds the
    /// configuration, and, through the [`Search`], where the walk starts and
    /// which markers identify the project. [`load`][load] then runs the
    /// search and reads the file, and
    /// [`load_or_create`][load-or-create] writes the file when the project
    /// has none.
    ///
    /// Every project belongs to an application, and the name of the
    /// application decides where the configuration file is:
    /// `.config/<name>.toml` inside the project. The name is an
    /// [`ApplicationName`], which examines its value when the application
    /// creates it, so a malformed name cannot fail the load. An application
    /// whose host dictates another location names it with
    /// [`configuration_file`][configuration-file] instead. An application
    /// that has no configuration file declares this with
    /// [`without_configuration`][without-configuration], and the project
    /// then reads no file.
    ///
    /// The search must name at least one marker. A search without one does
    /// not compile:
    ///
    /// ```compile_fail
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// let search = Search::start("src");
    /// let project: Project = Project::builder()
    ///     .application("example".parse().unwrap())
    ///     .load(&search)
    ///     .unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`UndiscoverableProject`][undiscoverable] when the search
    /// produces no project: no marker matched, or the walk could not begin.
    ///
    /// Returns [`UnloadableConfiguration`][unloadable] when a configuration
    /// file exists at the location of the project and cannot be read, parsed,
    /// or deserialized.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde::Deserialize;
    ///
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// #[derive(Deserialize)]
    /// struct Configuration {
    ///     port: u16,
    /// }
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::create_dir_all(directory.path().join(".config"))?;
    /// std::fs::write(
    ///     directory.path().join(".config").join("example.toml"),
    ///     "port = 8080",
    /// )?;
    ///
    /// let search = Search::start(directory.path()).marker(".config/example.toml");
    /// let project: Project<Configuration> =
    ///     Project::builder().application("example".parse()?).load(&search)?;
    ///
    /// assert_eq!(project.configuration().unwrap().port, 8080);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [application]: ProjectBuilder::application
    /// [configuration-file]: ProjectBuilder::configuration_file
    /// [load]: ProjectBuilder::load
    /// [load-or-create]: ProjectBuilder::load_or_create
    /// [without-configuration]: ProjectBuilder::without_configuration
    /// [undiscoverable]: LoadProjectError::UndiscoverableProject
    /// [unloadable]: LoadProjectError::UnloadableConfiguration
    // The original function stays private, so `builder` is the only way to
    // describe a project. Its own visibility is set here, because bon gives
    // the generated functions the visibility of the function that it wraps.
    //
    // The generated finishing function stays private as well. A caller
    // finishes with `load` or with `load_or_create`. The two differ in what
    // they do with a project that has no configuration file, and bon
    // generates one finishing function.
    #[builder(
        builder_type(vis = "pub"),
        state_mod(vis = "pub"),
        start_fn(name = builder, vis = "pub"),
        finish_fn(name = finish, vis = "")
    )]
    // project[impl configuration.load]
    // project[impl configuration.location]
    // project[impl discover.markers.required]
    // project[verify discover.markers.required]
    // project[impl configuration.location.custom]
    // project[impl configuration.location.directory]
    // project[impl configuration.missing]
    // project[impl configuration.none]
    // project[impl data.load]
    // project[impl discover.start.caller]
    fn new(
        // bon requires the argument of the finishing function before the
        // members that get a setter.
        #[builder(finish_fn)] search: &Search<Marked>,
        application: ApplicationName,
        // The generated setter is private. The two public methods on the
        // builder wrap it, and each one requires this member to be unset, so
        // a caller cannot name two locations for one file.
        #[builder(default = ConfigurationSource::Conventional, setters(name = configuration_source, vis = ""))]
        configuration: ConfigurationSource,
        // The generated setters are private, and `without_configuration`
        // wraps them. The member records the declaration in the state of the
        // builder. `load_or_create` then requires it to be unset, because an
        // application that reads no configuration file creates none either.
        #[builder(default, setters(name = no_configuration_file, vis = ""))]
        without_configuration: WithoutConfiguration,
    ) -> Result<Self, LoadProjectError> {
        let start = resolve(search.start_directory().get(), std::env::current_dir())
            .map_err(|source| LoadProjectError::UndiscoverableProject { source })?;

        let discovery = walk(&start, search.markers(), search.fallback())
            .map_err(|source| LoadProjectError::UndiscoverableProject { source })?;

        let configuration_file = match &configuration {
            ConfigurationSource::File(file) => file.clone(),
            ConfigurationSource::Conventional => configuration_file_of(&application),
            ConfigurationSource::Directory => configuration_directory_of(&application),
        };

        let configuration_path =
            ConfigurationPath::new(discovery.root.get().join(configuration_file.get()));

        let configuration = match without_configuration {
            // An application that declared that it has no configuration file
            // reads none. A file at the location belongs to something else,
            // and it stays untouched.
            WithoutConfiguration::Present => None,
            WithoutConfiguration::Absent => {
                if exists(configuration_path.get()) {
                    Some(load_configuration(&configuration_path)?)
                } else {
                    None
                }
            }
        };

        Ok(Self {
            root: discovery.root,
            application,
            marker: discovery.marker,
            configuration,
            configuration_path,
        })
    }
}

/// Where a project keeps its configuration file
///
/// The default is the conventional location, which the name of the
/// application decides. A developer whose host dictates another location
/// names it, and a developer who owns a directory in `.config` selects it.
///
/// A developer whose application has no configuration file at all opts out
/// with [`WithoutConfiguration`], which is a separate member of the builder.
/// The location of the file is one question, and whether the application
/// reads a file at all is another. An application that reads none still
/// reports the conventional location to its user.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
enum ConfigurationSource {
    /// The conventional location, `.config/<application>.toml`
    Conventional,

    /// A location that the developer names
    File(ConfigurationFile),

    /// The conventional directory, `.config/<application>/config.toml`
    Directory,
}

/// The declaration that an application has no configuration file
///
/// A developer makes the declaration with
/// [`without_configuration`][without-configuration], which sets the member of
/// the builder that holds this value. The state of that member records the
/// declaration, and [`load_or_create`][load-or-create] requires it to be
/// unset. An application that reads no configuration file creates none
/// either, and the compiler reports a builder that contradicts itself.
///
/// [load-or-create]: ProjectBuilder::load_or_create
/// [without-configuration]: ProjectBuilder::without_configuration
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
enum WithoutConfiguration {
    /// The developer made no declaration, and the project reads its file
    #[default]
    Absent,

    /// The developer declared that the application has no configuration file
    Present,
}

impl<'search, T, S: project_builder::State> ProjectBuilder<'search, T, S>
where
    T: DeserializeOwned,
{
    /// Names the file that holds the configuration of the project
    ///
    /// The value is a path relative to the directory of the project. Use this
    /// method for an application whose host dictates a location, such as a
    /// GitHub Action that reads `.github`. An application that keeps its file
    /// at the conventional `.config/<application>.toml` names no file.
    ///
    /// Where the project gets its configuration is one thing, so this method,
    /// [`with_configuration_directory`][directory], and
    /// [`without_configuration`][without] describe the same thing. A builder
    /// that calls more than one of them does not compile.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde::Deserialize;
    ///
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// #[derive(Deserialize)]
    /// struct Configuration {
    ///     port: u16,
    /// }
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::create_dir_all(directory.path().join(".github"))?;
    /// std::fs::write(
    ///     directory.path().join(".github").join("example.toml"),
    ///     "port = 8080",
    /// )?;
    ///
    /// let search = Search::start(directory.path()).marker(".github/example.toml");
    /// let project: Project<Configuration> = Project::builder()
    ///     .application("example".parse()?)
    ///     .configuration_file(".github/example.toml")
    ///     .load(&search)?;
    ///
    /// assert_eq!(project.configuration().unwrap().port, 8080);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [directory]: ProjectBuilder::with_configuration_directory
    /// [without]: ProjectBuilder::without_configuration
    pub fn configuration_file(
        self,
        configuration_file: impl Into<ConfigurationFile>,
    ) -> ProjectBuilder<'search, T, project_builder::SetConfiguration<S>>
    where
        S::Configuration: project_builder::IsUnset,
        S::WithoutConfiguration: project_builder::IsUnset,
    {
        self.configuration_source(ConfigurationSource::File(configuration_file.into()))
    }

    /// Declares that the application has no configuration file
    ///
    /// The project reads no file, and [`configuration`][configuration]
    /// reports `None` for it. Use this method for an application that wants
    /// only the directory of its project. A file at the conventional
    /// location then belongs to something else, and the project leaves it
    /// alone.
    ///
    /// [`configuration_path`][configuration-path] still reports the
    /// conventional location. An application that writes the file later
    /// therefore knows where the file goes.
    ///
    /// An application that reads no configuration file creates none either,
    /// so [`load_or_create`][load-or-create] does not compile on such a
    /// builder:
    ///
    /// ```compile_fail
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// let search = Search::start(".").marker(".git");
    /// let project: Project<u16> = Project::builder()
    ///     .application("example".parse().unwrap())
    ///     .without_configuration()
    ///     .load_or_create(&search, || 8080)
    ///     .unwrap();
    /// ```
    ///
    /// Where the project gets its configuration is one thing, so this method,
    /// [`configuration_file`][file], and
    /// [`with_configuration_directory`][directory] describe the same thing. A
    /// builder that calls more than one of them does not compile:
    ///
    /// ```compile_fail
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// let search = Search::start(".").marker(".git");
    /// let project: Project = Project::builder()
    ///     .application("example".parse().unwrap())
    ///     .configuration_file(".github/example.toml")
    ///     .without_configuration()
    ///     .load(&search)
    ///     .unwrap();
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::write(directory.path().join(".git"), "")?;
    ///
    /// let search = Search::start(directory.path()).marker(".git");
    /// let project: Project = Project::builder()
    ///     .application("example".parse()?)
    ///     .without_configuration()
    ///     .load(&search)?;
    ///
    /// assert!(project.configuration().is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [configuration]: Project::configuration
    /// [configuration-path]: Project::configuration_path
    /// [directory]: ProjectBuilder::with_configuration_directory
    /// [file]: ProjectBuilder::configuration_file
    /// [load-or-create]: ProjectBuilder::load_or_create
    // project[verify configuration.create.none]
    pub fn without_configuration(
        self,
    ) -> ProjectBuilder<'search, T, project_builder::SetWithoutConfiguration<S>>
    where
        S::Configuration: project_builder::IsUnset,
        S::WithoutConfiguration: project_builder::IsUnset,
    {
        self.no_configuration_file(WithoutConfiguration::Present)
    }

    /// Selects the configuration directory that the application owns in `.config`
    ///
    /// The configuration file becomes `config.toml` in
    /// `.config/<application>`, the directory in which an application keeps
    /// the other files it owns.
    ///
    /// Where the project gets its configuration is one thing, so this method,
    /// [`configuration_file`][file], and [`without_configuration`][without]
    /// describe the same thing. A builder that calls more than one of them
    /// does not compile:
    ///
    /// ```compile_fail
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// let search = Search::start(".").marker(".git");
    /// let project: Project = Project::builder()
    ///     .application("example".parse().unwrap())
    ///     .with_configuration_directory()
    ///     .configuration_file(".github/example.toml")
    ///     .load(&search)
    ///     .unwrap();
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use serde::Deserialize;
    ///
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// #[derive(Deserialize)]
    /// struct Configuration {
    ///     port: u16,
    /// }
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::write(directory.path().join(".git"), "")?;
    /// std::fs::create_dir_all(directory.path().join(".config").join("example"))?;
    /// std::fs::write(
    ///     directory.path().join(".config").join("example").join("config.toml"),
    ///     "port = 8080",
    /// )?;
    ///
    /// let search = Search::start(directory.path()).marker(".git");
    /// let project: Project<Configuration> = Project::builder()
    ///     .application("example".parse()?)
    ///     .with_configuration_directory()
    ///     .load(&search)?;
    ///
    /// assert_eq!(project.configuration().unwrap().port, 8080);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [file]: ProjectBuilder::configuration_file
    /// [without]: ProjectBuilder::without_configuration
    pub fn with_configuration_directory(
        self,
    ) -> ProjectBuilder<'search, T, project_builder::SetConfiguration<S>>
    where
        S::Configuration: project_builder::IsUnset,
        S::WithoutConfiguration: project_builder::IsUnset,
    {
        self.configuration_source(ConfigurationSource::Directory)
    }
}

impl<T, S> ProjectBuilder<'_, T, S>
where
    T: DeserializeOwned,
    S: project_builder::IsComplete,
{
    /// Finds the project and reads its configuration file
    ///
    /// The search runs, and the project reads the file at its configuration
    /// path when a file exists there. A project without the file is a normal
    /// state, and [`configuration`][configuration] reports `None` for it.
    ///
    /// This method writes nothing. A read that writes surprises its caller,
    /// so an application that needs the file states that with
    /// [`load_or_create`][load-or-create].
    ///
    /// # Errors
    ///
    /// Returns [`UndiscoverableProject`][undiscoverable] when the search
    /// produces no project: no marker matched, or the walk could not begin.
    ///
    /// Returns [`UnloadableConfiguration`][unloadable] when a configuration
    /// file exists at the location of the project and cannot be read, parsed,
    /// or deserialized.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde::Deserialize;
    ///
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// #[derive(Deserialize)]
    /// struct Configuration {
    ///     port: u16,
    /// }
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::write(directory.path().join(".git"), "")?;
    ///
    /// let search = Search::start(directory.path()).marker(".git");
    /// let project: Project<Configuration> =
    ///     Project::builder().application("example".parse()?).load(&search)?;
    ///
    /// assert!(project.configuration().is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [configuration]: Project::configuration
    /// [load-or-create]: ProjectBuilder::load_or_create
    /// [undiscoverable]: LoadProjectError::UndiscoverableProject
    /// [unloadable]: LoadProjectError::UnloadableConfiguration
    // project[impl configuration.create.load]
    pub fn load(self, search: &Search<Marked>) -> Result<Project<T>, LoadProjectError> {
        self.finish(search)
    }

    /// Finds the project, and creates its configuration file when it has none
    ///
    /// The search runs, and the project reads the file at its configuration
    /// path when a file exists there. When none exists, the closure produces
    /// the configuration, the project writes it to that path, and
    /// [`configuration`][configuration] then reports the value that the file
    /// holds. The crate creates the directories that the path needs as well.
    ///
    /// Use this method for an application that needs the file. Such an
    /// application keeps a value in the file that it makes for one project,
    /// an identifier for example. No constant describes such a value, so the
    /// caller supplies it. The closure runs only when the project has no
    /// configuration file.
    ///
    /// Creation is the only write. A file that a user wrote holds their
    /// comments and the order of their fields. A serializer that writes the
    /// whole document loses both, so this method does not repair a file that
    /// exists. A file that the type of the application rejects fails the
    /// load, and the message of the error names the problem for the user to
    /// correct.
    ///
    /// The search runs before the write, and a search that finds no project
    /// fails, so this method writes no file outside a project.
    ///
    /// # Errors
    ///
    /// Returns [`UndiscoverableProject`][undiscoverable] when the search
    /// produces no project: no marker matched, or the walk could not begin.
    ///
    /// Returns [`UnloadableConfiguration`][unloadable] when a configuration
    /// file exists at the location of the project and cannot be read, parsed,
    /// or deserialized.
    ///
    /// Returns [`UncreatableConfiguration`][uncreatable] when the project has
    /// no configuration file, and the value cannot be serialized or the file
    /// cannot be written.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde::Deserialize;
    /// use serde::Serialize;
    ///
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    ///
    /// #[derive(Deserialize, Serialize)]
    /// struct Configuration {
    ///     id: String,
    /// }
    ///
    /// let directory = tempfile::tempdir()?;
    /// std::fs::write(directory.path().join(".git"), "")?;
    ///
    /// let search = Search::start(directory.path()).marker(".git");
    /// let project: Project<Configuration> = Project::builder()
    ///     .application("example".parse()?)
    ///     .load_or_create(&search, || Configuration {
    ///         id: "f2a1b7".to_owned(),
    ///     })?;
    ///
    /// assert_eq!(project.configuration().unwrap().id, "f2a1b7");
    /// assert!(project.configuration_path().get().is_file());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [configuration]: Project::configuration
    /// [uncreatable]: LoadProjectError::UncreatableConfiguration
    /// [undiscoverable]: LoadProjectError::UndiscoverableProject
    /// [unloadable]: LoadProjectError::UnloadableConfiguration
    // project[impl configuration.create]
    // project[impl configuration.create.existing]
    // project[impl configuration.create.none]
    // project[impl configuration.create.result]
    pub fn load_or_create<F>(
        self,
        search: &Search<Marked>,
        configuration: F,
    ) -> Result<Project<T>, LoadProjectError>
    where
        F: FnOnce() -> T,
        S::WithoutConfiguration: project_builder::IsUnset,
        T: Serialize,
    {
        let mut project = self.finish(search)?;

        // A project reports a configuration when a file exists at its path,
        // and the load already read that file. The closure therefore runs
        // only for a project whose file this method creates.
        if project.configuration.is_none() {
            let configuration = configuration();

            create_configuration(&project.configuration_path, &configuration)?;

            project.configuration = Some(configuration);
        }

        Ok(project)
    }
}

impl<T> Project<T> {
    /// Returns the configuration that the project holds
    ///
    /// Returns `None` when no file exists at the configuration path of the
    /// project, which is a normal state and not a failure. An application
    /// whose configuration is required reports that itself, and
    /// [`configuration_path`][configuration-path] tells its user where to put
    /// the file.
    ///
    /// [configuration-path]: Project::configuration_path
    pub fn configuration(&self) -> Option<&T> {
        self.configuration.as_ref()
    }

    /// Returns the path at which the project keeps its configuration file
    ///
    /// The path is known whether or not a file exists at it.
    pub fn configuration_path(&self) -> &ConfigurationPath {
        &self.configuration_path
    }

    /// Creates the data directory of the project and returns its path
    ///
    /// The data directory is outside the repository, in the local data
    /// directory of the user: `<data>/<application>/projects/<identifier>`.
    /// An application writes the files of the project here that must not be
    /// in the working tree, such as a log for each run.
    ///
    /// `<data>` is `XDG_DATA_HOME`, or `.local/share` in the home directory,
    /// on Linux and the other systems that follow the XDG Base Directory
    /// Specification. It is `Library/Application Support` in the home
    /// directory on macOS, and the directory for the local application data
    /// of the user on Windows.
    ///
    /// The application supplies the identifier, because only the application
    /// knows what makes two checkouts the same project. The project does not
    /// keep the identifier, so a call with another identifier returns another
    /// directory.
    ///
    /// Each call creates the directory and the directories above it when they
    /// do not exist. A directory that the user deleted while the application
    /// ran therefore exists again after the next call, and a call for a
    /// directory that exists succeeds. On Unix, the directories that the call
    /// creates get the mode `0700`, so that only the user can read them. A
    /// directory that exists keeps its mode.
    ///
    /// The load of a project does not create the data directory. A project
    /// that never calls this method therefore writes nothing to the data
    /// directory of the user.
    ///
    /// # Errors
    ///
    /// Returns [`UnknownLocalDataDirectory`][unknown] when the platform has no
    /// local data directory, when the crate cannot determine the home
    /// directory of the user, or when the directory that it finds is not an
    /// absolute path.
    ///
    /// Returns [`UncreatableDataDirectory`][uncreatable] when the directory
    /// or a directory above it cannot be created. The error names the path of
    /// the data directory.
    ///
    /// The crate has no fallback directory. An application whose files are
    /// optional reports the error as a warning and continues.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use kawauso_project::Project;
    /// use kawauso_project::Search;
    /// use kawauso_project::project::ProjectIdentifier;
    ///
    /// let search = Search::working_directory().marker(".git");
    /// let project: Project = Project::builder()
    ///     .application("example".parse()?)
    ///     .load(&search)?;
    ///
    /// let identifier: ProjectIdentifier = "my-project".parse()?;
    /// let directory = project.data_directory(&identifier)?;
    ///
    /// std::fs::write(directory.get().join("run.log"), "")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [uncreatable]: CreateDataDirectoryError::UncreatableDataDirectory
    /// [unknown]: CreateDataDirectoryError::UnknownLocalDataDirectory
    pub fn data_directory(
        &self,
        identifier: &ProjectIdentifier,
    ) -> Result<DataDirectory, CreateDataDirectoryError> {
        self.data_directory_below(LocalDataDirectory::of_platform(), identifier)
    }

    /// Creates the data directory of the project below a base directory
    ///
    /// The base is an argument, so that a test can name a directory of its
    /// own and does not write to the directory of the user.
    ///
    /// # Errors
    ///
    /// Returns an error when the base is unknown, and when the data directory
    /// or a directory above it cannot be created.
    fn data_directory_below(
        &self,
        base: Option<LocalDataDirectory>,
        identifier: &ProjectIdentifier,
    ) -> Result<DataDirectory, CreateDataDirectoryError> {
        create_data_directory(base, &self.application, identifier)
    }

    /// Returns the marker that identified the project
    ///
    /// Returns `None` when no marker matched and the search fell back to the
    /// start directory.
    pub fn marker(&self) -> Option<&Marker> {
        self.marker.as_ref()
    }

    /// Returns the directory of the project
    pub fn root(&self) -> &ProjectRoot {
        &self.root
    }
}

/// What the walk found: a directory, and the marker that identified it
///
/// The walk runs before the crate knows the configuration of the project, so
/// it cannot produce a [`Project`] on its own. This type carries its result
/// until the configuration joins it.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
struct Discovery {
    /// The directory of the project
    root: ProjectRoot,

    /// The marker that identified the project, if one matched
    marker: Option<Marker>,
}

/// Returns the conventional location of the configuration file
///
/// Our projects keep the file of a tool in the subdirectory `.config`, with
/// the name of the application and the extension `.toml`. The crate states
/// this convention here, so that no application repeats it.
// project[impl configuration.location]
fn configuration_file_of(application: &ApplicationName) -> ConfigurationFile {
    ConfigurationFile::new(PathBuf::from(".config").join(format!("{application}.toml")))
}

/// Returns the directory location of the configuration file
///
/// An application that owns the directory `.config/<application>` keeps its
/// configuration in `config.toml` inside it, next to the other files that it
/// writes. The directory, like the file layout, is conventional, so no
/// application repeats it.
// project[impl configuration.location.directory]
fn configuration_directory_of(application: &ApplicationName) -> ConfigurationFile {
    ConfigurationFile::new(
        PathBuf::from(".config")
            .join(application.get())
            .join("config.toml"),
    )
}

/// Creates the data directory of a project and returns its path
///
/// The local data directory of the platform is an argument, so that a test
/// can name a directory of its own, and does not write to the directory of
/// the user. `None` stands for a platform that names no such directory.
///
/// A base that is not an absolute path counts as unknown. Such a path
/// resolves against the working directory, and the data directory would then
/// be inside the working tree that it exists to avoid.
///
/// # Errors
///
/// Returns an error when the local data directory is unknown or relative, and
/// when the data directory or a directory above it cannot be created.
// project[impl data.base.absolute]
// project[impl data.create]
// project[impl data.create.existing]
// project[impl data.create.mode]
// project[impl data.error.create]
// project[impl data.error.unknown-directory]
// project[impl data.path]
fn create_data_directory(
    base: Option<LocalDataDirectory>,
    application: &ApplicationName,
    identifier: &ProjectIdentifier,
) -> Result<DataDirectory, CreateDataDirectoryError> {
    // A relative base, such as one from a relative `HOME`, would put the
    // directory below the working directory, which can be the repository.
    let base = base
        .filter(|base| base.get().is_absolute())
        .ok_or(CreateDataDirectoryError::UnknownLocalDataDirectory {})?;

    // The segment `projects` keeps the directory of the application free for
    // files that belong to no project, so that no identifier collides with
    // them.
    let directory = DataDirectory::new(
        base.get()
            .join(application.get())
            .join("projects")
            .join(identifier.get()),
    );

    // A recursive builder succeeds when the directory exists, and it gives
    // its mode to each directory that it creates, the base and the directory
    // of the application included.
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);

    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);

    builder.create(directory.get()).map_err(|source| {
        CreateDataDirectoryError::UncreatableDataDirectory {
            path: directory.clone(),
            source,
        }
    })?;

    Ok(directory)
}

/// Writes a configuration file, with the directories that its path needs
///
/// The caller established that no file exists at the path, so the write
/// destroys no formatting of an author. The function creates the directories
/// above the file as well. The conventional location lives in `.config`, and
/// a project that never held a configuration file has no such directory.
///
/// The cause of a failure is boxed, because the type that produced it belongs
/// to a dependency and never crosses the boundary of this crate.
///
/// # Errors
///
/// Returns an error when the value cannot be serialized, when the directories
/// cannot be created, or when the file cannot be written.
// project[impl configuration.create]
// project[impl configuration.create.directories]
// project[impl configuration.create.error]
fn create_configuration<T>(
    path: &ConfigurationPath,
    configuration: &T,
) -> Result<(), LoadProjectError>
where
    T: Serialize,
{
    let uncreatable =
        |source: Box<dyn Error + Send + Sync>| LoadProjectError::UncreatableConfiguration {
            path: path.clone(),
            source,
        };

    let contents =
        toml::to_string_pretty(configuration).map_err(|source| uncreatable(Box::new(source)))?;

    if let Some(directory) = path.get().parent() {
        std::fs::create_dir_all(directory).map_err(|source| uncreatable(Box::new(source)))?;
    }

    std::fs::write(path.get(), contents).map_err(|source| uncreatable(Box::new(source)))
}

/// Reads a configuration file and deserializes it
///
/// The read and the deserialization belong to `kawauso-config`, so a failure
/// in a file of a project is reported in the same words as for every other
/// configuration file. The cause is boxed, because the type that produced it
/// belongs to a dependency and never crosses the boundary of this crate.
///
/// # Errors
///
/// Returns an error when the file cannot be read, parsed, or deserialized.
// project[impl configuration.error]
// project[impl configuration.load]
fn load_configuration<T>(path: &ConfigurationPath) -> Result<T, LoadProjectError>
where
    T: DeserializeOwned,
{
    Loader::path(path.get())
        .load()
        .map_err(|source| LoadProjectError::UnloadableConfiguration {
            path: path.clone(),
            source: Box::new(source),
        })
}

/// Reports whether an entry exists at a path
///
/// Any entry counts: a file, a directory, or a symbolic link to one of them.
/// A `.git` entry, for example, is a directory in a repository and a file in
/// a worktree, and both identify the repository. A symbolic link whose target
/// does not exist counts as nothing, because the file system reports nothing
/// about the target.
fn exists(path: &Path) -> bool {
    std::fs::metadata(path).is_ok()
}

/// Reports whether a marker names an entry inside another directory
///
/// A path that joins onto a directory can leave it again. An absolute path
/// replaces the directory, and a `..` component moves above it. Either one
/// takes the search to a place that the walk never reaches, and an absolute
/// path takes every directory of the walk to the same place.
///
/// A path that names no entry at all, such as an empty path or `.`, is no
/// marker either: every directory holds it, so the start would always be the
/// project.
fn is_inside(marker: &Marker) -> bool {
    let mut names_an_entry = false;

    for component in marker.get().components() {
        match component {
            Component::Normal(_) => names_an_entry = true,
            Component::CurDir => {}
            Component::ParentDir | Component::Prefix(_) | Component::RootDir => return false,
        }
    }

    names_an_entry
}

/// Resolves the start of the walk to the canonical path of a directory
///
/// A relative start resolves against the working directory of the process,
/// which the caller supplies, so that a test can name one. The result is the
/// canonical path: the `.` and `..` components go, and the symbolic links
/// resolve.
///
/// The walk goes up one component at a time. A `..` component after a
/// symbolic link would otherwise take the walk through a directory that the
/// caller never entered. The directory that the walk reports is the directory
/// that holds the marker, and a caller that joins a path onto it reaches the
/// entry that the walk saw.
///
/// A start that names a file yields the directory that holds the file,
/// because the project that governs a file is the project of that directory.
///
/// # Errors
///
/// Returns an error when the start is relative and the working directory is
/// unknown, or when the start does not exist or cannot be read.
// project[impl discover.start.absolute+2]
// project[impl discover.start.error.unknown-directory]
// project[impl discover.start.error.unreadable]
// project[impl discover.start.file]
fn resolve(
    start: &Path,
    working_directory: std::io::Result<PathBuf>,
) -> Result<PathBuf, DiscoverProjectError> {
    let absolute = if start.is_absolute() {
        start.to_path_buf()
    } else {
        // An empty path is the working directory to every other operation of
        // the standard library, and joining it onto the working directory
        // gives the same answer here.
        let working_directory = working_directory
            .map_err(|source| DiscoverProjectError::UnknownWorkingDirectory { source })?;

        working_directory.join(start)
    };

    // Canonicalization reads the file system, so a start that does not exist,
    // or that the process cannot read, fails here. The report names the start
    // as the caller gave it, resolved against the working directory, because
    // the canonical path of such a start does not exist.
    let start = std::fs::canonicalize(&absolute).map_err(|source| {
        DiscoverProjectError::UnreadableStart {
            start: StartDirectory::new(absolute),
            source,
        }
    })?;

    // Canonicalization already read the path, so the file system answers this
    // question, and a path that it cannot answer for is no directory.
    if start.is_dir() {
        return Ok(start);
    }

    let directory = start
        .parent()
        .map_or_else(|| start.clone(), Path::to_path_buf);

    Ok(directory)
}

/// Walks from the start to the root of the file system and tests the markers
///
/// The walk is the outer loop, so every marker is tested in one directory
/// before any marker is tested in the directory above it. A project therefore
/// wins over the directory that contains it.
///
/// The markers are tested before the walk begins, because a marker that
/// leaves its directory is a mistake in the application, and reading the file
/// system would not make the answer any better.
///
/// # Errors
///
/// Returns an error when a marker is not a relative path inside a directory,
/// and when no marker matches in any directory of the walk.
// project[impl discover.error.missing]
// project[impl discover.markers]
// project[impl discover.markers.error.outside]
// project[impl discover.markers.walk]
// project[impl discover.order]
// project[impl discover.precedence]
// project[impl discover.result]
// project[impl discover.walk]
fn walk(
    start: &Path,
    markers: &[Marker],
    fallback: Fallback,
) -> Result<Discovery, DiscoverProjectError> {
    if let Some(marker) = markers.iter().find(|marker| !is_inside(marker)) {
        return Err(DiscoverProjectError::OutsideMarker {
            marker: marker.clone(),
        });
    }

    for directory in start.ancestors() {
        for marker in markers {
            if exists(&directory.join(marker.get())) {
                return Ok(Discovery {
                    root: ProjectRoot::new(directory.to_path_buf()),
                    marker: Some(marker.clone()),
                });
            }
        }
    }

    match fallback {
        // project[impl discover.fallback]
        Fallback::Start => Ok(Discovery {
            root: ProjectRoot::new(start.to_path_buf()),
            marker: None,
        }),
        Fallback::Error => Err(DiscoverProjectError::MissingProject {
            start: StartDirectory::new(start.to_path_buf()),
            markers: Markers::new(markers.to_vec()),
        }),
    }
}

#[cfg(test)]
mod tests {
    // An assertion in a test panics by design. A `# Panics` section on every
    // test would repeat that and give the reader no information.
    #![allow(clippy::missing_panics_doc)]

    use std::io::ErrorKind;

    use tempfile::TempDir;

    use super::*;

    /// A marker that no directory of the file system holds
    ///
    /// A walk that must not match needs a marker that no ancestor of a
    /// temporary directory holds, up to the root of the file system.
    const ABSENT: &str = ".kawauso-project-absent-marker";

    /// Returns the canonical path of the temporary directory
    ///
    /// A temporary directory can sit below a symbolic link, which is what
    /// macOS does for `/var`. The walk reports canonical paths, so a test
    /// that names a location in the directory canonicalizes it first.
    fn canonical(root: &TempDir) -> PathBuf {
        std::fs::canonicalize(root.path()).unwrap()
    }

    /// Creates a directory below the temporary directory and returns its path
    fn directory(root: &TempDir, path: &str) -> PathBuf {
        let directory = root.path().join(path);
        std::fs::create_dir_all(&directory).unwrap();

        directory
    }

    /// Creates an empty file below the temporary directory
    fn file(root: &TempDir, path: &str) {
        let file = root.path().join(path);
        if let Some(parent) = file.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(file, "").unwrap();
    }

    /// Returns the name of the application in the tests of the data directory
    fn application() -> ApplicationName {
        "example".parse().unwrap()
    }

    /// Returns the identifier of the project in the tests of the data directory
    fn identifier() -> ProjectIdentifier {
        "example-project".parse().unwrap()
    }

    // project[verify data.create]
    #[test]
    fn create_data_directory_creates_the_directory() {
        let root = tempfile::tempdir().unwrap();
        let base = LocalDataDirectory::new(root.path().join("data"));

        let directory = create_data_directory(Some(base), &application(), &identifier()).unwrap();

        assert!(directory.get().is_dir());
    }

    // Each directory that the call creates gets the mode, the base and the
    // directory of the application included. The mask of the process can
    // only remove permissions, so it cannot make a mode wider than `0700`.
    // project[verify data.create.mode]
    #[cfg(unix)]
    #[test]
    fn create_data_directory_on_unix_creates_directories_for_the_user_alone() {
        use std::os::unix::fs::PermissionsExt;

        let root = tempfile::tempdir().unwrap();
        let base = root.path().join("data");

        create_data_directory(
            Some(LocalDataDirectory::new(base.clone())),
            &application(),
            &identifier(),
        )
        .unwrap();

        let modes: Vec<u32> = [
            base.clone(),
            base.join("example"),
            base.join("example").join("projects"),
            base.join("example")
                .join("projects")
                .join("example-project"),
        ]
        .iter()
        .map(|path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777)
        .collect();

        assert_eq!(modes, vec![0o700; 4]);
    }

    // project[verify data.path]
    #[test]
    fn create_data_directory_returns_the_directory_of_the_project() {
        let root = tempfile::tempdir().unwrap();
        let base = LocalDataDirectory::new(root.path().to_path_buf());

        let directory = create_data_directory(Some(base), &application(), &identifier()).unwrap();

        assert_eq!(
            directory.get(),
            root.path()
                .join("example")
                .join("projects")
                .join("example-project")
        );
    }

    // project[verify data.error.create]
    #[test]
    fn create_data_directory_with_a_file_as_the_base_names_the_directory() {
        let root = tempfile::tempdir().unwrap();
        file(&root, "data");
        let base = LocalDataDirectory::new(root.path().join("data"));

        let error = create_data_directory(Some(base), &application(), &identifier()).unwrap_err();

        assert_eq!(
            error.to_string(),
            format!(
                "failed to create the data directory of the project at `{}`",
                root.path()
                    .join("data")
                    .join("example")
                    .join("projects")
                    .join("example-project")
                    .display()
            )
        );
    }

    // project[verify data.error.create]
    #[test]
    fn create_data_directory_with_a_file_as_the_base_reports_the_cause() {
        let root = tempfile::tempdir().unwrap();
        file(&root, "data");
        let base = LocalDataDirectory::new(root.path().join("data"));

        let error = create_data_directory(Some(base), &application(), &identifier()).unwrap_err();

        assert!(Error::source(&error).is_some());
    }

    // project[verify data.error.create]
    #[test]
    fn create_data_directory_with_a_file_as_the_base_returns_an_error() {
        let root = tempfile::tempdir().unwrap();
        file(&root, "data");
        let base = LocalDataDirectory::new(root.path().join("data"));

        let error = create_data_directory(Some(base), &application(), &identifier()).unwrap_err();

        assert!(matches!(
            error,
            CreateDataDirectoryError::UncreatableDataDirectory { .. }
        ));
    }

    // project[verify data.base.absolute]
    #[test]
    fn create_data_directory_with_a_relative_base_returns_an_error() {
        // A file of the crate is in the path, so that a fault that ignores the
        // rule cannot create a directory in the working tree of the test.
        let base = LocalDataDirectory::new(PathBuf::from("Cargo.toml").join("data"));

        let error = create_data_directory(Some(base), &application(), &identifier()).unwrap_err();

        assert!(matches!(
            error,
            CreateDataDirectoryError::UnknownLocalDataDirectory { .. }
        ));
    }

    // project[verify data.create.existing]
    #[test]
    fn create_data_directory_with_an_existing_directory_returns_the_directory() {
        let root = tempfile::tempdir().unwrap();
        let existing = directory(&root, "example/projects/example-project");
        let base = LocalDataDirectory::new(root.path().to_path_buf());

        let directory = create_data_directory(Some(base), &application(), &identifier()).unwrap();

        assert_eq!(directory.get(), existing);
    }

    // project[verify data.error.unknown-directory]
    #[test]
    fn create_data_directory_without_a_base_returns_an_error() {
        let error = create_data_directory(None, &application(), &identifier()).unwrap_err();

        assert!(matches!(
            error,
            CreateDataDirectoryError::UnknownLocalDataDirectory { .. }
        ));
    }

    // The application whose project this is names the directory below the
    // base, so the name that the builder took reaches the path.
    // project[verify data.path]
    #[test]
    fn data_directory_below_returns_the_directory_of_the_application() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, "project/.git");
        let search = Search::start(root.path().join("project")).marker(".git");
        let project: Project = Project::builder()
            .application("other".parse().unwrap())
            .load(&search)
            .unwrap();
        let base = LocalDataDirectory::new(root.path().join("data"));

        let directory = project
            .data_directory_below(Some(base), &identifier())
            .unwrap();

        assert_eq!(
            directory.get(),
            root.path()
                .join("data")
                .join("other")
                .join("projects")
                .join("example-project")
        );
    }

    // The test reads the local data directory of the user, and writes
    // nothing there. It therefore needs an environment that names that
    // directory. The name of the application is unique to this test, so that
    // no other application owns a directory with the name. Only a load that
    // creates the directory, which is the fault that the test finds, leaves
    // the directory behind for a later run.
    // project[verify data.load]
    #[test]
    fn load_creates_no_data_directory() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        let application: ApplicationName =
            "kawauso-project-test-load-creates-nothing".parse().unwrap();
        let search = Search::start(root.path()).marker(".git");

        let _project: Project = Project::builder()
            .application(application.clone())
            .load(&search)
            .unwrap();

        let base = LocalDataDirectory::of_platform().expect("the test needs a data directory");
        assert!(!exists(&base.get().join(application.get())));
    }

    // project[verify discover.start.file]
    #[test]
    fn resolve_with_a_file_returns_its_directory() {
        let root = tempfile::tempdir().unwrap();
        file(&root, "src/main.rs");

        let start = resolve(&root.path().join("src").join("main.rs"), Ok(PathBuf::new())).unwrap();

        assert_eq!(start, canonical(&root).join("src"));
    }

    // project[verify discover.start.absolute+2]
    #[test]
    fn resolve_with_a_relative_start_resolves_against_the_working_directory() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, "src");

        let start = resolve(Path::new("src"), Ok(root.path().to_path_buf())).unwrap();

        assert_eq!(start, canonical(&root).join("src"));
    }

    // project[verify discover.start.error.unreadable]
    #[test]
    fn resolve_with_a_start_that_does_not_exist_returns_an_error() {
        let root = tempfile::tempdir().unwrap();

        let error = resolve(&root.path().join("absent"), Ok(PathBuf::new())).unwrap_err();

        assert!(matches!(
            error,
            DiscoverProjectError::UnreadableStart { .. }
        ));
    }

    // A `..` component after a symbolic link leaves the tree that the link
    // points into. A walk that keeps the link therefore passes through a
    // directory that the user never entered, which this test holds the
    // resolution to.
    // project[verify discover.start.absolute+2]
    #[cfg(unix)]
    #[test]
    fn resolve_with_a_symbolic_link_returns_the_real_path() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, "real/inner");
        std::os::unix::fs::symlink(root.path().join("real"), root.path().join("link")).unwrap();

        let start = resolve(&root.path().join("link").join("inner"), Ok(PathBuf::new())).unwrap();

        assert_eq!(start, canonical(&root).join("real").join("inner"));
    }

    // project[verify discover.start.absolute+2]
    #[test]
    fn resolve_with_dot_components_removes_them() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, "src");

        let start = resolve(
            &root.path().join("src").join("..").join("src"),
            Ok(PathBuf::new()),
        )
        .unwrap();

        assert_eq!(start, canonical(&root).join("src"));
    }

    // project[verify discover.start.error.unknown-directory]
    #[test]
    fn resolve_without_a_working_directory_returns_an_error() {
        let unknown = std::io::Error::new(ErrorKind::NotFound, "the working directory is gone");

        let error = resolve(Path::new("src"), Err(unknown)).unwrap_err();

        assert!(matches!(
            error,
            DiscoverProjectError::UnknownWorkingDirectory { .. }
        ));
    }

    // project[verify discover.markers]
    #[test]
    fn walk_with_a_directory_as_the_marker_returns_the_project() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");

        let discovery = walk(root.path(), &[Marker::from(".git")], Fallback::Error).unwrap();

        assert_eq!(discovery.root.get(), root.path());
    }

    // project[verify discover.markers.error.outside]
    #[test]
    fn walk_with_a_marker_above_the_directory_returns_an_error() {
        let root = tempfile::tempdir().unwrap();

        let error = walk(root.path(), &[Marker::from("../.git")], Fallback::Error).unwrap_err();

        assert!(matches!(error, DiscoverProjectError::OutsideMarker { .. }));
    }

    // project[verify discover.walk]
    #[test]
    fn walk_with_a_marker_in_an_ancestor_returns_the_ancestor() {
        let root = tempfile::tempdir().unwrap();
        file(&root, "Cargo.toml");
        let start = directory(&root, "crates/example/src");

        let discovery = walk(&start, &[Marker::from("Cargo.toml")], Fallback::Error).unwrap();

        assert_eq!(discovery.root.get(), root.path());
    }

    // project[verify discover.result]
    #[test]
    fn walk_with_a_marker_in_an_ancestor_returns_the_marker() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        let start = directory(&root, "src");

        let discovery = walk(&start, &[Marker::from(".git")], Fallback::Error).unwrap();

        assert_eq!(discovery.marker.unwrap().get(), Path::new(".git"));
    }

    // project[verify discover.order]
    #[test]
    fn walk_with_a_marker_in_two_ancestors_returns_the_nearer_ancestor() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        let parent = directory(&root, "crates");
        directory(&root, "crates/.git");
        let start = directory(&root, "crates/example");

        let discovery = walk(&start, &[Marker::from(".git")], Fallback::Error).unwrap();

        assert_eq!(discovery.root.get(), parent);
    }

    // project[verify discover.markers.error.outside]
    #[test]
    fn walk_with_a_marker_that_names_no_entry_returns_an_error() {
        let root = tempfile::tempdir().unwrap();

        let error = walk(root.path(), &[Marker::from(".")], Fallback::Error).unwrap_err();

        assert!(matches!(error, DiscoverProjectError::OutsideMarker { .. }));
    }

    // project[verify discover.markers.error.outside]
    #[test]
    fn walk_with_an_absolute_marker_returns_an_error() {
        let root = tempfile::tempdir().unwrap();

        let error = walk(root.path(), &[Marker::from("/etc")], Fallback::Error).unwrap_err();

        assert!(matches!(error, DiscoverProjectError::OutsideMarker { .. }));
    }

    // project[verify discover.precedence]
    #[test]
    fn walk_with_markers_in_the_start_and_an_ancestor_reports_the_start() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        let start = directory(&root, "crates/example");
        directory(&root, "crates/example/.git");

        let discovery = walk(&start, &[Marker::from(".git")], Fallback::Error).unwrap();

        assert_eq!(discovery.root.get(), start);
    }

    // project[verify discover.markers.walk]
    #[test]
    fn walk_with_the_second_marker_in_the_start_returns_the_start() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        let start = directory(&root, "crates/example");
        file(&root, "crates/example/Cargo.toml");

        let discovery = walk(
            &start,
            &[Marker::from(".git"), Marker::from("Cargo.toml")],
            Fallback::Error,
        )
        .unwrap();

        assert_eq!(discovery.root.get(), start);
    }

    // project[verify discover.markers.order]
    #[test]
    fn walk_with_two_markers_in_the_start_returns_the_first() {
        let root = tempfile::tempdir().unwrap();
        directory(&root, ".git");
        file(&root, "Cargo.toml");

        let discovery = walk(
            root.path(),
            &[Marker::from(".git"), Marker::from("Cargo.toml")],
            Fallback::Error,
        )
        .unwrap();

        assert_eq!(discovery.marker.unwrap().get(), Path::new(".git"));
    }

    // project[verify discover.fallback]
    #[test]
    fn walk_without_a_match_and_the_fallback_returns_no_marker() {
        let root = tempfile::tempdir().unwrap();

        let discovery = walk(root.path(), &[Marker::from(ABSENT)], Fallback::Start).unwrap();

        assert!(discovery.marker.is_none());
    }

    // project[verify discover.fallback]
    #[test]
    fn walk_without_a_match_and_the_fallback_returns_the_start() {
        let root = tempfile::tempdir().unwrap();

        let discovery = walk(root.path(), &[Marker::from(ABSENT)], Fallback::Start).unwrap();

        assert_eq!(discovery.root.get(), root.path());
    }

    // project[verify discover.error.missing.message]
    #[test]
    fn walk_without_a_match_names_the_start_and_the_markers() {
        let root = tempfile::tempdir().unwrap();

        let error = walk(root.path(), &[Marker::from(ABSENT)], Fallback::Error).unwrap_err();

        assert_eq!(
            error.to_string(),
            format!(
                "no project exists at or above `{}`, because no directory holds any of these markers: `{ABSENT}`",
                root.path().display()
            )
        );
    }

    // project[verify discover.error.missing]
    #[test]
    fn walk_without_a_match_returns_an_error() {
        let root = tempfile::tempdir().unwrap();

        let error = walk(root.path(), &[Marker::from(ABSENT)], Fallback::Error).unwrap_err();

        assert!(matches!(error, DiscoverProjectError::MissingProject { .. }));
    }
}