aboutsummaryrefslogtreecommitdiff
path: root/bdep/new.cxx
blob: 3e7f29556c5b495ed9731f7de4e58be39c5650dc (plain)
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
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
// file      : bdep/new.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <bdep/new.hxx>

#include <map>
#include <algorithm> // replace()

#include <libbutl/regex.mxx>
#include <libbutl/command.mxx>
#include <libbutl/project-name.mxx>

#include <bdep/git.hxx>
#include <bdep/project.hxx>
#include <bdep/project-author.hxx>
#include <bdep/database.hxx>
#include <bdep/diagnostics.hxx>

#include <bdep/init.hxx>
#include <bdep/config.hxx>

using namespace std;
using namespace butl;

namespace bdep
{
  // License id to full name map.
  //
  static const map<string, string, icase_compare_string> licenses = {
    {"MIT",               "MIT License"                            },
    {"BSD2",              "Simplified 2-clause BSD License"        },
    {"BSD3",              "New 3-clause BSD License"               },
    {"BSD4",              "Original 4-clause BSD License"          },
    {"GPLv2",             "GNU General Public License v2.0"        },
    {"GPLv3",             "GNU General Public License v3.0"        },
    {"LGPLv2",            "GNU Lesser General Public License v2.0" },
    {"LGPLv2.1",          "GNU Lesser General Public License v2.1" },
    {"LGPLv3",            "GNU Lesser General Public License v3.0" },
    {"AGPLv2",            "Affero General Public License v2.0"     },
    {"AGPLv3",            "GNU Affero General Public License v3.0" },
    {"ASLv1",             "Apache License v1.0"                    },
    {"ASLv1.1",           "Apache License v1.1"                    },
    {"ASLv2",             "Apache License v2.0"                    },
    {"MPLv2",             "Mozilla Public License v2.0"            },

    // Note: entries with empty full name are here to get canonical case.
    //
    {"public domain" ,    ""                                       },
    {"available source",  "Not free software/open source"          },
    {"proprietary",       ""                                       },
    {"TODO",              "License is not yet decided"             }};


  // Extract a license id from a license file returning an empty string if
  // it doesn't match any known license file signatures.
  //
  static string
  extract_license (const path& f)
  {
    // The overall plan is to read the license heading and then try to match
    // it against a bunch of regular expression.
    //
    // Some license headings are spread over multiple lines but all the files
    // that we have seen so far separate the heading from the license body
    // with a blank line, for example:
    //
    //                       Apache License
    //                   Version 2.0, January 2004
    //                http://www.apache.org/licenses/
    //
    //   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    //   ....
    //
    // So what we are going to do is combine all the lines (trimmed and
    // separated with spaces) until the blank and run our regular expressions
    // on that. Note that it's possible we will end up with some non-heading
    // junk, as in the case of MPL:
    //
    //   Mozilla Public License Version 2.0
    //   ==================================
    //
    //   1. Definitions
    //   ...
    //
    string h;
    try
    {
      ifdstream is (f, ifdstream::badbit);

      for (string l; !eof (getline (is, l)); )
      {
        if (trim (l).empty ())
          break;

        if (!h.empty ())
          h += ' ';

        h += l;
      }
    }
    catch (const io_error& e)
    {
      fail << "unable to read " << f << ": " << e << endf;
    }

    if (h.empty ())
      return "";

    // We do case-insensitive first-only match ignoring the unmatched parts.
    //
    string r;
    auto test = [&h, &r] (const string& e, const string& f) -> bool
    {
      regex re (e, regex::ECMAScript | regex::icase);

      pair<string, bool> p (
        regex_replace_search (h,
                              re,
                              f,
                              regex_constants::format_first_only |
                              regex_constants::format_no_copy));

      if (p.second)
      {
        assert (!p.first.empty ());
        r = move (p.first);
      }

      return p.second;
    };

    // Note that some licenses (like ASL, MPL) always spell the minor verison,
    // even if it is there (unlike the GNU licenses). So for them we need to
    // ignore the zero minor component.
    //
    (test ("MIT License",                                         "MIT")     ||
     test ("BSD ([1234])-Clause License",                         "BSD$1")   ||
     test ("Apache License Version ([0-9]+(\\.[1-9])?)",          "ASLv$1")  ||
     test ("Mozilla Public License Version ([0-9]+(\\.[1-9])?)",  "MPLv$1")  ||
     test ("GNU GENERAL PUBLIC LICENSE Version ([0-9.]+)",        "GPLv$1")  ||
     test ("GNU LESSER GENERAL PUBLIC LICENSE Version ([0-9.]+)", "LGPLv$1") ||
     test ("GNU AFFERO GENERAL PUBLIC LICENSE Version ([0-9.]+)", "AGPLv$1") ||
     test ("public domain",                                 "public domain"));

    return r;
  }

  // Extract a summary line from a README.md file returning an empty string if
  // unable to. The second argument is the project name.
  //
  static string
  extract_summary (const path& f, const string& n)
  {
    // README.md created by popular hosting services (GitHub, GitLab) have the
    // following format (give or take a few blank lines in between):
    //
    // # <name>
    // <summary>
    //
    // Of course, the file could have been tweaked. In particular, one popular
    // alternative arrangement looks like this:
    //
    // # <name> - <summary>
    //
    // Let's start simple by only support the first version and maybe
    // extend/complicate things later.
    //
    try
    {
      ifdstream is (f, ifdstream::badbit);

      string l;
      auto next = [&is, &l] () -> bool
      {
        while (!eof (getline (is, l)) && trim (l).empty ())
          ;
        return !l.empty ();
      };

      if (next ())
      {
        if (icasecmp (l, "# " + n) == 0)
        {
          if (next ())
          {
            // Potential improvements:
            //
            // - Strip trailing period, if any.
            // - Get only the first sentence.
            //
            return l;
          }
        }
      }

      return "";
    }
    catch (const io_error& e)
    {
      fail << "unable to read " << f << ": " << e << endf;
    }
  }

  using type = cmd_new_type;
  using lang = cmd_new_lang;
  using vcs  = cmd_new_vcs;

