pyflow 0.3.1

A modern Python installation and dependency manager
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
#![allow(clippy::non_ascii_literal)]

#[mockall_double::double]
use crate::dep_resolution::res;
use crate::dep_types::{
    Constraint, Extras, Lock, LockPackage, Package, Rename, Req, ReqType, Version,
};
use crate::util::{abort, Os};

use regex::Regex;
use serde::Deserialize;
use std::{collections::HashMap, env, error::Error, fs, path::PathBuf, str::FromStr};

use std::io::{BufRead, BufReader};
use std::path::Path;
use std::sync::{Arc, RwLock};
use structopt::StructOpt;
use termcolor::{Color, ColorChoice};

mod build;
mod commands;
mod dep_parser;
mod dep_resolution;
mod dep_types;
mod files;
mod install;
mod py_versions;
mod util;

// todo:
// Custom build system
// Fix pydeps caching timeout
// Make binaries work on any linux distro
// Mac binaries for pyflow and python
// "fatal: destination path exists" when using git deps
// add hash and git/path info to locks
// clear download git source as an option. In general, git install is a mess

type PackToInstall = ((String, Version), Option<(u32, String)>); // ((Name, Version), (parent id, rename name))

#[derive(StructOpt, Debug)]
#[structopt(name = "pyflow", about = "Python packaging and publishing")]
struct Opt {
    #[structopt(subcommand)]
    subcmds: SubCommand,

    /// Force a color option: auto (default), always, ansi, never
    #[structopt(short, long)]
    color: Option<String>,
}

#[derive(StructOpt, Debug)]
enum SubCommand {
    /// Create a project folder with the basics
    #[structopt(name = "new")]
    New {
        #[structopt(name = "name")]
        name: String, // holds the project name.
    },

    /** Install packages from `pyproject.toml`, `pyflow.lock`, or speficied ones. Example:

    `pyflow install`: sync your installation with `pyproject.toml`, or `pyflow.lock` if it exists.
    `pyflow install numpy scipy`: install `numpy` and `scipy`.*/
    #[structopt(name = "install")]
    Install {
        #[structopt(name = "packages")]
        packages: Vec<String>,
        /// Save package to your dev-dependencies section
        #[structopt(short, long)]
        dev: bool,
    },
    /// Uninstall all packages, or ones specified
    #[structopt(name = "uninstall")]
    Uninstall {
        #[structopt(name = "packages")]
        packages: Vec<String>,
    },
    /// Display all installed packages and console scripts
    #[structopt(name = "list")]
    List,
    /// Build the package - source and wheel
    #[structopt(name = "package")]
    Package {
        #[structopt(name = "extras")]
        extras: Vec<String>,
    },
    /// Publish to `pypi`
    #[structopt(name = "publish")]
    Publish,
    /// Create a `pyproject.toml` from requirements.txt, pipfile etc, setup.py etc
    #[structopt(name = "init")]
    Init,
    /// Remove the environment, and uninstall all packages
    #[structopt(name = "reset")]
    Reset,
    /// Remove cached packages, Python installs, or script-environments. Eg to free up hard drive space.
    #[structopt(name = "clear")]
    Clear,
    /// Run a CLI script like `ipython` or `black`. Note that you can simply run `pyflow black`
    /// as a shortcut.
    // Dummy option with space at the end for documentation
    #[structopt(name = "run ")] // We don't need to invoke this directly, but the option exists
    Run,

    /// Run the project python or script with the project python environment.
    /// As a shortcut you can simply specify a script name ending in `.py`
    // Dummy option with space at the end for documentation
    #[structopt(name = "python ")]
    Python,

    /// Run a standalone script not associated with a project
    // Dummy option with space at the end for documentation
    #[structopt(name = "script ")]
    Script,
    //    /// Run a package globally; used for CLI tools like `ipython` and `black`. Doesn't
    //    /// interfere Python installations. Must have been installed with `pyflow install -g black` etc
    //    #[structopt(name = "global")]
    //    Global {
    //        #[structopt(name = "name")]
    //        name: String,
    //    },
    /// Change the Python version for this project. eg `pyflow switch 3.8`. Equivalent to setting
    /// `py_version` in `pyproject.toml`.
    #[structopt(name = "switch")]
    Switch {
        #[structopt(name = "version")]
        version: String,
    },
    // Documentation for supported external subcommands can be documented by
    // adding a `dummy` subcommand with the name having a trailing space.
    // #[structopt(name = "external ")]
    #[structopt(external_subcommand, name = "external")]
    External(Vec<String>),
}

#[derive(Clone, Debug)]
enum ExternalSubcommands {
    Run,
    Script,
    Python,
    ImpliedRun(String),
    ImpliedPython(String),
}

impl ToString for ExternalSubcommands {
    fn to_string(&self) -> String {
        match self {
            Self::Run => "run".into(),
            Self::Script => "script".into(),
            Self::Python => "python".into(),
            Self::ImpliedRun(x) => x.into(),
            Self::ImpliedPython(x) => x.into(),
        }
    }
}

impl FromStr for ExternalSubcommands {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> anyhow::Result<Self> {
        let result = match s {
            "run" => Self::Run,
            "script" => Self::Script,
            "python" => Self::Python,
            x if x.ends_with(".py") => Self::ImpliedPython(x.to_string()),
            x => Self::ImpliedRun(x.to_string()),
        };
        Ok(result)
    }
}

#[derive(Clone, Debug)]
struct ExternalCommand {
    cmd: ExternalSubcommands,
    args: Vec<String>,
}

impl ExternalCommand {
    fn from_opt(args: Vec<String>) -> Self {
        let cmd = ExternalSubcommands::from_str(&args[0]).unwrap();
        let cmd_args = match cmd {
            ExternalSubcommands::Run
            | ExternalSubcommands::Script
            | ExternalSubcommands::Python => &args[1..],
            ExternalSubcommands::ImpliedRun(_) | ExternalSubcommands::ImpliedPython(_) => &args,
        };
        let cmd = match cmd {
            ExternalSubcommands::ImpliedRun(_) => ExternalSubcommands::Run,
            ExternalSubcommands::ImpliedPython(_) => ExternalSubcommands::Python,
            x => x,
        };
        Self {
            cmd,
            args: cmd_args.to_vec(),
        }
    }
}
/// A config, parsed from pyproject.toml
#[derive(Clone, Debug, Default, Deserialize)]
// todo: Auto-desr some of these
pub struct Config {
    name: Option<String>,
    py_version: Option<Version>,
    reqs: Vec<Req>,
    dev_reqs: Vec<Req>,
    version: Option<Version>,
    authors: Vec<String>,
    license: Option<String>,
    extras: HashMap<String, String>,
    description: Option<String>,
    classifiers: Vec<String>, // https://pypi.org/classifiers/
    keywords: Vec<String>,
    homepage: Option<String>,
    repository: Option<String>,
    repo_url: Option<String>,
    package_url: Option<String>,
    readme: Option<String>,
    build: Option<String>, // A python file used to build non-python extensions
    //    entry_points: HashMap<String, Vec<String>>, // todo option?
    scripts: HashMap<String, String>, //todo: put under [tool.pyflow.scripts] ?
    //    console_scripts: Vec<String>, // We don't parse these; pass them to `setup.py` as-entered.
    python_requires: Option<String>,
}

