/
main.rs
1617 lines (1441 loc) · 54.1 KB
/
main.rs
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
#![allow(clippy::non_ascii_literal)]
use crate::dep_types::{Constraint, Lock, LockPackage, Package, Rename, Req, ReqType, Version};
use crate::util::{abort, Os};
use crossterm::{Color, Colored};
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 structopt::StructOpt;
mod build;
mod commands;
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: Option<SubCommand>,
#[structopt(name = "script")]
// #[structopt(raw(setting = "structopt::clap::AppSettings::TrailingVarArg"))]
script: Vec<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>,
},
/// Run python
#[structopt(name = "python")]
Python {
#[structopt(name = "args")]
args: 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.
#[structopt(name = "run")] // We don't need to invoke this directly, but the option exists
Run {
#[structopt(name = "args")]
args: Vec<String>,
},
/// Run a standalone script not associated with a project
#[structopt(name = "script")]
Script {
#[structopt(name = "args")]
args: Vec<String>,
},
// /// 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,
},
}
/// 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 {
python_version = Some(
Constraint::from_str(&v)
.expect("Problem parsing python version in dependency"),
);
}
}
}
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 {
python_version = Some(
Constraint::from_str(&v)
.expect("Problem parsing python version in dependency"),
);
}
// todo repository etc
}
}
if &name.to_lowercase() == "python" {
if let Some(constr) = constraints.get(0) {
result.py_version = Some(constr.version)
}
} 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 =
"# See PEP 518: https://www.python.org/dev/peps/pep-0518/ for info on this \
file's structure.\n"
.to_string();
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.7\"".to_owned() + "\n"));
}
if let Some(vers) = self.version {
result.push_str(&(format!("version = \"{}\"", vers.to_string2()) + "\n"));
} else {
result.push_str("version = \"0.1.0\"");
result.push_str("\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_str("\n\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_str("\n\n");
result.push_str("[tool.pyflow.dependencies]\n");
for dep in &self.reqs {
result.push_str(&(dep.to_cfg_string() + "\n"));
}
result.push_str("\n\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_str("\n"); // trailing newline
if fs::write(file, result).is_err() {
abort("Problem writing `pyproject.toml`")
}
}
}
/// 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 mut cfg = Config::default();
cfg.authors = util::get_git_author();
cfg.py_version = Some(util::prompt_py_vers());
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::DarkYellow,
);
};
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"),
),
match &lp.rename {
// todo back to our custom type?
Some(rn) => Some(parse_lockpack_rename(rn)),
None => None,
},
)
})
.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))
.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);
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 = dep_resolution::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")]
println!(
"Installing {}{}{} {} ...",
Colored::Fg(Color::Cyan),
&name,
Colored::Fg(Color::Reset),
&version
);
#[cfg(target_os = "linux")]
println!(
"⬇ Installing {}{}{} {} ...",
Colored::Fg(Color::Cyan),
&name,
Colored::Fg(Color::Reset),
&version
);
#[cfg(target_os = "macos")]
println!(
"⬇ Installing {}{}{} {} ...",
Colored::Fg(Color::Cyan),
&name,
Colored::Fg(Color::Reset),
&version
);
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_string2())),
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() {
if let Ok(l) = line {
if let Some(c) = re.captures(&l) {
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("'", "")
})
.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: &mut Vec<String>,
pyflow_dir: &Path,
) {
// todo: DRY with run_cli_tool and subcommand::Install
let filename = if let Some(a) = args.get(0) {
a.clone()
} else {
abort("`run` 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 = script_env_path.join(&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_string2())
.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(),
};