  int
  cmd_new (cmd_new_options&& o, cli::group_scanner& args)
  {
    tracer trace ("new");

    // Validate options.
    //
    bool ca (o.config_add_specified ());
    bool cc (o.config_create_specified ());

    if (o.package () && o.subdirectory ())
      fail << "both --package and --subdirectory specified";

    const char* m (o.package ()      ? "--package"      :
                   o.subdirectory () ? "--subdirectory" : nullptr);

    if (m && o.no_init ())
      fail << "both --no-init and " << m << " specified";

    if (const char* n = (o.no_init () ? "--no-init" :
                         m            ? m           : nullptr))
    {
      if (ca) fail << "both " << n << " and --config-add specified";
      if (cc) fail << "both " << n << " and --config-create specified";
    }

    if (o.directory_specified () && !m)
      fail << "--directory|-d only valid with --package or --subdirectory";

    if (const char* n = cmd_config_validate_add (o))
    {
      if (!ca && !cc)
        fail << n << " specified without --config-(add|create)";

      if (o.existing () && !cc)
        fail << "--existing|-e specified without --config-create";

      if (o.wipe () && !cc)
        fail << "--wipe specified without --config-create";
    }

    // Validate language options.
    //
    const lang& l (o.lang ());

    switch (l)
    {
    case lang::c:
      {
        break;
      }
    case lang::cxx:
      {
        auto& o (l.cxx_opt);

        if (o.cpp () && o.extension_specified ())
          fail << "'extension' and 'cpp' are mutually exclusive c++ options";

        // Verify that none of the extensions are specified as empty, except
        // for hxx.
        //
        auto empty_ext = [] (const string& v, const char* o)
        {
          if (v.empty () || (v.size () == 1 && v[0] == '.'))
            fail << "empty extension specified with '" << o << "' c++ option";
        };

        if (o.extension_specified ()) empty_ext (o.extension (), "extension");

        if (o.cxx_specified ()) empty_ext (o.cxx (), "cxx");
        if (o.ixx_specified ()) empty_ext (o.ixx (), "ixx");
        if (o.txx_specified ()) empty_ext (o.txx (), "txx");
        if (o.mxx_specified ()) empty_ext (o.mxx (), "mxx");

        break;
      }
    }

    // Validate type options.
    //
    const type& t (o.type ());

    // For a library source subdirectory (--subdirectory) we don't generate
    // the export stub, integration tests (because there is no export stub),
    // or the version header (because the project name used in the .in file
    // will most likely be wrong). All this seems reasonable for what this
    // mode is expected to be used ("end-product" kind of projects).
    //
    bool readme  (false); // !no-readme
    bool altn    (false); // alt-naming
    bool itest   (false); // !no-tests
    bool utest   (false); // unit-tests
    bool install (false); // !no-install
    bool ver     (false); // !no-version

    string license;
    bool   license_o (false);
    {
      bool pkg (o.package ());
      bool sub (o.subdirectory ());

      switch (t)
      {
      case type::exe:
        {
          readme  = !t.exe_opt.no_readme ()  && !sub;
          altn    =  t.exe_opt.alt_naming ();
          itest   = !t.exe_opt.no_tests ();
          utest   =  t.exe_opt.unit_tests ();
          install = !t.exe_opt.no_install ();

          if (!sub)
          {
            license   = t.exe_opt.license ();
            license_o = t.exe_opt.license_specified ();
          }
          break;
        }
      case type::lib:
        {
          readme  = !t.lib_opt.no_readme ()  && !sub;
          altn    =  t.lib_opt.alt_naming ();
          itest   = !t.lib_opt.no_tests ()   && !sub;
          utest   =  t.lib_opt.unit_tests ();
          install = !t.lib_opt.no_install ();
          ver     = !t.lib_opt.no_version () && !sub;

          if (!sub)
          {
            license   = t.lib_opt.license ();
            license_o = t.lib_opt.license_specified ();
          }
          break;
        }
      case type::bare:
        {
          if (sub)
            fail << "cannot create bare source subdirectory";

          readme  = !t.bare_opt.no_readme ();
          altn    =  t.bare_opt.alt_naming ();
          itest   = !t.bare_opt.no_tests ();
          install = !t.bare_opt.no_install ();

          if (!sub)
          {
            license   = t.bare_opt.license ();
            license_o = t.bare_opt.license_specified ();
          }
          break;
        }
      case type::empty:
        {
          if (const char* w = (sub ? "source subdirectory" :
                               pkg ? "package"             : nullptr))
            fail << "cannot create empty " << w;

          readme = !t.empty_opt.no_readme ();
          break;
        }
      }

      // @@ TODO: move into the lib case once binless is a project type
      //    suboption.
      //
      if (l == lang::cxx && l.cxx_opt.binless () && t != type::lib)
        fail << "'binless' is only valid for libraries";
    }

    // Standard/alternative build file/directory naming scheme.
    //
    const dir_path build_dir      (altn ? "build2"     : "build");
    const string   build_ext      (altn ? "build2"     : "build");
    const path     buildfile_file (altn ? "build2file" : "buildfile");

    // Validate vcs options.
    //
    vcs  vc   (o.vcs ());
    bool vc_o (o.vcs_specified ());

    // Check if we have the argument (name). If not, then we use the specified
    // output or current working directory name.
    //
    string a;
    if (args.more ())
      a = args.next ();
    else
    {
      if (!o.output_dir_specified ())
      {
        // Reduce this case (for the logic that follows) to as-if the current
        // working directory was specified as the output directory.
        //
        o.output_dir (path::current_directory ());
        o.output_dir_specified (true);
      }

      a = o.output_dir ().leaf ().string ();
    }

    // If the project type is not empty then the project name is also a package
    // name. But even if it is empty, verify it is a valid package name since
    // it will most likely end up in the 'project' manifest value.
    //
    package_name pkgn;

    try
    {
      pkgn = package_name (move (a));
    }
    catch (const invalid_argument& e)
    {
      fail << "invalid " << (t == type::empty ? "project" : "package")
           << " name: " << e;
    }

    // Full package name vs base name (e.g., libhello in libhello.bash) vs the
    // name stem (e.g, hello in libhello).
    //
    // We use the full name in the manifest and the top-level directory, the
    // base name for inner filesystem directories and preprocessor macros,
    // while the (sanitized) stem for modules, namespaces, etc.
    //
    const string&   n (pkgn.string ());   // Full name.
    const string&   b (pkgn.base ());     // Base name.
    const string&   v (pkgn.variable ()); // Variable name.
    string          s (b);                // Name stem.
    {
      // Warn about the lib prefix unless we are creating a source
      // subdirectory, in which case the project is probably not meant to be a
      // package anyway.
      //
      bool w (!o.subdirectory ());

      switch (t)
      {
      case type::exe:
        {
          if (w && s.compare (0, 3, "lib") == 0)
            warn << "executable name starts with 'lib'";

          break;
        }
      case type::lib:
        {
          if (s.compare (0, 3, "lib") == 0)
          {
            s.erase (0, 3);

            if (w && s.empty ())
              fail << "empty library name stem in '" << b << "'";
          }
          else if (w)
            warn << "library name does not start with 'lib'";

          break;
        }
      case type::bare:
      case type::empty:
        break;
      }
    }

    // Sanitize the stem to be a valid language identifier.
    //
    string id;
    switch (l)
    {
    case lang::c:
    case lang::cxx:
      {
        id = sanitize_identifier (const_cast<const string&> (s));
        break;
      }
    }

    dir_path prj;           // Project.
    dir_path out;           // Project/package/subdirectory output directory.
    optional<dir_path> pkg; // Package relative to its project root.
    optional<dir_path> sub; // Source subdirectory relative to its
                            // project/package root.
    {
      // Figure the final output and tentative project directories.
      //
      if (o.package () || o.subdirectory ())
      {
        if (o.directory_specified ())
          prj = normalize (o.directory (), "project");
        else
          prj = current_directory ();

        out = o.output_dir_specified () ? o.output_dir () : prj / dir_path (n);
        normalize (out, "output");
      }
      else
      {
        out = o.output_dir_specified () ? o.output_dir () : dir_path (n);
        normalize (out, "output");
        prj = out;
      }

      // Get the actual project/package information as "seen" from the output
      // directory.
      //
      project_package pp (
        find_project_package (out, true /* ignore_not_found */));

      // Finalize the tentative project directory and do some sanity checks
      // (nested packages, etc; you would be surprised what people come up
      // with).
      //
      if (o.package ())
      {
        if (!o.no_checks ())
        {
          if (pp.project.empty ())
            warn << prj << " does not look like a project directory";
          else
          {
            if (pp.package)
              fail << "package directory " << out << " is inside another "
                   << "package directory " << pp.project / *pp.package <<
                info << "nested packages are not allowed";
          }
        }

        if (!pp.project.empty ())
        {
          if (prj != pp.project)
            prj = move (pp.project);
        }

        if (!out.sub (prj))
          fail << "package directory " << out << " is not a subdirectory of "
               << "project directory " << prj;

        pkg = out.leaf (prj);
      }
      else if (o.subdirectory ())
      {
        if (!o.no_checks ())
        {
          if (pp.project.empty () || !pp.package)
            warn << prj << " does not look like a package directory";
        }

        // Note: our prj should actually be the package (i.e., the build
        // system project root).
        //
        if (!pp.project.empty ())
        {
          dir_path pkg (move (pp.project));

          if (pp.package)
            pkg /= *pp.package;

          if (prj != pkg)
            prj = move (pkg);
        }

        if (!out.sub (prj))
          fail << "source subdirectory " << out << " is not a subdirectory of "
               << "package directory " << prj;

        // We use this information to form the include directories. The idea
        // is that if the user places the subdirectory somewhere deeper (say
        // into core/libfoo/), then we want the include directives to contain
        // the prefix from the project root (so it will be <core/libfoo/...>)
        // since all our buildfiles are hardwired with -I$src_root.
        //
        // Note also that a crafty user can adjust the prefix by picking the
        // appropriate --directory|-d (i.e., it can point somewhere deeper
        // than the project root). They will need to adjust their buildfiles,
        // however (or we could get smarter by finding the actual package root
        // and adding the difference to -I). Also, some other things, such as
        // the namespace, currently do not contain the prefix.
        //
        sub = out.leaf (prj);
      }
      else
      {
        if (!o.no_checks ())
        {
          if (!pp.project.empty ())
            fail << "project directory " << out << " is inside another "
                 << "project directory " << pp.project <<
              info << "nested projects are not allowed";
        }
      }

      // Create the output directory if it doesn't exit. Note that we are
      // ok with it already existing and containing some things; see below
      // for details.
      //
      if (!exists (out))
        mk_p (out);
    }

    // Run pre/post hooks.
    //
    auto run_hooks = [&prj, &sub, &pkg, &n, &b, &s, &t, &l, &vc, &out]
                     (const strings& hooks, const char* what)
    {
      command_substitution_map subs;
      strings                  vars;

      auto add_var = [&subs, &vars] (string name, string value)
      {
        vars.push_back ("BDEP_NEW_"                              +
                        ucase (const_cast<const string&> (name)) +
                        '='                                      +
                        value);

        subs[move (name)] = move (value);
      };

      add_var ("mode", sub ? "subdirectory" : pkg ? "package" : "project");
      add_var ("name", n);
      add_var ("base", b);
      add_var ("stem", s);
      add_var ("type", t.string ());
      add_var ("lang", l.string (true /* lower */));
      add_var ("vcs",  vc.string ());
      add_var ("root", prj.string ());

      // Note: out directory path is absolute and normalized.
      //
      optional<process_env> env (process_env (process_path (), out, vars));

      for (const string& cmd: hooks)
      {
        try
        {
          process_exit e (command_run (cmd,
                                       env,
                                       subs,
                                       '@',
                                       [] (const char* const args[], size_t n)
                                       {
                                         if (verb >= 2)
                                         {
                                           print_process (args, n);
                                         }
                                       }));

          if (!e)
          {
            if (e.normal ())
              throw failed (); // Assume the command issued diagnostics.

            fail << what << " hook '" << cmd << "' " << e;
          }
        }
        catch (const invalid_argument& e)
        {
          fail << "invalid " << what << " hook '" << cmd << "': " << e;
        }
        catch (const io_error& e)
        {
          fail << "unable to execute " << what << " hook '" << cmd << "': "
               << e;
        }
        // Also handles process_error exception (derived from system_error).
        //
        catch (const system_error& e)
        {
          fail << "unable to execute " << what << " hook '" << cmd << "': "
               << e;
        }
      }
    };

    // Run pre hooks.
    //
    if (o.pre_hook_specified ())
      run_hooks (o.pre_hook (), "pre");

    // Source directory relative to package root.
    //
    const dir_path& d (sub ? *sub : dir_path (b));

    // Check if certain things already exist.
    //
    optional<vcs::vcs_type> vc_e;      // Detected version control system.
    optional<string>        readme_e;  // Extracted summary line.
    optional<string>        license_e; // Extracted license id.
    {
      if (!sub)
      {
        if (!pkg)
        {
          if (git_repository (out))
            vc_e = vcs::git;
        }

        // @@ What if in the --package mode these files already exist but are
        //    not in the package but in the project root? This also goes back
        //    to an existing desire to somehow reuse project README.md/LICENSE
        //    in its packages (currently a reference from manifest out of
        //    package is illegal). Maybe via symlinks? We could probably even
        //    automatically find and symlink them?
        //
        path f;

        // README.md
        //
        if (exists ((f = out / "README.md")))
        {
          readme_e = extract_summary (f, n);

          if (readme_e->empty ())
            warn << "unable to extract project summary from " << f <<
              info << "using generic summary in manifest";
        }

        // LICENSE
        //
        if (exists ((f = out / "LICENSE")))
        {
          license_e = extract_license (f);

          if (license_e->empty () && !license_o)
            fail << "unable to guess project license from " << f <<
              info << "use license --type|-t sub-option to specify explicitly";
        }
      }

      // Merge option and existing values verifying that what already exists
      // does not conflict with what's requested.
      //
      if (vc_e)
      {
        if (!vc_o)
          vc = *vc_e;
        else if (*vc_e != vc)
          fail << "existing version control system does not match requested" <<
            info << "existing: " << *vc_e <<
            info << "requested: " << vc;
      }

      if (readme_e)
      {
        if (!readme)
          fail << "no-readme sub-option specified but README already exists";
      }

      if (license_e)
      {
        if (!license_o)
          license = *license_e;
        else if (icasecmp (*license_e, license) != 0)
          fail << "extracted license does not match requested" <<
            info << "extracted: " << *license_e <<
            info << "requested: " << license;
      }
    }

    // Initialize the version control system. Do it before writing anything
    // ourselves in case it fails. Also, the email discovery may do the VCS
    // detection.
    //
    if (!vc_e && !pkg && !sub)
    {
      switch (vc)
      {
      case vcs::git:  run ("git", "init", "-q", out); break;
      case vcs::none:                                 break;
      }
    }

    // We support creating a project that already contains some files provided
    // none of them conflict with what we are trying to create (with a few
    // exceptions such as LICENSE and README.md that are handled explicitly
    // plus packages.manifest to which we append last).
    //
    // While we could verify at the outset that none of the files we will be
    // creating exist, that would be quite unwieldy. So instead we are going
    // to fail as we go along but, in this case, also cleanup any files that
    // we have already created.
    //
    vector<auto_rmfile> rms;
    for (path cf;;) // Breakout loop with the current file being written.
    try
    {
      ofdstream os;
      auto open = [&cf, &os, &rms] (path f)
      {
        try
        {
          os.open (f, (fdopen_mode::out    |
                       fdopen_mode::create |
                       fdopen_mode::exclusive));
          cf = f;
          rms.push_back (auto_rmfile (move (f)));
        }
        catch (const io_error& e)
        {
          fail << "unable to create " << f << ": " << e;
        }
      };

      // .gitignore
      //
      // See also tests/.gitignore below.
      //
      if (!sub)
      {
        if (vc == vcs::git)
        {
          // Use POSIX directory separators here.
          //
          open (out / ".gitignore");
          if (!pkg)
            os << bdep_dir.posix_representation ()                     << endl
               <<                                                         endl
               << "# Local default options files."                     << endl
               << "#"                                                  << endl
               << ".build2/local/"                                     << endl
               <<                                                         endl;
          if (t != type::empty)
            os << "# Compiler/linker output."                          << endl
               << "#"                                                  << endl
               << "*.d"                                                << endl
               << "*.t"                                                << endl
               << "*.i"                                                << endl
               << "*.ii"                                               << endl
               << "*.o"                                                << endl
               << "*.obj"                                              << endl
               << "*.so"                                               << endl
               << "*.dll"                                              << endl
               << "*.a"                                                << endl
               << "*.lib"                                              << endl
               << "*.exp"                                              << endl
               << "*.pdb"                                              << endl
               << "*.ilk"                                              << endl
               << "*.exe"                                              << endl
               << "*.exe.dlls/"                                        << endl
               << "*.exe.manifest"                                     << endl
               << "*.pc"                                               << endl;
          os.close ();
        }
      }

      // repositories.manifest
      //
      if (!pkg && !sub)
      {
        open (out / "repositories.manifest");
        os << ": 1"                                                    << endl
           << "summary: " << n << " project repository"                << endl
           <<                                                             endl
           << "#:"                                                     << endl
           << "#role: prerequisite"                                    << endl
           << "#location: https://pkg.cppget.org/1/stable"             << endl
           << "#trust: ..."                                            << endl
           <<                                                             endl
           << "#:"                                                     << endl
           << "#role: prerequisite"                                    << endl
           << "#location: https://git.build2.org/hello/libhello.git"   << endl;
        os.close ();
      }

      // README.md
      //
      if (!readme_e && readme)
      {
        open (out / "README.md");
        switch (t)
        {
        case type::exe:
        case type::lib:
          {
            // @@ Maybe we should generate a "Hello, World" description and
            //    usage example as a guide, at least for a library?

            os << "# " << n                                            << endl
               <<                                                         endl
               << l << " " << t                                        << endl;
            break;
          }
        case type::bare:
        case type::empty:
          {
            os << "# " << n                                            << endl;
            break;
          }
        }
        os.close ();
      }

      if (t == type::empty)
        break; // Done.

      // manifest
      //
      if (!sub)
      {
        // Project name.
        //
        // If this is a package in a project (--package mode), then use the
        // project directory name as the project name. Otherwise, the project
        // name is the same as the package and is therefore omitted.
        //
        // In case of a library, we could have used either the full name or
        // the stem without the lib prefix. And it could go either way: if a
        // library is (likely to be) accompanied by an executable (or some
        // other extra packages), then its project should probably be the
        // stem. Otherwise, if it is a standalone library, then the full
        // library name is probably preferred. The stem also has another
        // problem: it could be an invalid project name. So using the full
        // name seems like a simpler and more robust approach.
        //
        // There was also an idea to warn if the project name ends with a
        // digit (think libfoo and libfoo2).
        //
        optional<project_name> pn;
        if (pkg)
        {
          string p (prj.leaf ().string ());

          if (p != n) // Omit if the same as the package name.
          {
            try
            {
              pn = project_name (move (p));
            }
            catch (const invalid_argument& e)
            {
              warn << "project name '" << p << "' is invalid: " << e <<
                info << "leaving the 'project' manifest value empty";

              pn = project_name ();
            }
          }
        }

        // Project email.
        //
        string pe;
        {
          optional<string> r (find_project_author_email (prj));
          pe = r ? move (*r) : "you@example.org";
        }

        // Full license name.
        //
        string ln;
        {
          auto i (licenses.find (license));
          if (i != licenses.end ())
          {
            ln = i->second;
            license = i->first; // Use canonical case.
          }
          else
          {
            if (icasecmp (license, "BSD") == 0)
              warn << "BSD license name is ambiguous" <<
                info << "consider using BSD3 for \"New 3-clause BSD License\"";
          }
        }

        open (out / "manifest");
        os << ": 1"                                                    << endl
           << "name: " << n                                            << endl
           << "version: 0.1.0-a.0.z"                                   << endl;
        if (pn)
          os << "project: " << *pn                                     << endl;
        if (readme_e && !readme_e->empty ())
          os << "summary: " << *readme_e                               << endl;
        else
          os << "summary: " << s << " " << l << " " << t               << endl;
        if (ln.empty ())
          os << "license: " << license                                 << endl;
        else
          os << "license: " << license << " ; " << ln << "."           << endl;
        if (readme)
          os << "description-file: README.md"                          << endl;
        os << "url: https://example.org/" << (pn ? pn->string () : n)  << endl
           << "email: " << pe                                          << endl
           << "depends: * build2 >= 0.12.0"                            << endl
           << "depends: * bpkg >= 0.12.0"                              << endl
           << "#depends: libhello ^1.0.0"                              << endl;
        os.close ();
      }

      string m;  // Language module.
      string x;  // Source target type.
      string h;  // Header target type.
      string hs; // All header-like target types.
      string xe; // Source file extension (including leading dot).
      string he; // Header file extension (including leading dot unless empty).

      // @@ In a modular project, mxx is probably more like hxx/cxx rather
      //    than ixx/txx.
      //
      optional<string> ie; // Inline file extension.
      optional<string> te; // Template file extension.
      optional<string> me; // Module interface extension.

      switch (l)
      {
      case lang::c:
        {
          m  = "c";
          x  = "c";
          h  = "h";
          hs = "h";
          xe = ".c";
          he = ".h";
          break;
        }
      case lang::cxx:
        {
          const auto& opt (l.cxx_opt);

          m  = "cxx";
          x  = "cxx";
          h  = "hxx";
          hs = "hxx";

          // Return the extension (v), if specified (s), derive the extension
          // from the pattern and type (t), or return the default (d), if
          // specified.
          //
          auto ext = [&opt] (bool s,
                             const string& v,
                             optional<char> t,
                             const char* d = nullptr) -> optional<string>
          {
            optional<string> r;

            if (s)
              r = v;
            else if (t && (opt.extension_specified () || opt.cpp ()))
            {
              string p (opt.extension_specified () ? opt.extension () :
                        opt.cpp ()                 ? "?pp"            : "");

              replace (p.begin (), p.end (), '?', *t);
              r = move (p);
            }
            else if (d != nullptr)
              r = d;

            // Add leading dot if absent.
            //
            if (r && !r->empty () && r->front () != '.')
              r = '.' + *r;

            return r;
          };

          xe = *ext (opt.cxx_specified (), opt.cxx (), 'c', "cxx");
          he = *ext (opt.hxx_specified (), opt.hxx (), 'h', "hxx");

          // We only want default .ixx/.txx/.mxx if the user didn't specify
          // any of the extension-related options explicitly.
          //
          bool d (!opt.cxx_specified () &&
                  !opt.hxx_specified () &&
                  !opt.ixx_specified () &&
                  !opt.txx_specified () &&
                  !opt.mxx_specified ());

          ie = ext (opt.ixx_specified (), opt.ixx (), 'i', d ? "ixx" : nullptr);
          te = ext (opt.txx_specified (), opt.txx (), 't', d ? "txx" : nullptr);

          // For now only include mxx in buildfiles if its extension was
          // explicitly specified with mxx=.
          //
          me = ext (opt.mxx_specified (), opt.mxx (), nullopt, nullptr);

          if (ie) hs += " ixx";
          if (te) hs += " txx";
          if (me) hs += " mxx";

          break;
        }
      }

      // Return the pointer to the extension suffix after the leading dot or
      // to the extension beginning if it is empty.
      //
      auto pure_ext = [] (const string& e)
      {
        assert (e.empty () || e[0] == '.');
        return e.c_str () + (e.empty () ? 0 : 1);
      };

      // build/
      //
      dir_path bd;
      if (!sub)
      {
        bd = out / build_dir;
        mk (bd);

        // build/bootstrap.build
        //
        open (bd / "bootstrap." + build_ext);
        os << "project = " << n                                        << endl;
        if (o.no_amalgamation ())
          os << "amalgamation = # Disabled."                           << endl;
        os <<                                                             endl
           << "using version"                                          << endl
           << "using config"                                           << endl;
        if (itest || utest)
          os << "using test"                                           << endl;
        if (install)
          os << "using install"                                        << endl;
        os << "using dist"                                             << endl;
        os.close ();

        // build/root.build
        //
        // Note: see also tests/build/root.build below.
        //
        open (bd / "root." + build_ext);

        switch (l)
        {
        case lang::c:
          {
            // @@ TODO: 'latest' in c.std.
            //
            // << "c.std = latest"                                     << endl
            // <<                                                         endl
            os << "using c"                                            << endl
               <<                                                         endl
               << "h{*}: extension = h"                                << endl
               << "c{*}: extension = c"                                << endl;
            break;
          }
        case lang::cxx:
          {
            os << "cxx.std = latest"                                   << endl
               <<                                                         endl
               << "using cxx"                                          << endl
               <<                                                         endl;

            if (me) os << "mxx{*}: extension = " << pure_ext (*me)     << endl;
            os         << "hxx{*}: extension = " << pure_ext (he)      << endl;
            if (ie) os << "ixx{*}: extension = " << pure_ext (*ie)     << endl;
            if (te) os << "txx{*}: extension = " << pure_ext (*te)     << endl;
            os         << "cxx{*}: extension = " << pure_ext (xe)      << endl;

            break;
          }
        }

        if ((itest || utest) && !m.empty ())
          os <<                                                           endl
             << "# The test target for cross-testing (running tests under Wine, etc)." << endl
             << "#"                                                    << endl
             << "test.target = $" << m << ".target"                    << endl;

        os.close ();

        // build/.gitignore
        //
        if (vc == vcs::git)
        {
          open (bd / ".gitignore");
          os << "config." << build_ext                                 << endl
             << "root/"                                                << endl
             << "bootstrap/"                                           << endl;
          os.close ();
        }
      }

      // buildfile
      //
      if (!sub)
      {
        open (out / buildfile_file);

        os << "./: {*/ -" << build_dir.posix_representation () << "}"  <<
          (readme ? " doc{README.md}" : "") << " manifest"             << endl;

        if (itest && install && t == type::lib) // Have tests/ subproject.
          os <<                                                           endl
             << "# Don't install tests."                               << endl
             << "#"                                                    << endl
             << "tests/: install = false"                              << endl;
        os.close ();
      }

      if (t == type::bare)
        break; // Done

      // <base>/ (source subdirectory).
      //
      const dir_path& sd (sub ? out : out / d);
      mk (sd);

      switch (t)
      {
      case type::exe:
        {
          switch (l)
          {
          case lang::c:
            {
              // <base>/<stem>.c
              //
              open (sd / s + ".c");
              os << "#include <stdio.h>"                               << endl
                 <<                                                       endl
                 << "int main (int argc, char *argv[])"                << endl
                 << "{"                                                << endl
                 << "  if (argc < 2)"                                  << endl
                 << "  {"                                              << endl
                 << "    fprintf (stderr, \"error: missing name\\n\");"<< endl
                 << "    return 1;"                                    << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  printf (\"Hello, %s!\\n\", argv[1]);"           << endl
                 << "  return 0;"                                      << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
          case lang::cxx:
            {
              // <base>/<stem>.<cxx-ext>
              //
              open (sd / s + xe);
              os << "#include <iostream>"                              << endl
                 <<                                                       endl
                 << "int main (int argc, char* argv[])"                << endl
                 << "{"                                                << endl
                 << "  using namespace std;"                           << endl
                 <<                                                       endl
                 << "  if (argc < 2)"                                  << endl
                 << "  {"                                              << endl
                 << "    cerr << \"error: missing name\" << endl;"     << endl
                 << "    return 1;"                                    << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  cout << \"Hello, \" << argv[1] << '!' << endl;" << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
          }

          // <base>/buildfile
          //
          open (sd / buildfile_file);
          os << "libs ="                                               << endl
             << "#import libs += libhello%lib{hello}"                  << endl
             <<                                                           endl;

          if (!utest)
            os << "exe{" << s << "}: "                                 <<
              "{" << hs << ' ' << x << "}{**} "                        <<
              "$libs"                                                  <<
              (itest ? " testscript" : "")                             << endl;
          else
          {
            os << "./: exe{" << s << "}: libue{" << s << "}: "         <<
              "{" << hs << ' ' << x << "}{** -**.test...} $libs"       << endl;

            if (itest)
              os << "exe{" << s << "}: testscript"                     << endl;

            os <<                                                         endl
               << "# Unit tests."                                      << endl
               << "#"                                                  << endl;

            if (install)
              os << "exe{*.test}:"                                     << endl
                 << "{"                                                << endl
                 << "  test = true"                                    << endl
                 << "  install = false"                                << endl
                 << "}"                                                << endl;
            else
              os << "exe{*.test}: test = true"                         << endl;

            os <<                                                         endl
               << "for t: " << x << "{**.test...}"                     << endl
               << "{"                                                  << endl
               << "  d = $directory($t)"                               << endl
               << "  n = $name($t)..."                                 << endl
               <<                                                         endl
               << "  ./: $d/exe{$n}: $t $d/{" << hs                    <<
              "}{+$n} $d/testscript{+$n}"                              << endl
               << "  $d/exe{$n}: libue{" << s << "}: bin.whole = false"<< endl
               << "}"                                                  << endl;
          }

          os <<                                                           endl
             << m << ".poptions =+ \"-I$out_root\" \"-I$src_root\""    << endl;
          os.close ();

          // <base>/.gitignore
          //
          if (vc == vcs::git)
          {
            open (sd / ".gitignore");
            os << s                                                    << endl;
            if (utest)
              os << "*.test"                                           << endl;
            if (itest || utest)
              os <<                                                       endl
                 << "# Testscript output directory (can be symlink)."  << endl
                 << "#"                                                << endl;
            if (itest)
              os << "test-" << s                                       << endl;
            if (utest)
              os << "test-*.test"                                      << endl;
            os.close ();
          }

          // <base>/testscript
          //
          if (itest)
          {
            open (sd / "testscript");
            os << ": basics"                                           << endl
               << ":"                                                  << endl
               << "$* 'World' >'Hello, World!'"                        << endl
               <<                                                         endl
               << ": missing-name"                                     << endl
               << ":"                                                  << endl
               << "$* 2>>EOE != 0"                                     << endl
               << "error: missing name"                                << endl
               << "EOE"                                                << endl;
            os.close ();
          }

          // <base>/<stem>.test.*
          //
          if (utest)
          {
            switch (l)
            {
            case lang::c:
              {
                // <base>/<stem>.test.c
                //
                open (sd / s + ".test.c");
                os << "#include <stdio.h>"                             << endl
                   << "#include <assert.h>"                            << endl
                   <<                                                     endl
                   << "int main ()"                                    << endl
                   << "{"                                              << endl
                   << "  return 0;"                                    << endl
                   << "}"                                              << endl;
                os.close ();

                break;
              }
            case lang::cxx:
              {
                // <base>/<stem>.test.<cxx-ext>
                //
                open (sd / s + ".test" + xe);
                os << "#include <cassert>"                             << endl
                   << "#include <iostream>"                            << endl
                   <<                                                     endl
                   << "int main ()"                                    << endl
                   << "{"                                              << endl
                   <<                                                     endl
                   << "}"                                              << endl;
                os.close ();

                break;
              }
            }
          }

          break;
        }
      case type::lib:
        {
          string ip (d.posix_representation ()); // Include prefix.

          // Macro prefix.
          //
          string mp (
            sanitize_identifier (ucase (const_cast<const string&> (ip))));

          // Strip the trailing underscore (produced from slash).
          //
          mp.pop_back ();

          string apih; // API header name.
          string exph; // Export header name (empty if binless).
          string verh; // Version header name.

          switch (l)
          {
          case lang::c:
            {
              apih = s + ".h";
              exph = "export.h";
              verh = ver ? "version.h" : string ();

              // <stem>.h
              //
              open (sd / apih);
              os << "#pragma once"                                     << endl
                 <<                                                       endl
                 << "#include <stdio.h>"                               << endl
                 <<                                                       endl
                 << "#include <" << ip << exph << ">"                  << endl
                 <<                                                       endl
                 << "/* Print a greeting for the specified name into the specified"   << endl
                 << " * stream. On success, return the number of characters printed." << endl
                 << " * On failure, set errno and return a negative value."           << endl
                 << " */"                                                             << endl
                 << mp << "_SYMEXPORT int"                             << endl
                 << "say_hello (FILE *, const char *name);"            << endl;
              os.close ();

              // <stem>.c
              //
              open (sd / s + ".c");
              os << "#include <" << ip << apih << ">"                  << endl
                 <<                                                       endl
                 << "#include <errno.h>"                               << endl
                 <<                                                       endl
                 << "int say_hello (FILE *f, const char* n)"           << endl
                 << "{"                                                << endl
                 << "  if (f == NULL || n == NULL || *n == '\\0')"     << endl
                 << "  {"                                              << endl
                 << "    errno = EINVAL;"                              << endl
                 << "    return -1;"                                   << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  return fprintf (f, \"Hello, %s!\\n\", n);"      << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
          case lang::cxx:
            if (l.cxx_opt.binless ())
            {
              apih = s + he;
              verh = ver ? "version" + he : string ();

              // <stem>[.<hxx-ext>]
              //
              open (sd / apih);
              os << "#pragma once"                                     << endl
                 <<                                                       endl
                 << "#include <string>"                                << endl
                 << "#include <ostream>"                               << endl
                 << "#include <stdexcept>"                             << endl
                 <<                                                       endl
                 << "namespace " << id                                 << endl
                 << "{"                                                << endl
                 << "  // Print a greeting for the specified name into the specified" << endl
                 << "  // stream. Throw std::invalid_argument if the name is empty."  << endl
                 << "  //"                                                            << endl
                 << "  inline void"                                    << endl
                 << "  say_hello (std::ostream& o, const std::string& name)" << endl
                 << "  {"                                              << endl
                 << "    using namespace std;"                         << endl
                 <<                                                       endl
                 << "    if (name.empty ())"                           << endl
                 << "      throw invalid_argument (\"empty name\");"   << endl
                 <<                                                       endl
                 << "    o << \"Hello, \" << name << '!' << endl;"     << endl
                 << "  }"                                              << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
            else
            {
              apih = s + he;
              exph = "export" + he;
              verh = ver ? "version" + he : string ();

              // <stem>[.<hxx-ext>]
              //
              open (sd / apih);
              os << "#pragma once"                                     << endl
                 <<                                                       endl
                 << "#include <iosfwd>"                                << endl
                 << "#include <string>"                                << endl
                 <<                                                       endl
                 << "#include <" << ip << exph << ">"                  << endl
                 <<                                                       endl
                 << "namespace " << id                                 << endl
                 << "{"                                                << endl
                 << "  // Print a greeting for the specified name into the specified" << endl
                 << "  // stream. Throw std::invalid_argument if the name is empty."  << endl
                 << "  //"                                                            << endl
                 << "  " << mp << "_SYMEXPORT void"                    << endl
                 << "  say_hello (std::ostream&, const std::string& name);" << endl
                 << "}"                                                << endl;
              os.close ();

              // <stem>.<cxx-ext>
              //
              open (sd / s + xe);
              os << "#include <" << ip << apih << ">"                  << endl
                 <<                                                       endl
                 << "#include <ostream>"                               << endl
                 << "#include <stdexcept>"                             << endl
                 <<                                                       endl
                 << "using namespace std;"                             << endl
                 <<                                                       endl
                 << "namespace " << id                                 << endl
                 << "{"                                                << endl
                 << "  void say_hello (ostream& o, const string& n)"   << endl
                 << "  {"                                              << endl
                 << "    if (n.empty ())"                              << endl
                 << "      throw invalid_argument (\"empty name\");"   << endl
                 <<                                                       endl
                 << "    o << \"Hello, \" << n << '!' << endl;"        << endl
                 << "  }"                                              << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
          }

          // export.h[??]
          //
          if (!exph.empty ())
          {
            open (sd / exph);
            os << "#pragma once"                                       << endl
               <<                                                         endl;
            if (l == lang::cxx)
            {
              os << "// Normally we don't export class templates (but do complete specializations)," << endl
                 << "// inline functions, and classes with only inline member functions. Exporting"  << endl
                 << "// classes that inherit from non-exported/imported bases (e.g., std::string)"   << endl
                 << "// will end up badly. The only known workarounds are to not inherit or to not"  << endl
                 << "// export. Also, MinGW GCC doesn't like seeing non-exported functions being"    << endl
                 << "// used before their inline definition. The workaround is to reorder code. In"  << endl
                 << "// the end it's all trial and error."                                           << endl
                 <<                                                                                     endl;
            }
            os << "#if defined(" << mp << "_STATIC)         // Using static."    << endl
               << "#  define " << mp << "_SYMEXPORT"                             << endl
               << "#elif defined(" << mp << "_STATIC_BUILD) // Building static." << endl
               << "#  define " << mp << "_SYMEXPORT"                             << endl
               << "#elif defined(" << mp << "_SHARED)       // Using shared."    << endl
               << "#  ifdef _WIN32"                                             << endl
               << "#    define " << mp << "_SYMEXPORT __declspec(dllimport)"     << endl
               << "#  else"                                                     << endl
               << "#    define " << mp << "_SYMEXPORT"                           << endl
               << "#  endif"                                                    << endl
               << "#elif defined(" << mp << "_SHARED_BUILD) // Building shared." << endl
               << "#  ifdef _WIN32"                                             << endl
               << "#    define " << mp << "_SYMEXPORT __declspec(dllexport)"     << endl
               << "#  else"                                                     << endl
               << "#    define " << mp << "_SYMEXPORT"                           << endl
               << "#  endif"                                                    << endl
               << "#else"                                                       << endl
               << "// If none of the above macros are defined, then we assume we are being used"  << endl
               << "// by some third-party build system that cannot/doesn't signal the library"    << endl
               << "// type. Note that this fallback works for both static and shared but in case" << endl
               << "// of shared will be sub-optimal compared to having dllimport."                << endl
               << "//"                                                                            << endl
               << "#  define " << mp << "_SYMEXPORT         // Using static or shared." << endl
               << "#endif"                                                             << endl;
            os.close ();
          }

          // version.h[??].in
          //
          if (ver)
          {
            open (sd / verh + ".in");

            os << "#pragma once"                                       << endl
               <<                                                         endl
               << "// The numeric version format is AAAAABBBBBCCCCCDDDE where:"<< endl
               << "//"                                                 << endl
               << "// AAAAA - major version number"                    << endl
               << "// BBBBB - minor version number"                    << endl
               << "// CCCCC - bugfix version number"                   << endl
               << "// DDD   - alpha / beta (DDD + 500) version number" << endl
               << "// E     - final (0) / snapshot (1)"                << endl
               << "//"                                                 << endl
               << "// When DDDE is not 0, 1 is subtracted from AAAAABBBBBCCCCC. For example:" << endl
               << "//"                                                 << endl
               << "// Version      AAAAABBBBBCCCCCDDDE"                << endl
               << "//"                                                 << endl
               << "// 0.1.0        0000000001000000000"                << endl
               << "// 0.1.2        0000000001000020000"                << endl
               << "// 1.2.3        0000100002000030000"                << endl
               << "// 2.2.0-a.1    0000200001999990010"                << endl
               << "// 3.0.0-b.2    0000299999999995020"                << endl
               << "// 2.2.0-a.1.z  0000200001999990011"                << endl
               << "//"                                                 << endl
               << "#define " << mp << "_VERSION       $" << v << ".version.project_number$ULL" << endl
               << "#define " << mp << "_VERSION_STR   \"$" << v << ".version.project$\""       << endl
               << "#define " << mp << "_VERSION_ID    \"$" << v << ".version.project_id$\""    << endl
               <<                                                                                  endl
               << "#define " << mp << "_VERSION_MAJOR $" << v << ".version.major$" << endl
               << "#define " << mp << "_VERSION_MINOR $" << v << ".version.minor$" << endl
               << "#define " << mp << "_VERSION_PATCH $" << v << ".version.patch$" << endl
               <<                                                                    endl
               << "#define " << mp << "_PRE_RELEASE   $" << v << ".version.pre_release$" << endl
               <<                                                                          endl
               << "#define " << mp << "_SNAPSHOT_SN   $" << v << ".version.snapshot_sn$ULL"<< endl
               << "#define " << mp << "_SNAPSHOT_ID   \"$" << v << ".version.snapshot_id$\"" << endl;
            os.close ();
          }

          bool binless (l == lang::cxx && l.cxx_opt.binless ());

          // buildfile
          //
          open (sd / buildfile_file);
          os << "int_libs = # Interface dependencies."                 << endl
             << "imp_libs = # Implementation dependencies."            << endl
             << "#import imp_libs += libhello%lib{hello}"              << endl
             <<                                                           endl;

          if (!utest)
          {
            os << "lib{" << s << "}: "                                 <<
              "{" << hs << (binless ? "" : ' ' + x) << "}{**";
            if (ver)
              os << " -version} " << h << "{version}";
            else
              os << "}";
            os << " $imp_libs $int_libs"                               << endl;
          }
          else
          {
            if (binless)
            {
              os << "./: lib{" << s << "}: "                           <<
                "{" << hs << "}{** -**.test...";
              if (ver)
                os << " -version} " << h << "{version} \\"             << endl
                   << " ";
              else
                os << "}";
              os << " $imp_libs $int_libs"                             << endl;
            }
            else
            {
              os << "./: lib{" << s << "}: libul{" << s << "}: "       <<
                "{" << hs << ' ' << x << "}{** -**.test...";
              if (ver)
                os << " -version} \\"                                  << endl
                   << "  " << h << "{version}";
              else
                os << "}";
              os << " $imp_libs $int_libs"                             << endl;
            }

            os <<                                                         endl
               << "# Unit tests."                                      << endl
               << "#"                                                  << endl;

            if (install)
              os << "exe{*.test}:"                                     << endl
                 << "{"                                                << endl
                 << "  test = true"                                    << endl
                 << "  install = false"                                << endl
                 << "}"                                                << endl;
            else
              os << "exe{*.test}: test = true"                         << endl;

            os <<                                                         endl
               << "for t: " << x << "{**.test...}"                     << endl
               << "{"                                                  << endl
               << "  d = $directory($t)"                               << endl
               << "  n = $name($t)..."                                 << endl
               <<                                                         endl
               << "  ./: $d/exe{$n}: $t $d/{" << hs << "}{+$n} $d/testscript{+$n}";

            if (binless)
              os << ' ' << "lib{" << s << "}"                          << endl;
            else
              os << '\n'
                 << "  $d/exe{$n}: libul{" << s << "}: bin.whole = false" << endl;

            os << "}"                                                  << endl;
          }

          if (ver)
            os <<                                                         endl
               << "# Include the generated version header into the distribution (so that we don't" << endl
               << "# pick up an installed one) and don't remove it when cleaning in src (so that"  << endl
               << "# clean results in a state identical to distributed)."                          << endl
               << "#"                                                                              << endl
               << h << "{version}: in{version} $src_root/manifest"     << endl
               << "{"                                                  << endl
               << "  dist  = true"                                     << endl
               << "  clean = ($src_root != $out_root)"                 << endl
               << "}"                                                  << endl;

          // Build.
          //
          os <<                                                           endl
             << "# Build options."                                     << endl
             << "#"                                                    << endl
             << m << ".poptions =+ \"-I$out_root\" \"-I$src_root\""    << endl;

          if (!binless)
            os <<                                                         endl
               << "obja{*}: " << m << ".poptions += -D" << mp << "_STATIC_BUILD" << endl
               << "objs{*}: " << m << ".poptions += -D" << mp << "_SHARED_BUILD" << endl;

          // Export.
          //
          os <<                                                           endl
             << "# Export options."                                    << endl
             << "#"                                                    << endl
             << "lib{" <<  s << "}:"                                   << endl
             << "{"                                                    << endl
             << "  " << m << ".export.poptions = \"-I$out_root\" \"-I$src_root\"" << endl
             << "  " << m << ".export.libs = $int_libs"                << endl
             << "}"                                                    << endl;

          if (!binless)
            os <<                                                         endl
               << "liba{" << s << "}: " << m << ".export.poptions += -D" << mp << "_STATIC" << endl
               << "libs{" << s << "}: " << m << ".export.poptions += -D" << mp << "_SHARED" << endl;

          // Library versioning.
          //
          if (!binless)
            os <<                                                         endl
               << "# For pre-releases use the complete version to make sure they cannot be used" << endl
               << "# in place of another pre-release or the final version. See the version module" << endl
               << "# for details on the version.* variable values."    << endl
               << "#"                                                                            << endl
               << "if $version.pre_release"                                                   << endl
               << "  lib{" << s << "}: bin.lib.version = @\"-$version.project_id\""           << endl
               << "else"                                                                      << endl
               << "  lib{" << s << "}: bin.lib.version = @\"-$version.major.$version.minor\"" << endl;

          // Installation.
          //
          if (install)
            os <<                                                         endl
               << "# Install into the " << ip << " subdirectory of, say, /usr/include/" << endl
               << "# recreating subdirectories."                                        << endl
               << "#"                                                                   << endl
               << "{" << hs << "}{*}:"                                 << endl
               << "{"                                                  << endl
               << "  install         = include/" << ip                 << endl
               << "  install.subdirs = true"                           << endl
               << "}"                                                  << endl;

          os.close ();

          // <base>/.gitignore
          //
          if (ver || utest)
          {
            if (vc == vcs::git)
            {
              open (sd / ".gitignore");
              if (ver)
                os << "# Generated version header."                    << endl
                   << "#"                                              << endl
                   << verh                                             << endl;
              if (utest)
                os <<                                        (ver ? "\n" : "")
                   << "# Unit test executables and Testscript output directories" << endl
                   << "# (can be symlinks)."                           << endl
                   << "#"                                              << endl
                   << "*.test"                                         << endl
                   << "test-*.test"                                    << endl;
              os.close ();
            }
          }

          // <base>/<stem>.test.*
          //
          if (utest)
          {
            switch (l)
            {
            case lang::c:
              {
                // <base>/<stem>.test.c
                //
                open (sd / s + ".test.c");
                os << "#include <stdio.h>"                             << endl
                   << "#include <assert.h>"                            << endl
                   <<                                                     endl
                   << "#include <" << ip << apih << ">"                << endl
                   <<                                                     endl
                   << "int main ()"                                    << endl
                   << "{"                                              << endl
                   << "  return 0;"                                    << endl
                   << "}"                                              << endl;
                os.close ();

                break;
              }
            case lang::cxx:
              {
                // <base>/<stem>.test.<cxx-ext>
                //
                open (sd / s + ".test" + xe);
                os << "#include <cassert>"                             << endl
                   << "#include <iostream>"                            << endl
                   <<                                                     endl
                   << "#include <" << ip << apih << ">"                << endl
                   <<                                                     endl
                   << "int main ()"                                    << endl
                   << "{"                                              << endl
                   <<                                                     endl
                   << "}"                                              << endl;
                os.close ();

                break;
              }
            }
          }

          // build/export.build
          //
          if (!sub)
          {
            open (bd / "export." + build_ext);
            os << "$out_root/"                                         << endl
               << "{"                                                  << endl
               << "  include " << ip                                   << endl
               << "}"                                                  << endl
               <<                                                         endl
               << "export $out_root/" << ip << "$import.target"        << endl;
            os.close ();
          }

          // tests/ (tests subproject).
          //
          if (!itest)
            break;

          dir_path td (dir_path (out) /= "tests");
          mk (td);

          // tests/build/
          //
          dir_path tbd (dir_path (td) / build_dir);
          mk (tbd);

          // tests/build/bootstrap.build
          //
          open (tbd / "bootstrap." + build_ext);
          os << "project = # Unnamed tests subproject."                << endl
             <<                                                           endl
             << "using config"                                         << endl
             << "using test"                                           << endl
             << "using dist"                                           << endl;
          os.close ();

          // tests/build/root.build
          //
          open (tbd / "root." + build_ext);
          switch (l)
          {
          case lang::c:
            {
              // @@ TODO: 'latest' in c.std.
              //
              os //<< "c.std = latest"                                 << endl
                //<<                                                      endl
                << "using c"                                           << endl
                <<                                                        endl
                << "h{*}: extension = h"                               << endl
                << "c{*}: extension = c"                               << endl;
              break;
            }
          case lang::cxx:
            {
              os << "cxx.std = latest"                                 << endl
                 <<                                                       endl
                 << "using cxx"                                        << endl
                 <<                                                       endl;

              if (me) os << "mxx{*}: extension = " << pure_ext (*me)   << endl;
              os         << "hxx{*}: extension = " << pure_ext (he)    << endl;
              if (ie) os << "ixx{*}: extension = " << pure_ext (*ie)   << endl;
              if (te) os << "txx{*}: extension = " << pure_ext (*te)   << endl;
              os         << "cxx{*}: extension = " << pure_ext (xe)    << endl;

              break;
            }
          }
          os <<                                                            endl
             << "# Every exe{} in this subproject is by default a test."<< endl
             << "#"                                                     << endl
             << "exe{*}: test = true"                                   << endl
             <<                                                            endl
             << "# The test target for cross-testing (running tests under Wine, etc)." << endl
             << "#"                                                     << endl
             << "test.target = $" << m << ".target"                     << endl;
          os.close ();

          // tests/build/.gitignore
          //
          if (vc == vcs::git)
          {
            open (tbd / ".gitignore");
            os << "config." << build_ext                               << endl
               << "root/"                                              << endl
               << "bootstrap/"                                         << endl;
            os.close ();
          }

          // tests/buildfile
          //
          open (td / buildfile_file);
          os << "./: {*/ -" << build_dir.posix_representation () << "}" << endl;
          os.close ();

          // tests/.gitignore
          //
          if (vc == vcs::git)
          {
            open (td / ".gitignore");
            os << "# Test executables."                                << endl
               << "#"                                                  << endl
               << "driver"                                             << endl
               <<                                                         endl
               << "# Testscript output directories (can be symlinks)." << endl
               << "#"                                                  << endl
               << "test"                                               << endl
               << "test-*"                                             << endl;
            os.close ();
          }

          // tests/basics/
          //
          td /= "basics";
          mk (td);

          switch (l)
          {
          case lang::c:
            {
              // It would have been nice if we could use something like
              // open_memstream() or fmemopen() but these are not portable.
              // So we resort to tmpfile(), which, turns out, is broken on
              // Windows (it may try to create a file in the root directory of
              // a drive and that may require elevated privileges). So we
              // provide our own implementation for that. Who thought writing
              // portable C could be so hard?

              // tests/basics/driver.c
              //
              open (td / "driver.c");
              os << "#include <stdio.h>"                               << endl
                 << "#include <errno.h>"                               << endl
                 << "#include <string.h>"                              << endl
                 << "#include <assert.h>"                              << endl
                 <<                                                       endl;
              if (ver)
                os << "#include <" << ip << verh << ">"                << endl;
              os << "#include <" << ip << apih << ">"                  << endl
                 <<                                                       endl
                 << "#ifdef _WIN32"                                    << endl
                 << "#define tmpfile mytmpfile"                        << endl
                 << "static FILE *mytmpfile ();"                       << endl
                 << "#endif"                                           << endl
                 <<                                                       endl
                 << "int main ()"                                      << endl
                 << "{"                                                << endl
                 << "  char b[256];"                                   << endl
                 <<                                                       endl
                 << "  /* Basics."                                     << endl
                 << "   */"                                            << endl
                 << "  {"                                              << endl
                 << "    FILE *o = tmpfile ();"                        << endl
                 << "    assert (say_hello (o, \"World\") > 0);"       << endl
                 << "    rewind (o);"                                  << endl
                 << "    assert (fread (b, 1, sizeof (b), o) == 14 &&" << endl
                 << "            strncmp (b, \"Hello, World!\\n\", 14) == 0);" << endl
                 << "    fclose (o);"                                  << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  /* Empty name."                                 << endl
                 << "   */"                                            << endl
                 << "  {"                                              << endl
                 << "    FILE *o = tmpfile ();"                        << endl
                 << "    assert (say_hello (o, \"\") < 0 && errno == EINVAL);" << endl
                 << "    fclose (o);"                                  << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  return 0;"                                      << endl
                 << "}"                                                << endl
                 <<                                                       endl
                 << "#ifdef _WIN32"                                    << endl
                 << "#include <windows.h>"                             << endl
                 << "#include <fcntl.h>"                               << endl
                 << "#include <io.h>"                                  << endl
                 <<                                                       endl
                 << "FILE *mytmpfile ()"                               << endl
                 << "{"                                                << endl
                 << "  char d[MAX_PATH + 1], p[MAX_PATH + 1];"         << endl
                 << "  if (GetTempPathA (sizeof (d), d) == 0 ||"       << endl
                 << "      GetTempFileNameA (d, \"tmp\", 0, p) == 0)"  << endl
                 << "    return NULL;"                                 << endl
                 <<                                                       endl
                 << "  HANDLE h = CreateFileA (p,"                     << endl
                 << "                          GENERIC_READ | GENERIC_WRITE," << endl
                 << "                          0,"                     << endl
                 << "                          NULL,"                  << endl
                 << "                          CREATE_ALWAYS,"         << endl
                 << "                          FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE," << endl
                 << "                          NULL);"                 << endl
                 << "  if (h == INVALID_HANDLE_VALUE)"                 << endl
                 << "    return NULL;"                                 << endl
                 <<                                                       endl
                 << "  int fd = _open_osfhandle ((intptr_t) h, _O_RDWR);" << endl
                 << "  if (fd == -1)"                                  << endl
                 << "    return NULL;"                                 << endl
                 <<                                                       endl
                 << "  FILE *f = _fdopen (fd, \"wb+\");"               << endl
                 << "  if (f == NULL)"                                 << endl
                 << "    _close (fd);"                                 << endl
                 <<                                                       endl
                 << "  return f;"                                      << endl
                 << "}"                                                << endl
                 << "#endif"                                           << endl;
              os.close ();

              break;
            }
          case lang::cxx:
            {
              // tests/basics/driver.<cxx-ext>
              //
              open (td / "driver" + xe);
              os << "#include <cassert>"                               << endl
                 << "#include <sstream>"                               << endl
                 << "#include <stdexcept>"                             << endl
                 <<                                                       endl;
              if (ver)
                os << "#include <" << ip << verh << ">"                << endl;
              os << "#include <" << ip << apih << ">"                  << endl
                 <<                                                       endl
                 << "int main ()"                                      << endl
                 << "{"                                                << endl
                 << "  using namespace std;"                           << endl
                 << "  using namespace " << id << ";"                  << endl
                 <<                                                       endl
                 << "  // Basics."                                     << endl
                 << "  //"                                             << endl
                 << "  {"                                              << endl
                 << "    ostringstream o;"                             << endl
                 << "    say_hello (o, \"World\");"                    << endl
                 << "    assert (o.str () == \"Hello, World!\\n\");"   << endl
                 << "  }"                                              << endl
                 <<                                                       endl
                 << "  // Empty name."                                 << endl
                 << "  //"                                             << endl
                 << "  try"                                            << endl
                 << "  {"                                              << endl
                 << "    ostringstream o;"                             << endl
                 << "    say_hello (o, \"\");"                         << endl
                 << "    assert (false);"                              << endl
                 << "  }"                                              << endl
                 << "  catch (const invalid_argument& e)"              << endl
                 << "  {"                                              << endl
                 << "    assert (e.what () == string (\"empty name\"));" << endl
                 << "  }"                                              << endl
                 << "}"                                                << endl;
              os.close ();

              break;
            }
          }

          // tests/basics/buildfile
          //
          open (td / buildfile_file);
          os << "import libs = " << n << "%lib{" << s << "}"           << endl
             <<                                                           endl
             << "exe{driver}: {" << hs << ' ' << x                     <<
            "}{**} $libs testscript{**}"                               << endl;
          // <<                                                         endl
          // << m << ".poptions =+ \"-I$out_root\" \"-I$src_root\""  << endl;
          os.close ();

          break;
        }
      case type::bare:
      case type::empty:
        {
          assert (false);
        }
      }

      break; // Done.
    }
    catch (const io_error& e)
    {
      fail << "unable to write to " << cf << ": " << e;
    }

    // Cancel auto-removal of the files we have created.
    //
    for (auto& rm: rms)
      rm.cancel ();

    // packages.manifest
    //
    if (pkg)
    {
      path f (prj / "packages.manifest");
      bool e (exists (f));
      try
      {
        ofdstream os (f, (fdopen_mode::out    |
                          fdopen_mode::create |
                          fdopen_mode::append));
        os << (e ? ":" : ": 1")                                        << endl
           << "location: " << pkg->posix_representation ()             << endl;
        os.close ();
      }
      catch (const io_error& e)
      {
        fail << "unable to write to " << f << ": " << e;
      }
    }

    // Run post hooks.
    //
    if (o.post_hook_specified ())
      run_hooks (o.post_hook (), "post");

    if (verb)
      text << "created new " << t << ' ' << (sub ? "source subdirectory" :
                                             pkg ? "package" : "project")
           << ' ' << n << " in " << out;

    // --no-init | --package | --subdirectory
    //
    if (o.no_init () || pkg || sub)
      return 0;

    // Create .bdep/.
    //
    mk (prj / bdep_dir);

    // Initialize tmp directory.
    //
    init_tmp (prj);

    // Everything else requires a database.
    //
    database db (open (prj, trace, true /* create */));

    if (ca || cc)
    {
      package_locations pkgs;

      if (t != type::empty) // prj == pkg
        pkgs.push_back (package_location {move (pkgn), nullopt, dir_path ()});

      strings cfg_args;
      if (cc)
        for (; args.more (); cfg_args.push_back (args.next ())) ;

      configurations cfgs {
        cmd_init_config (
          o,
          o,
          prj,
          pkgs,
          db,
          ca ? o.config_add () : o.config_create (),
          cfg_args,
          ca,
          cc)};

      cmd_init (o, prj, db, cfgs, pkgs, strings () /* pkg_args */);
    }

    return 0;
  }

  default_options_files
  options_files (const char*, const cmd_new_options& o, const strings&)
  {
    // NOTE: remember to update the documentation if changing anything here.

    // bdep.options
    // bdep-{config config-add}.options               # -A
    // bdep-{config config-add config-create}.options # -C
    // bdep-new.options
    // bdep-new-{project|package|subdirectory}.options

    // Use the project directory as a start directory in the
    // package/subdirectory modes and the parent directory of the new project
    // otherwise.
    //
    // Note that we will not validate the command arguments and let cmd_new()
    // complain later in case of an error.
    //
    optional<dir_path> start;

    auto output_parent_dir = [&o] ()
    {
      return normalize (o.output_dir (), "output");
    };

    if (o.package () || o.subdirectory ())
    {
      start =
        o.output_dir_specified () ? output_parent_dir ()                  :
        o.directory_specified  () ? normalize (o.directory (), "project") :
        current_directory ();

      // Get the actual project directory.
      //
      project_package pp (find_project_package (*start,
                                                true /* ignore_not_found */));

      if (!pp.project.empty ())
        start = move (pp.project);
      else if (!o.no_checks ())
        start = nullopt;           // Let cmd_new() fail.
    }
    else // New project.
    {
      start = o.output_dir_specified ()
              ? output_parent_dir ()
              : current_directory ();
    }

    default_options_files r {{path ("bdep.options")}, move (start)};

    auto add = [&r] (const string& n)
    {
      r.files.push_back (path ("bdep-" + n + ".options"));
    };

    if (o.config_add_specified () || o.config_create_specified ())
    {
      add ("config");
      add ("config-add");
    }

    if (o.config_create_specified ())
      add ("config-create");

    add ("new");

    // Add the mode-specific options file.
    //
    add (o.subdirectory () ? "new-subdirectory" :
         o.package ()      ? "new-package"      :
                             "new-project");

    return r;
  }

  cmd_new_options
  merge_options (const default_options<cmd_new_options>& defs,
                 const cmd_new_options& cmd)
  {
    // NOTE: remember to update the documentation if changing anything here.

    // While validating/merging the default options, check for the "remote"
    // hooks presence and prepare the prompt, if that's the case.
    //
    diag_record dr;

    auto verify = [&dr] (const default_options_entry<cmd_new_options>& e,
                         const cmd_new_options&)
    {
      const cmd_new_options& o (e.options);

      auto forbid = [&e] (const char* opt, bool specified)
      {
        if (specified)
          fail (e.file) << opt << " in default options file";
      };

      forbid ("--output-dir|-o",    o.output_dir_specified ());
      forbid ("--directory|-d",     o.directory_specified ());
      forbid ("--package",          o.package ());
      forbid ("--subdirectory",     o.subdirectory ());
      forbid ("--no-checks",        o.no_checks ());
      forbid ("--config-add|-A",    o.config_add_specified ());
      forbid ("--config-create|-C", o.config_create_specified ());
      forbid ("--wipe",             o.wipe ()); // Dangerous.

      if (e.remote && (o.pre_hook_specified () || o.post_hook_specified ()))
      {
        if (dr.empty ())
          dr << text;
        else
          dr << '\n';

        dr << "remote hook commands in " << e.file << ':';

        auto add = [&dr] (const strings& hs, const char* what)
        {
          for (const string& cmd: hs)
            dr << "\n  " << what << ' ' << cmd;
        };

        if (o.pre_hook_specified ())
          add (o.pre_hook (),   "pre: ");

        if (o.post_hook_specified ())
          add (o.post_hook (), "post:");
      }
    };

    cmd_new_options r (merge_default_options (defs, cmd, verify));

    if (!dr.empty ())
    {
      dr.flush ();

      if (!yn_prompt ("execute? [y/n]"))
        throw failed ();
    }

    return r;
  }
}