/// Reduce repetition between reqs and dev reqs when populating reqs of path reqs.
fn pop_reqs_helper(reqs: &[Req], dev: bool) -> Vec<Req> {
    let mut result = vec![];
    for req in reqs.iter().filter(|r| r.path.is_some()) {
        let req_path = PathBuf::from(req.path.clone().unwrap());
        let pyproj = req_path.join("pyproject.toml");
        let req_txt = req_path.join("requirements.txt");
        //        let pipfile = req_path.join("Pipfile");

        let mut dummy_cfg = Config::default();

        if req_txt.exists() {
            files::parse_req_dot_text(&mut dummy_cfg, &req_txt);
        }

        //        if pipfile.exists() {
        //            files::parse_pipfile(&mut dummy_cfg, &pipfile);
        //        }

        if dev {
            result.append(&mut dummy_cfg.dev_reqs);
        } else {
            result.append(&mut dummy_cfg.reqs);
        }

        // We don't parse `setup.py`, since it involves running arbitrary Python code.

        if pyproj.exists() {
            let mut req_cfg = Config::from_file(&PathBuf::from(&pyproj))
                .unwrap_or_else(|| panic!("Problem parsing`pyproject.toml`: {:?}", &pyproj));
            result.append(&mut req_cfg.reqs)
        }

        // Check for metadata of a built wheel
        for folder_name in util::find_folders(&req_path) {
            // todo: Dry from `util` and `install`.
            let re_dist = Regex::new(r"^(.*?)-(.*?)\.dist-info$").unwrap();
            if re_dist.captures(&folder_name).is_some() {
                let metadata_path = req_path.join(folder_name).join("METADATA");
                let mut metadata = util::parse_metadata(&metadata_path);

                result.append(&mut metadata.requires_dist);
            }
        }
    }
    result
}

impl Config {
    /// Helper fn to prevent repetition
    fn parse_deps(deps: HashMap<String, files::DepComponentWrapper>) -> Vec<Req> {
        let mut result = Vec::new();
        for (name, data) in deps {
            let constraints;
            let mut extras = None;
            let mut git = None;
            let mut path = None;
            let mut python_version = None;
            match data {
                files::DepComponentWrapper::A(constrs) => {
                    constraints = if let Ok(c) = Constraint::from_str_multiple(&constrs) {
                        c
                    } else {
                        abort(&format!(
                            "Problem parsing constraints in `pyproject.toml`: {}",
                            &constrs
                        ));
                        unreachable!()
                    };
                }
                files::DepComponentWrapper::B(subdata) => {
                    constraints = match subdata.constrs {
                        Some(constrs) => {
                            if let Ok(c) = Constraint::from_str_multiple(&constrs) {
                                c
                            } else {
                                abort(&format!(
                                    "Problem parsing constraints in `pyproject.toml`: {}",
                                    &constrs
                                ));
                                unreachable!()
                            }
                        }
                        None => vec![],
                    };

                    if let Some(ex) = subdata.extras {
                        extras = Some(ex);
                    }
                    if let Some(p) = subdata.path {
                        path = Some(p);
                    }
                    if let Some(repo) = subdata.git {
                        git = Some(repo);
                    }
                    if let Some(v) = subdata.python {
                        let pv = Constraint::from_str(&v)
                            .expect("Problem parsing python version in dependency");
                        python_version = Some(vec![pv]);
                    }
                }
            }

            result.push(Req {
                name,
                constraints,
                extra: None,
                sys_platform: None,
                python_version,
                install_with_extras: extras,
                path,
                git,
            });
        }
        result
    }

    // todo: DRY at the top from `from_file`.
    fn from_pipfile(path: &Path) -> Option<Self> {
        // todo: Lots of tweaks and QC could be done re what fields to parse, and how best to
        // todo parse and store them.
        let toml_str = match fs::read_to_string(path).ok() {
            Some(d) => d,
            None => return None,
        };

        let decoded: files::Pipfile = if let Ok(d) = toml::from_str(&toml_str) {
            d
        } else {
            abort("Problem parsing `Pipfile`");
            unreachable!()
        };
        let mut result = Self::default();

        if let Some(pipfile_deps) = decoded.packages {
            result.reqs = Self::parse_deps(pipfile_deps);
        }
        if let Some(pipfile_dev_deps) = decoded.dev_packages {
            result.dev_reqs = Self::parse_deps(pipfile_dev_deps);
        }

        Some(result)
    }

    /// Pull config data from `pyproject.toml`. We use this to deserialize things like Versions
    /// and requirements.
    fn from_file(path: &Path) -> Option<Self> {
        // todo: Lots of tweaks and QC could be done re what fields to parse, and how best to
        // todo parse and store them.
        let toml_str = match fs::read_to_string(path) {
            Ok(d) => d,
            Err(_) => return None,
        };

        let decoded: files::Pyproject = if let Ok(d) = toml::from_str(&toml_str) {
            d
        } else {
            abort("Problem parsing `pyproject.toml`");
            unreachable!()
        };
        let mut result = Self::default();

        // Parse Poetry first, since we'll use pyflow if there's a conflict.
        if let Some(po) = decoded.tool.poetry {
            if let Some(v) = po.name {
                result.name = Some(v);
            }
            if let Some(v) = po.authors {
                result.authors = v;
            }
            if let Some(v) = po.license {
                result.license = Some(v);
            }

            if let Some(v) = po.homepage {
                result.homepage = Some(v);
            }
            if let Some(v) = po.description {
                result.description = Some(v);
            }
            if let Some(v) = po.repository {
                result.repository = Some(v);
            }
            if let Some(v) = po.readme {
                result.readme = Some(v);
            }
            if let Some(v) = po.build {
                result.build = Some(v);
            }
            // todo: Process entry pts, classifiers etc?
            if let Some(v) = po.classifiers {
                result.classifiers = v;
            }
            if let Some(v) = po.keywords {
                result.keywords = v;
            }

            //                        if let Some(v) = po.source {
            //                result.source = v;
            //            }
            //            if let Some(v) = po.scripts {
            //                result.console_scripts = v;
            //            }
            if let Some(v) = po.extras {
                result.extras = v;
            }

            if let Some(v) = po.version {
                result.version = Some(
                    Version::from_str(&v).expect("Problem parsing version in `pyproject.toml`"),
                )
            }

            // todo: DRY (c+p) from pyflow dependency parsing, other than parsing python version here,
            // todo which only poetry does.
            // todo: Parse poetry dev deps
            if let Some(deps) = po.dependencies {
                for (name, data) in deps {
                    let constraints;
                    let mut extras = None;
                    let mut python_version = None;
                    match data {
                        files::DepComponentWrapperPoetry::A(constrs) => {
                            constraints = Constraint::from_str_multiple(&constrs)
                                .expect("Problem parsing constraints in `pyproject.toml`.");
                        }
                        files::DepComponentWrapperPoetry::B(subdata) => {
                            constraints = Constraint::from_str_multiple(&subdata.constrs)
                                .expect("Problem parsing constraints in `pyproject.toml`.");
                            if let Some(ex) = subdata.extras {
                                extras = Some(ex);
                            }
                            if let Some(v) = subdata.python {
                                let pv = Constraint::from_str(&v)
                                    .expect("Problem parsing python version in dependency");
                                python_version = Some(vec![pv]);
                            }
                            // todo repository etc
                        }
                    }
                    if &name.to_lowercase() == "python" {
                        if let Some(constr) = constraints.get(0) {
                            result.py_version = Some(constr.version.clone())
                        }
                    } else {
                        result.reqs.push(Req {
                            name,
                            constraints,
                            extra: None,
                            sys_platform: None,
                            python_version,
                            install_with_extras: extras,
                            path: None,
                            git: None,
                        });
                    }
                }
            }
        }

        if let Some(pf) = decoded.tool.pyflow {
            if let Some(v) = pf.name {
                result.name = Some(v);
            }

            if let Some(v) = pf.authors {
                result.authors = if v.is_empty() {
                    util::get_git_author()
                } else {
                    v
                };
            }
            if let Some(v) = pf.license {
                result.license = Some(v);
            }
            if let Some(v) = pf.homepage {
                result.homepage = Some(v);
            }
            if let Some(v) = pf.description {
                result.description = Some(v);
            }
            if let Some(v) = pf.repository {
                result.repository = Some(v);
            }

            // todo: Process entry pts, classifiers etc?
            if let Some(v) = pf.classifiers {
                result.classifiers = v;
            }
            if let Some(v) = pf.keywords {
                result.keywords = v;
            }
            if let Some(v) = pf.readme {
                result.readme = Some(v);
            }
            if let Some(v) = pf.build {
                result.build = Some(v);
            }
            //            if let Some(v) = pf.entry_points {
            //                result.entry_points = v;
            //            } // todo
            if let Some(v) = pf.scripts {
                result.scripts = v;
            }

            if let Some(v) = pf.python_requires {
                result.python_requires = Some(v);
            }

            if let Some(v) = pf.package_url {
                result.package_url = Some(v);
            }

            if let Some(v) = pf.version {
                result.version = Some(
                    Version::from_str(&v).expect("Problem parsing version in `pyproject.toml`"),
                )
            }

            if let Some(v) = pf.py_version {
                result.py_version = Some(
                    Version::from_str(&v)
                        .expect("Problem parsing python version in `pyproject.toml`"),
                );
            }

            if let Some(deps) = pf.dependencies {
                result.reqs = Self::parse_deps(deps);
            }
            if let Some(deps) = pf.dev_dependencies {
                result.dev_reqs = Self::parse_deps(deps);
            }
        }

        Some(result)
    }

    /// For reqs of `path` type, add their sub-reqs by parsing `setup.py` or `pyproject.toml`.
    fn populate_path_subreqs(&mut self) {
        self.reqs.append(&mut pop_reqs_helper(&self.reqs, false));
        self.dev_reqs
            .append(&mut pop_reqs_helper(&self.dev_reqs, true));
    }

    /// Create a new `pyproject.toml` file.
    fn write_file(&self, path: &Path) {
        let file = path;
        if file.exists() {
            abort("`pyproject.toml` already exists")
        }

        let mut result = String::new();

        result.push_str("\n[tool.pyflow]\n");
        if let Some(name) = &self.name {
            result.push_str(&("name = \"".to_owned() + name + "\"\n"));
        } else {
            // Give name, and a few other fields default values.
            result.push_str(&("name = \"\"".to_owned() + "\n"));
        }
        if let Some(py_v) = &self.py_version {
            result.push_str(&("py_version = \"".to_owned() + &py_v.to_string_no_patch() + "\"\n"));
        } else {
            result.push_str(&("py_version = \"3.8\"".to_owned() + "\n"));
        }
        if let Some(vers) = self.version.clone() {
            result.push_str(&(format!("version = \"{}\"", vers.to_string() + "\n")));
        } else {
            result.push_str("version = \"0.1.0\"");
            result.push('\n');
        }
        if !self.authors.is_empty() {
            result.push_str("authors = [\"");
            for (i, author) in self.authors.iter().enumerate() {
                if i != 0 {
                    result.push_str(", ");
                }
                result.push_str(author);
            }
            result.push_str("\"]\n");
        }

        if let Some(v) = &self.description {
            result.push_str(&(format!("description = \"{}\"", v) + "\n"));
        }
        if let Some(v) = &self.homepage {
            result.push_str(&(format!("homepage = \"{}\"", v) + "\n"));
        }

        // todo: More fields

        result.push('\n');
        result.push_str("[tool.pyflow.scripts]\n");
        for (name, mod_fn) in &self.scripts {
            result.push_str(&(format!("{} = \"{}\"", name, mod_fn) + "\n"));
        }

        result.push('\n');
        result.push_str("[tool.pyflow.dependencies]\n");
        for dep in &self.reqs {
            result.push_str(&(dep.to_cfg_string() + "\n"));
        }

        result.push('\n');
        result.push_str("[tool.pyflow.dev-dependencies]\n");
        for dep in &self.dev_reqs {
            result.push_str(&(dep.to_cfg_string() + "\n"));
        }

        result.push('\n'); // trailing newline

        if fs::write(file, result).is_err() {
            abort("Problem writing `pyproject.toml`")
        }
    }
}

/// Cli Config to hold command line options
struct CliConfig {
    pub color_choice: ColorChoice,
}

impl Default for CliConfig {
    fn default() -> Self {
        Self {
            color_choice: ColorChoice::Auto,
        }
    }
}

impl CliConfig {
    pub fn current() -> Arc<CliConfig> {
        CLI_CONFIG.with(|c| c.read().unwrap().clone())
    }
    pub fn make_current(self) {
        CLI_CONFIG.with(|c| *c.write().unwrap() = Arc::new(self))
    }
}

thread_local! {
    static CLI_CONFIG: RwLock<Arc<CliConfig>> = RwLock::new(Default::default());
}

/// Create a template directory for a python project.
pub fn new(name: &str) -> Result<(), Box<dyn Error>> {
    if !PathBuf::from(name).exists() {
        fs::create_dir_all(&format!("{}/{}", name, name.replace("-", "_")))?;
        fs::File::create(&format!("{}/{}/__init__.py", name, name.replace("-", "_")))?;
        fs::File::create(&format!("{}/README.md", name))?;
        fs::File::create(&format!("{}/.gitignore", name))?;
    }

    let gitignore_init = r##"# General Python ignores
build/
dist/
__pycache__/
__pypackages__/
.ipynb_checkpoints/
*.pyc
*~
*/.mypy_cache/


# Project ignores
"##;

    let readme_init = &format!("# {}\n\n{}", name, "(A description)");

    fs::write(&format!("{}/.gitignore", name), gitignore_init)?;
    fs::write(&format!("{}/README.md", name), readme_init)?;

    let cfg = Config {
        name: Some(name.to_string()),
        authors: util::get_git_author(),
        py_version: Some(util::prompt_py_vers()),
        ..Default::default()
    };

    cfg.write_file(&PathBuf::from(format!("{}/pyproject.toml", name)));

    if commands::git_init(Path::new(name)).is_err() {
        util::print_color(
            "Unable to initialize a git repo for your project",
            Color::Yellow, // Dark
        );
    };

    Ok(())
}

/// Read dependency data from a lock file.
fn read_lock(path: &Path) -> Result<Lock, Box<dyn Error>> {
    let data = fs::read_to_string(path)?;
    Ok(toml::from_str(&data)?)
}

/// Write dependency data to a lock file.
fn write_lock(path: &Path, data: &Lock) -> Result<(), Box<dyn Error>> {
    let data = toml::to_string(data)?;
    fs::write(path, data)?;
    Ok(())
}

fn parse_lockpack_rename(rename: &str) -> (u32, String) {
    let re = Regex::new(r"^(\d+)\s(.*)$").unwrap();
    let caps = re
        .captures(rename)
        .expect("Problem reading lock file rename");

    let id = caps.get(1).unwrap().as_str().parse::<u32>().unwrap();
    let name = caps.get(2).unwrap().as_str().to_owned();

    (id, name)
}

/// Install/uninstall deps as required from the passed list, and re-write the lock file.
fn sync_deps(
    paths: &util::Paths,
    lock_packs: &[LockPackage],
    dont_uninstall: &[String],
    installed: &[(String, Version, Vec<String>)],
    os: util::Os,
    python_vers: &Version,
) {
    let packages: Vec<PackToInstall> = lock_packs
        .iter()
        .map(|lp| {
            (
                (
                    util::standardize_name(&lp.name),
                    Version::from_str(&lp.version).expect("Problem parsing lock version"),
                ),
                lp.rename.as_ref().map(|rn| parse_lockpack_rename(rn)),
            )
        })
        .collect();

    // todo shim. Use top-level A/R. We discard it temporarily while working other issues.
    let installed: Vec<(String, Version)> = installed
        .iter()
        // Don't standardize name here; see note below in to_uninstall.
        .map(|t| (t.0.clone(), t.1.clone()))
        .collect();

    // Filter by not-already-installed.
    let to_install: Vec<&PackToInstall> = packages
        .iter()
        .filter(|(pack, _)| {
            let mut contains = false;
            for inst in &installed {
                if util::compare_names(&pack.0, &inst.0) && pack.1 == inst.1 {
                    contains = true;
                    break;
                }
            }

            // The typing module is sometimes downloaded, causing a conflict/improper
            // behavior compared to the built in module.
            !contains && pack.0 != "typing"
        })
        .collect();

    // todo: Once you include rename info in installed, you won't need to use the map logic here.
    let packages_only: Vec<&(String, Version)> = packages.iter().map(|(p, _)| p).collect();
    let to_uninstall: Vec<&(String, Version)> = installed
        .iter()
        .filter(|inst| {
            // Don't standardize the name here; we need original capitalization to uninstall
            // metadata etc.
            let inst = (inst.0.clone(), inst.1.clone());
            let mut contains = false;
            // We can't just use the contains method, due to needing compare_names().
            for pack in &packages_only {
                if util::compare_names(&pack.0, &inst.0) && pack.1 == inst.1 {
                    contains = true;
                    break;
                }
            }

            for name in dont_uninstall {
                if util::compare_names(name, &inst.0) {
                    contains = true;
                    break;
                }
            }

            !contains
        })
        .collect();

    for (name, version) in &to_uninstall {
        // todo: Deal with renamed. Currently won't work correctly with them.
        install::uninstall(name, version, &paths.lib)
    }

    for ((name, version), rename) in &to_install {
        let data =
            res::get_warehouse_release(name, version).expect("Problem getting warehouse data");

        let (best_release, package_type) =
            util::find_best_release(&data, name, version, os, python_vers);

        // Powershell  doesn't like emojis
        // todo format literal issues, so repeating this whole statement.
        #[cfg(target_os = "windows")]
        util::print_color_(&format!("Installing {}", &name), Color::Cyan);
        #[cfg(target_os = "linux")]
        util::print_color_(&format!("⬇ Installing {}", &name), Color::Cyan);
        #[cfg(target_os = "macos")]
        util::print_color_(&format!("⬇ Installing {}", &name), Color::Cyan);
        println!(" {} ...", &version.to_string_color());

        if install::download_and_install_package(
            name,
            version,
            &best_release.url,
            &best_release.filename,
            &best_release.digests.sha256,
            paths,
            package_type,
            rename,
        )
        .is_err()
        {
            abort("Problem downloading packages");
        }
    }
    // Perform renames after all packages are installed, or we may attempt to rename a package
    // we haven't yet installed.
    for ((name, version), rename) in &to_install {
        if let Some((id, new)) = rename {
            // Rename in the renamed package

            let renamed_path = &paths.lib.join(util::standardize_name(new));

            util::wait_for_dirs(&[renamed_path.clone()]).expect("Problem creating renamed path");
            install::rename_package_files(renamed_path, name, new);

            // Rename in the parent calling the renamed package. // todo: Multiple parents?
            let parent = lock_packs
                .iter()
                .find(|lp| lp.id == *id)
                .expect("Can't find parent calling renamed package");
            install::rename_package_files(
                &paths.lib.join(util::standardize_name(&parent.name)),
                name,
                new,
            );

            // todo: Handle this more generally, in case we don't have proper semver dist-info paths.
            install::rename_metadata(
                &paths
                    .lib
                    .join(&format!("{}-{}.dist-info", name, version.to_string())),
                name,
                new,
            );
        }
    }
}

fn already_locked(locked: &[Package], name: &str, constraints: &[Constraint]) -> bool {
    let mut result = true;
    for constr in constraints.iter() {
        if !locked
            .iter()
            .any(|p| util::compare_names(&p.name, name) && constr.is_compatible(&p.version))
        {
            result = false;
            break;
        }
    }
    result
}

/// Execute a python CLI tool, either specified in `pyproject.toml`, or in a dependency.
fn run_cli_tool(
    lib_path: &Path,
    bin_path: &Path,
    vers_path: &Path,
    cfg: &Config,
    args: Vec<String>,
) {
    // Allow both `pyflow run ipython` (args), and `pyflow ipython` (opt.script)
    if args.is_empty() {
        return;
    }

    let name = if let Some(a) = args.get(0) {
        a.clone()
    } else {
        abort("`run` must be followed by the script to run, eg `pyflow run black`");
        unreachable!()
    };

    // If the script we're calling is specified in `pyproject.toml`, ensure it exists.

    // todo: Delete these scripts as required to sync with pyproject.toml.
    let re = Regex::new(r"(.*?):(.*)").unwrap();

    let mut specified_args: Vec<String> = args.into_iter().skip(1).collect();

    // If a script name is specified by by this project and a dependency, favor
    // this project.
    if let Some(s) = cfg.scripts.get(&name) {
        let abort_msg = format!(
            "Problem running the function {}, specified in `pyproject.toml`",
            name,
        );

        if let Some(caps) = re.captures(s) {
            let module = caps.get(1).unwrap().as_str();
            let function = caps.get(2).unwrap().as_str();
            let mut args_to_pass = vec![
                "-c".to_owned(),
                format!(r#"import {}; {}.{}()"#, module, module, function),
            ];

            args_to_pass.append(&mut specified_args);
            if commands::run_python(bin_path, &[lib_path.to_owned()], &args_to_pass).is_err() {
                abort(&abort_msg);
            }
        } else {
            abort(&format!("Problem parsing the following script: {:#?}. Must be in the format module:function_name", s));
            unreachable!()
        }
        return;
    }
    //            None => {
    let abort_msg = format!(
        "Problem running the CLI tool {}. Is it installed? \
         Try running `pyflow install {}`",
        name, name
    );
    let script_path = vers_path.join("bin").join(name);
    if !script_path.exists() {
        abort(&abort_msg);
    }

    let mut args_to_pass = vec![script_path
        .to_str()
        .expect("Can't find script path")
        .to_owned()];

    args_to_pass.append(&mut specified_args);
    if commands::run_python(bin_path, &[lib_path.to_owned()], &args_to_pass).is_err() {
        abort(&abort_msg);
    }
}

/// Find a script's dependencies from a variable: `__requires__ = [dep1, dep2]`
fn find_deps_from_script(file_path: &Path) -> Vec<String> {
    // todo: Helper for this type of logic? We use it several times in the program.
    let f = fs::File::open(file_path).expect("Problem opening the Python script file.");

    let re = Regex::new(r"^__requires__\s*=\s*\[(.*?)\]$").unwrap();

    let mut result = vec![];
    for line in BufReader::new(f).lines().flatten() {
        if let Some(c) = re.captures(&line) {
            let deps_list = c.get(1).unwrap().as_str().to_owned();
            let deps: Vec<&str> = deps_list.split(',').collect();
            result = deps
                .into_iter()
                .map(|d| {
                    d.to_owned()
                        .replace(" ", "")
                        .replace("\"", "")
                        .replace("'", "")
                })
                .filter(|d| !d.is_empty())
                .collect();
        }
    }

    result
}

/// Run a standalone script file, with package management
/// // todo: Perhaps move this logic to its own file, if it becomes long.
/// todo: We're using script name as unique identifier; address this in the future,
/// todo perhaps with an id in a comment at the top of a file
fn run_script(
    script_env_path: &Path,
    dep_cache_path: &Path,
    os: util::Os,
    args: &[String],
    pyflow_dir: &Path,
) {
    #[cfg(debug_assertions)]
    eprintln!("Run script args: {:?}", args);
    // todo: DRY with run_cli_tool and subcommand::Install
    let filename = if let Some(a) = args.get(0) {
        a.clone()
    } else {
        abort("`script` must be followed by the script to run, eg `pyflow script myscript.py`");
        unreachable!()
    };

    // todo: Consider a metadata file, but for now, we'll use folders
    //    let scripts_data_path = script_env_path.join("scripts.toml");

    let env_path = util::canon_join(script_env_path, &filename);
    if !env_path.exists() {
        fs::create_dir_all(&env_path).expect("Problem creating environment for the script");
    }

    // Write the version we found to a file.
    let cfg_vers;
    let py_vers_path = env_path.join("py_vers.txt");

    if py_vers_path.exists() {
        cfg_vers = Version::from_str(
            &fs::read_to_string(py_vers_path)
                .expect("Problem reading Python version for this script")
                .replace("\n", ""),
        )
        .expect("Problem parsing version from file");
    } else {
        cfg_vers = util::prompt_py_vers();

        fs::File::create(&py_vers_path)
            .expect("Problem creating a file to store the Python version for this script");
        fs::write(py_vers_path, &cfg_vers.to_string())
            .expect("Problem writing Python version file.");
    }

    // todo DRY
    let pypackages_dir = env_path.join("__pypackages__");
    let (vers_path, py_vers) =
        util::find_or_create_venv(&cfg_vers, &pypackages_dir, pyflow_dir, dep_cache_path);

    let bin_path = util::find_bin_path(&vers_path);
    let lib_path = vers_path.join("lib");
    let script_path = vers_path.join("bin");
    let lock_path = env_path.join("pyproject.lock");

    let paths = util::Paths {
        bin: bin_path,
        lib: lib_path,
        entry_pt: script_path,
        cache: dep_cache_path.to_owned(),
    };

    let deps = find_deps_from_script(&PathBuf::from(&filename));

    let lock = match read_lock(&lock_path) {
        Ok(l) => l,
        Err(_) => Lock::default(),
    };

    let lockpacks = lock.package.unwrap_or_else(Vec::new);

    let reqs: Vec<Req> = deps
        .iter()
        .map(|name| {
            let (fmtd_name, version) = if let Some(lp) = lockpacks
                .iter()
                .find(|lp| util::compare_names(&lp.name, name))
            {
                (
                    lp.name.clone(),
                    Version::from_str(&lp.version).expect("Problem getting version"),
                )
            } else {
                let vinfo = res::get_version_info(
                    name,
                    Some(Req::new_with_extras(
                        name.to_string(),
                        vec![Constraint::new_any()],
                        Extras::new_py(Constraint::new(ReqType::Exact, py_vers.clone())),
                    )),
                )
                .unwrap_or_else(|_| panic!("Problem getting version info for {}", &name));
                (vinfo.0, vinfo.1)
            };

            Req::new(fmtd_name, vec![Constraint::new(ReqType::Caret, version)])
        })
        .collect();

    sync(
        &paths,
        &lockpacks,
        &reqs,
        &[],
        &[],
        os,
        &py_vers,
        &lock_path,
    );

    if commands::run_python(&paths.bin, &[paths.lib], args).is_err() {
        abort("Problem running this script")
    };
}

/// Function used by `Install` and `Uninstall` subcommands to syn dependencies with
/// the config and lock files.
#[allow(clippy::too_many_arguments)]
fn sync(
    paths: &util::Paths,
    lockpacks: &[LockPackage],
    reqs: &[Req],
    dev_reqs: &[Req],
    dont_uninstall: &[String],
    os: util::Os,
    py_vers: &Version,
    lock_path: &Path,
) {
    let installed = util::find_installed(&paths.lib);
    // We control the lock format, so this regex will always match
    let dep_re = Regex::new(r"^(.*?)\s(.*)\s.*$").unwrap();

    // We don't need to resolve reqs that are already locked.
    let locked: Vec<Package> = lockpacks
        .iter()
        .map(|lp| {
            let mut deps = vec![];
            for dep in lp.dependencies.as_ref().unwrap_or(&vec![]) {
                let caps = dep_re
                    .captures(dep)
                    .expect("Problem reading lock file dependencies");
                let name = caps.get(1).unwrap().as_str().to_owned();
                let vers = Version::from_str(caps.get(2).unwrap().as_str())
                    .expect("Problem parsing version from lock");
                deps.push((999, name, vers)); // dummy id
            }

            Package {
                id: lp.id, // todo
                parent: 0, // todo
                name: lp.name.clone(),
                version: Version::from_str(&lp.version).expect("Problem parsing lock version"),
                deps,
                rename: Rename::No, // todo
            }
        })
        .collect();

    // todo: Only show this when needed.
    // todo: Temporarily? Removed.
    // Powershell  doesn't like emojis
    //    #[cfg(target_os = "windows")]
    //    println!("Resolving dependencies...");
    //    #[cfg(target_os = "linux")]
    //    println!("🔍 Resolving dependencies...");
    //    #[cfg(target_os = "macos")]
    //    println!("🔍 Resolving dependencies...");

    // Dev reqs and normal reqs are both installed here; we only ommit dev reqs
    // when packaging.
    let mut combined_reqs = reqs.to_vec();
    for dev_req in dev_reqs.to_vec() {
        combined_reqs.push(dev_req);
    }

    let resolved = if let Ok(r) = res::resolve(&combined_reqs, &locked, os, py_vers) {
        r
    } else {
        abort("Problem resolving dependencies");
        unreachable!()
    };

    // Now merge the existing lock packages with new ones from resolved packages.
    // We have a collection of requirements; attempt to merge them with the already-locked ones.
    let mut updated_lock_packs = vec![];

    for package in &resolved {
        let dummy_constraints = vec![Constraint::new(ReqType::Exact, package.version.clone())];
        if already_locked(&locked, &package.name, &dummy_constraints) {
            let existing: Vec<&LockPackage> = lockpacks
                .iter()
                .filter(|lp| util::compare_names(&lp.name, &package.name))
                .collect();
            let existing2 = existing[0];

            updated_lock_packs.push(existing2.clone());
            continue;
        }

        let deps = package
            .deps
            .iter()
            .map(|(_, name, version)| {
                format!(
                    "{} {} pypi+https://pypi.org/pypi/{}/{}/json",
                    name, version, name, version,
                )
            })
            .collect();

        updated_lock_packs.push(LockPackage {
            id: package.id,
            name: package.name.clone(),
            version: package.version.to_string(),
            source: Some(format!(
                "pypi+https://pypi.org/pypi/{}/{}/json",
                package.name,
                package.version.to_string()
            )),
            dependencies: Some(deps),
            rename: match &package.rename {
                Rename::Yes(parent_id, _, name) => Some(format!("{} {}", parent_id, name)),
                Rename::No => None,
            },
        });
    }

    let updated_lock = Lock {
        //        metadata: Some(lock_metadata),
        metadata: HashMap::new(), // todo: Problem with toml conversion.
        package: Some(updated_lock_packs.clone()),
    };
    if write_lock(lock_path, &updated_lock).is_err() {
        abort("Problem writing lock file");
    }

    // Now that we've confirmed or modified the lock file, we're ready to sync installed
    // depenencies with it.
    sync_deps(
        paths,
        &updated_lock_packs,
        dont_uninstall,
        &installed,
        os,
        py_vers,
    );
}

#[derive(Clone)]
enum ClearChoice {
    Dependencies,
    ScriptEnvs,
    PyInstalls,
    //    Global,
    All,
}

impl ToString for ClearChoice {
    fn to_string(&self) -> String {
        "".into()
    }
}

/// Clear `Pyflow`'s cache. Allow the user to select which parts to clear based on a prompt.
fn clear(pyflow_path: &Path, cache_path: &Path, script_env_path: &Path) {
    let result = util::prompt_list(
        "Which cached items would you like to clear?",
        "choice",
        &[
            ("Downloaded dependencies".into(), ClearChoice::Dependencies),
            (
                "Standalone-script environments".into(),
                ClearChoice::ScriptEnvs,
            ),
            ("Python installations".into(), ClearChoice::PyInstalls),
            ("All of the above".into(), ClearChoice::All),
        ],
        false,
    );

    // todo: DRY
    match result.1 {
        ClearChoice::Dependencies => {
            if fs::remove_dir_all(&cache_path).is_err() {
                abort(&format!(
                    "Problem removing the dependency-cache path: {:?}",
                    cache_path
                ));
            }
        }
        ClearChoice::ScriptEnvs => {
            if fs::remove_dir_all(&script_env_path).is_err() {
                abort(&format!(
                    "Problem removing the script env path: {:?}",
                    script_env_path
                ));
            }
        }
        ClearChoice::PyInstalls => {}
        ClearChoice::All => {
            if fs::remove_dir_all(&pyflow_path).is_err() {
                abort(&format!(
                    "Problem removing the Pyflow path: {:?}",
                    pyflow_path
                ));
            }
        }
    }
}

/// We process input commands in a deliberate order, to ensure the required, and only the required
/// setup steps are accomplished before each.
fn main() {
    let cfg_filename = "pyproject.toml";
    let lock_filename = "pyflow.lock";

    let base_dir = directories::BaseDirs::new();
    let pyflow_path = base_dir
        .expect("Problem finding base directory")
        .data_dir()
        .to_owned()
        .join("pyflow");

    let dep_cache_path = pyflow_path.join("dependency-cache");
    let script_env_path = pyflow_path.join("script-envs");
    let git_path = pyflow_path.join("git");

    #[cfg(target_os = "windows")]
    let os = Os::Windows;
    #[cfg(target_os = "linux")]
    let os = Os::Linux;
    #[cfg(target_os = "macos")]
    let os = Os::Mac;

    let opt = Opt::from_args();
    #[cfg(debug_assertions)]
    eprintln!("opts {:?}", opt);
    // Handle color option
    let choice = match opt.color.unwrap_or_else(|| String::from("auto")).as_str() {
        "always" => ColorChoice::Always,
        "ansi" => ColorChoice::AlwaysAnsi,
        "auto" => {
            if atty::is(atty::Stream::Stdout) {
                ColorChoice::Auto
            } else {
                ColorChoice::Never
            }
        }
        _ => ColorChoice::Never,
    };

    CliConfig {
        color_choice: choice,
    }
    .make_current();

    // Handle commands that don't involve operating out of a project before one that do, with setup
    // code in-between.
    let subcmd = opt.subcmds;

    let extcmd = if let SubCommand::External(ref x) = subcmd {
        Some(ExternalCommand::from_opt(x.to_owned()))
    } else {
        None
    };

    // Run this before parsing the config.
    if let Some(x) = extcmd.clone() {
        if let ExternalSubcommands::Script = x.cmd {
            run_script(&script_env_path, &dep_cache_path, os, &x.args, &pyflow_path);
            return;
        }
    }

    if let SubCommand::New { name } = subcmd {
        if new(&name).is_err() {
            abort(
                "Problem creating the project. This may be due to a permissions problem. \
                 If on linux, please try again with `sudo`.",
            );
        }
        util::print_color(
            &format!("Created a new Python project named {}", name),
            Color::Green,
        );
        return;
    }

    if let SubCommand::Init {} = subcmd {
        let cfg_path = PathBuf::from(cfg_filename);
        if cfg_path.exists() {
            abort("pyproject.toml already exists - not overwriting.")
        }

        let mut cfg = match PathBuf::from("Pipfile").exists() {
            true => Config::from_pipfile(&PathBuf::from("Pipfile")).unwrap_or_default(),
            false => Config::default(),
        };

        cfg.py_version = Some(util::prompt_py_vers());

        files::parse_req_dot_text(&mut cfg, &PathBuf::from("requirements.txt"));

        cfg.write_file(&cfg_path);
        util::print_color("Created `pyproject.toml`", Color::Green);
        // Don't return here; let the normal logic create the venv now.
    }

    // We need access to the config from here on; throw an error if we can't find it.
    let mut cfg_path = PathBuf::from(cfg_filename);
    if !&cfg_path.exists() {
        //        if let SubCommand::Python { args: _ } = subcmd {
        // Try looking recursively in parent directories for a config file.
        let recursion_limit = 8; // How my levels to look up
        let mut current_level = env::current_dir().expect("Can't access current directory");
        for _ in 0..recursion_limit {
            if let Some(parent) = current_level.parent() {
                let parent_cfg_path = parent.join(cfg_filename);
                if parent_cfg_path.exists() {
                    cfg_path = parent_cfg_path;
                    break;
                }
                current_level = parent.to_owned();
            }
        }

        if !&cfg_path.exists() {
            // ie still can't find it after searching parents.
            util::print_color(
                "To get started, run `pyflow new projname` to create a project folder, or \
            `pyflow init` to start a project in this folder. For a list of what you can do, run \
            `pyflow help`.",
                Color::Cyan, // Dark
            );
            return;
        }
        //        }
    }

    // Base pypackages_path and lock_path on the `pyproject.toml` folder.
    let proj_path = cfg_path.parent().expect("Can't find proj pathw via parent");
    let pypackages_path = proj_path.join("__pypackages__");
    let lock_path = &proj_path.join(lock_filename);

    let mut cfg = Config::from_file(&cfg_path).unwrap_or_default();
    cfg.populate_path_subreqs();

    // Run subcommands that don't require info about the environment.
    match &subcmd {
        SubCommand::Reset {} => {
            if pypackages_path.exists() && fs::remove_dir_all(&pypackages_path).is_err() {
                abort("Problem removing `__pypackages__` directory")
            }
            if lock_path.exists() && fs::remove_file(&lock_path).is_err() {
                abort("Problem removing `pyflow.lock`")
            }
            util::print_color(
                "`__pypackages__` folder and `pyflow.lock` removed",
                Color::Green,
            );
            return;
        }
        SubCommand::Switch { version } => {
            // Updates `pyproject.toml` with a new python version
            let specified = util::fallible_v_parse(&version.clone());
            cfg.py_version = Some(specified.clone());
            files::change_py_vers(&PathBuf::from(&cfg_path), &specified);
            util::print_color(
                &format!("Switched to Python version {}", specified.to_string()),
                Color::Green,
            );
            // Don't return; now that we've changed the cfg version, let's run the normal flow.
        }
        SubCommand::Clear {} => {
            clear(&pyflow_path, &dep_cache_path, &script_env_path);
            return;
        }
        SubCommand::List => {
            let num_venvs = util::find_venvs(&pypackages_path).len();
            if !cfg_path.exists() && num_venvs == 0 {
                abort("Can't find a project in this directory")
            } else if num_venvs == 0 {
                util::print_color(
                    "There's no python environment set up for this project",
                    Color::Green,
                );
                return;
            }
        }
        _ => (),
    }

    let cfg_vers = if let Some(v) = cfg.py_version.clone() {
        v
    } else {
        let specified = util::prompt_py_vers();

        if !cfg_path.exists() {
            cfg.write_file(&cfg_path);
        }
        files::change_py_vers(&cfg_path, &specified);

        specified
    };

    // Check for environments. Create one if none exist. Set `vers_path`.
    let (vers_path, py_vers) =
        util::find_or_create_venv(&cfg_vers, &pypackages_path, &pyflow_path, &dep_cache_path);

    let paths = util::Paths {
        bin: util::find_bin_path(&vers_path),
        lib: vers_path.join("lib"),
        entry_pt: vers_path.join("bin"),
        cache: dep_cache_path,
    };

    // Add all path reqs to the PYTHONPATH; this is the way we make these packages accessible when
    // running `pyflow`.
    let mut pythonpath = vec![paths.lib.clone()];
    for r in cfg.reqs.iter().filter(|r| r.path.is_some()) {
        pythonpath.push(PathBuf::from(r.path.clone().unwrap()));
    }
    for r in cfg.dev_reqs.iter().filter(|r| r.path.is_some()) {
        pythonpath.push(PathBuf::from(r.path.clone().unwrap()));
    }

    let mut found_lock = false;
    let lock = match read_lock(&lock_path) {
        Ok(l) => {
            found_lock = true;
            l
        }
        Err(_) => Lock::default(),
    };

    let lockpacks = lock.package.unwrap_or_else(Vec::new);

    sync(
        &paths,
        &lockpacks,
        &cfg.reqs,
        &cfg.dev_reqs,
        &util::find_dont_uninstall(&cfg.reqs, &cfg.dev_reqs),
        os,
        &py_vers,
        &lock_path,
    );

    // Now handle subcommands that require info about the environment
    match subcmd {
        // Add pacakge names to `pyproject.toml` if needed. Then sync installed packages
        // and `pyproject.lock` with the `pyproject.toml`.
        // We use data from three sources: `pyproject.toml`, `pyflow.lock`, and
        // the currently-installed packages, found by crawling metadata in the `lib` path.
        // See the readme section `How installation and locking work` for details.
        SubCommand::Install { packages, dev } => {
            if !cfg_path.exists() {
                cfg.write_file(&cfg_path);
            }

            if found_lock {
                util::print_color("Found lockfile", Color::Green);
            }

            // Merge reqs added via cli with those in `pyproject.toml`.
            let (updated_reqs, up_dev_reqs) = util::merge_reqs(&packages, dev, &cfg, &cfg_path);

            let dont_uninstall = util::find_dont_uninstall(&updated_reqs, &up_dev_reqs);

            // git_reqs is used to store requirements from packages installed via git.
            let mut git_reqs = vec![]; // For path reqs too.
            let mut git_reqs_dev = vec![];
            for req in updated_reqs.iter().filter(|r| r.git.is_some()) {
                // todo: as_ref() would be better than clone, if we can get it working.
                let mut metadata = install::download_and_install_git(
                    &req.name,
                    //                    util::GitPath::Git(req.git.clone().unwrap()),
                    &req.git.clone().unwrap(),
                    &git_path,
                    &paths,
                );

                git_reqs.append(&mut metadata.requires_dist);
            }

            // todo: lots of DRY between reqs and dev reqs
            for req in up_dev_reqs.iter().filter(|r| r.git.is_some()) {
                let mut metadata = install::download_and_install_git(
                    &req.name,
                    //                    util::GitPath::Git(req.git.clone().unwrap()),
                    &req.git.clone().unwrap(),
                    &git_path,
                    &paths,
                );

                git_reqs_dev.append(&mut metadata.requires_dist);
            }

            // We don't pass the git requirement itself, since we've directly installed it,
            // but we do pass its requirements.
            let mut updated_reqs: Vec<Req> = updated_reqs
                .into_iter()
                .filter(|r| r.git.is_none() && r.path.is_none())
                .collect();
            let mut up_dev_reqs: Vec<Req> = up_dev_reqs
                .into_iter()
                .filter(|r| r.git.is_none() && r.path.is_none())
                .collect();

            for r in git_reqs {
                updated_reqs.push(r);
            }
            for r in git_reqs_dev {
                up_dev_reqs.push(r);
            }

            sync(
                &paths,
                &lockpacks,
                &updated_reqs,
                &up_dev_reqs,
                &dont_uninstall,
                os,
                &py_vers,
                &lock_path,
            );
            util::print_color("Installation complete", Color::Green);
        }

        SubCommand::Uninstall { packages } => {
            // todo: uninstall dev?
            // Remove dependencies specified in the CLI from the config, then lock and sync.

            let removed_reqs: Vec<String> = packages
                .into_iter()
                .map(|p| {
                    Req::from_str(&p, false)
                        .expect("Problem parsing req while uninstalling")
                        .name
                })
                .collect();

            files::remove_reqs_from_cfg(&cfg_path, &removed_reqs);

            // Filter reqs here instead of re-reading the config from file.
            let updated_reqs: Vec<Req> = cfg
                .clone()
                .reqs
                .into_iter()
                .filter(|req| !removed_reqs.contains(&req.name))
                .collect();

            sync(
                &paths,
                &lockpacks,
                &updated_reqs,
                &cfg.dev_reqs,
                &[],
                os,
                &py_vers,
                &lock_path,
            );
            util::print_color("Uninstall complete", Color::Green);
        }

        SubCommand::Package { extras } => {
            sync(
                &paths,
                &lockpacks,
                &cfg.reqs,
                &cfg.dev_reqs,
                &util::find_dont_uninstall(&cfg.reqs, &cfg.dev_reqs),
                os,
                &py_vers,
                &lock_path,
            );

            build::build(&lockpacks, &paths, &cfg, &extras)
        }
        SubCommand::Publish {} => build::publish(&paths.bin, &cfg),

        //        SubCommand::M { args } => {
        //            run_cli_tool(&paths.lib, &paths.bin, &vers_path, &cfg, args);
        //        }
        SubCommand::List {} => util::show_installed(
            &paths.lib,
            &[cfg.reqs.as_slice(), cfg.dev_reqs.as_slice()]
                .concat()
                .into_iter()
                .filter(|r| r.path.is_some())
                .collect::<Vec<Req>>(),
        ),
        _ => (),
    }

    if let Some(x) = extcmd {
        match x.cmd {
            ExternalSubcommands::Python => {
                if commands::run_python(&paths.bin, &pythonpath, &x.args).is_err() {
                    abort("Problem running Python");
                }
            }
            ExternalSubcommands::Run => {
                run_cli_tool(&paths.lib, &paths.bin, &vers_path, &cfg, x.args);
            }
            x => {
                abort(&format!(
                    "Sub command {:?} should have been handled already",
                    x
                ));
            }
        }
    }
}

#[cfg(test)]
pub mod tests {}