-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmod.rs
More file actions
1806 lines (1650 loc) · 57.6 KB
/
Copy pathmod.rs
File metadata and controls
1806 lines (1650 loc) · 57.6 KB
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
use std::collections::{HashMap, HashSet};
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::SystemTime;
use color_eyre::{
Section,
{
eyre::{eyre, WrapErr},
Result,
},
};
use fs_err as fs;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tracing::{debug, info, instrument, warn};
use walkdir::WalkDir;
use zip::write::FileOptions;
use kinode_process_lib::{kernel_types::Erc721Metadata, PackageId};
use crate::publish::make_local_file_link_path;
use crate::run_tests::types::BroadcastRecvBool;
use crate::setup::{
check_js_deps, check_py_deps, check_rust_deps, get_deps, get_newest_valid_node_version,
get_python_version, REQUIRED_PY_PACKAGE,
};
use crate::view_api;
use crate::KIT_CACHE;
mod rewrite;
use rewrite::copy_and_rewrite_package;
const PY_VENV_NAME: &str = "process_env";
const JAVASCRIPT_SRC_PATH: &str = "src/lib.js";
const PYTHON_SRC_PATH: &str = "src/lib.py";
const RUST_SRC_PATH: &str = "src/lib.rs";
const PACKAGE_JSON_NAME: &str = "package.json";
const COMPONENTIZE_MJS_NAME: &str = "componentize.mjs";
const KINODE_WIT_0_7_0_URL: &str =
"https://raw.githubusercontent.com/kinode-dao/kinode-wit/aa2c8b11c9171b949d1991c32f58591c0e881f85/kinode.wit";
const KINODE_WIT_0_8_0_URL: &str =
"https://raw.githubusercontent.com/kinode-dao/kinode-wit/v0.8/kinode.wit";
const KINODE_WIT_1_0_0_URL: &str =
"https://raw.githubusercontent.com/kinode-dao/kinode-wit/v1.0.0/kinode.wit";
const WASI_VERSION: &str = "27.0.0"; // TODO: un-hardcode
const DEFAULT_WORLD_0_7_0: &str = "process";
const DEFAULT_WORLD_0_8_0: &str = "process-v0";
const DEFAULT_WORLD_1_0_0: &str = "process-v1";
const KINODE_PROCESS_LIB_CRATE_NAME: &str = "kinode_process_lib";
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CargoFile {
package: CargoPackage,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CargoPackage {
name: String,
}
pub fn make_fake_kill_chan() -> BroadcastRecvBool {
let (_send_to_kill, recv_kill) = tokio::sync::broadcast::channel(1);
recv_kill
}
pub fn make_pkg_publisher(metadata: &Erc721Metadata) -> String {
let package_name = metadata.properties.package_name.as_str();
let publisher = metadata.properties.publisher.as_str();
let pkg_publisher = format!("{}:{}", package_name, publisher);
pkg_publisher
}
pub fn make_zip_filename(package_dir: &Path, pkg_publisher: &str) -> PathBuf {
let zip_filename = package_dir
.join("target")
.join(pkg_publisher)
.with_extension("zip");
zip_filename
}
#[instrument(level = "trace", skip_all)]
pub fn hash_zip_pkg(zip_path: &Path) -> Result<String> {
let mut file = fs::File::open(&zip_path)?;
let mut hasher = Sha256::new();
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
hasher.update(&buffer);
let hash_result = hasher.finalize();
Ok(format!("{hash_result:x}"))
}
#[instrument(level = "trace", skip_all)]
pub fn zip_pkg(package_dir: &Path, pkg_publisher: &str) -> Result<(PathBuf, String)> {
let pkg_dir = package_dir.join("pkg");
let target_dir = package_dir.join("target");
fs::create_dir_all(&target_dir)?;
let zip_filename = make_zip_filename(package_dir, pkg_publisher);
zip_directory(&pkg_dir, &zip_filename.to_str().unwrap())?;
let hash = hash_zip_pkg(&zip_filename)?;
Ok((zip_filename, hash))
}
#[instrument(level = "trace", skip_all)]
fn zip_directory(directory: &Path, zip_filename: &str) -> Result<()> {
let file = fs::File::create(zip_filename)?;
let mut zip = zip::ZipWriter::new(file);
let options = FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.unix_permissions(0o755)
.last_modified_time(zip::DateTime::from_date_and_time(2023, 6, 19, 0, 0, 0).unwrap());
let mut walk_dir = WalkDir::new(directory)
.into_iter()
.filter_map(|entry| entry.ok())
.collect::<Vec<_>>();
walk_dir.sort_by_key(|entry| entry.path().to_owned());
for entry in walk_dir {
let path = entry.path();
let name = path.strip_prefix(Path::new(directory))?;
if path.is_file() {
zip.start_file(name.to_string_lossy(), options)?;
let mut f = fs::File::open(path)?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
zip.write_all(&*buffer)?;
} else if name.as_os_str().len() != 0 {
// Only if it is not the root directory
zip.add_directory(name.to_string_lossy(), options)?;
}
}
zip.finish()?;
Ok(())
}
#[instrument(level = "trace", skip_all)]
pub fn has_feature(cargo_toml_path: &str, feature: &str) -> Result<bool> {
let cargo_toml_content = fs::read_to_string(cargo_toml_path)?;
let cargo_toml: toml::Value = cargo_toml_content.parse()?;
if let Some(features) = cargo_toml.get("features").and_then(|f| f.as_table()) {
Ok(features.contains_key(feature))
} else {
Ok(false)
}
}
#[instrument(level = "trace", skip_all)]
pub fn remove_missing_features(cargo_toml_path: &Path, features: Vec<&str>) -> Result<Vec<String>> {
let cargo_toml_content = fs::read_to_string(cargo_toml_path)?;
let cargo_toml: toml::Value = cargo_toml_content.parse()?;
let Some(cargo_features) = cargo_toml.get("features").and_then(|f| f.as_table()) else {
return Ok(vec![]);
};
Ok(features
.iter()
.filter_map(|f| {
let f = f.to_string();
if cargo_features.contains_key(&f) {
Some(f)
} else {
None
}
})
.collect())
}
/// Check if the first element is empty and there are no more elements
#[instrument(level = "trace", skip_all)]
fn is_only_empty_string(splitted: &Vec<&str>) -> bool {
let mut parts = splitted.iter();
parts.next() == Some(&"") && parts.next().is_none()
}
#[instrument(level = "trace", skip_all)]
pub fn run_command(cmd: &mut Command, verbose: bool) -> Result<Option<(String, String)>> {
if verbose {
let mut child = cmd.spawn()?;
let result = child.wait()?;
if result.success() {
return Ok(None);
} else {
return Err(eyre!(
"Command `{} {:?}` failed with exit code {:?}",
cmd.get_program().to_str().unwrap(),
cmd.get_args()
.map(|a| a.to_str().unwrap())
.collect::<Vec<_>>(),
result.code(),
));
}
}
let output = match cmd.output() {
Ok(o) => o,
Err(e) => {
return Err(eyre!(
"Command `{} {:?}` failed with error {:?}",
cmd.get_program().to_str().unwrap(),
cmd.get_args()
.map(|a| a.to_str().unwrap())
.collect::<Vec<_>>(),
e,
));
}
};
if output.status.success() {
Ok(Some((
String::from_utf8_lossy(&output.stdout).to_string(),
String::from_utf8_lossy(&output.stderr).to_string(),
)))
} else {
Err(eyre!(
"Command `{} {:?}` failed with exit code {:?}\nstdout: {}\nstderr: {}",
cmd.get_program().to_str().unwrap(),
cmd.get_args()
.map(|a| a.to_str().unwrap())
.collect::<Vec<_>>(),
output.status.code(),
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
))
}
}
#[instrument(level = "trace", skip_all)]
pub async fn download_file(url: &str, path: &Path) -> Result<()> {
fs::create_dir_all(&KIT_CACHE)?;
let mut hasher = Sha256::new();
hasher.update(url.as_bytes());
let hashed_url = hasher.finalize();
let hashed_url_path = Path::new(KIT_CACHE).join(format!("{hashed_url:x}"));
let content = if hashed_url_path.exists() {
fs::read(hashed_url_path)?
} else {
let response = reqwest::get(url).await?;
// Check if response status is 200 (OK)
if response.status() != reqwest::StatusCode::OK {
return Err(eyre!(
"Failed to download file: HTTP Status {}",
response.status()
));
}
let content = response.bytes().await?.to_vec();
fs::write(hashed_url_path, &content)?;
content
};
if path.exists() {
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
let existing_content = fs::read(path)?;
if content == existing_content {
return Ok(());
}
}
}
fs::create_dir_all(
path.parent()
.ok_or_else(|| eyre!("path doesn't have parent"))?,
)?;
fs::write(path, &content)?;
Ok(())
}
#[instrument(level = "trace", skip_all)]
pub fn read_metadata(package_dir: &Path) -> Result<Erc721Metadata> {
let metadata: Erc721Metadata =
serde_json::from_reader(fs::File::open(package_dir.join("metadata.json"))
.wrap_err_with(|| "Missing required metadata.json file. See discussion at https://book.kinode.org/my_first_app/chapter_1.html?highlight=metadata.json#metadatajson")?
)?;
Ok(metadata)
}
#[instrument(level = "trace", skip_all)]
pub fn read_and_update_metadata(package_dir: &Path) -> Result<Erc721Metadata> {
let mut metadata = read_metadata(package_dir)?;
let metadata_dot_json =
make_local_file_link_path(&package_dir.join("metadata.json"), "metadata.json")?;
let current_version_field = semver::Version::parse(&metadata.properties.current_version)?;
let most_recent_version: semver::Version = metadata
.properties
.code_hashes
.keys()
.filter_map(|s| semver::Version::parse(&s).ok())
.max()
.ok_or_else(|| eyre!("{metadata_dot_json} doesn't list versions"))?;
if most_recent_version == current_version_field {
// we're up-to-date: don't edit
} else if most_recent_version > current_version_field {
// we're out-of-date: update
replace_version_in_file(
&package_dir.join("metadata.json"),
r#"("current_version":\s*")(\d+\.\d+\.\d+)"#,
&format!(r#"${{1}}{most_recent_version}"#),
)?;
metadata = read_metadata(package_dir)?;
} else {
// unexpected case: error
return Err(eyre!(
"{} has a current_version ({}) that does not exist: newest listed version {}",
metadata_dot_json,
current_version_field,
most_recent_version,
));
}
Ok(metadata)
}
fn replace_version_in_file(file_path: &Path, pattern: &str, new_version: &str) -> Result<()> {
let file = fs::File::open(&file_path)?;
let reader = std::io::BufReader::new(file);
let mut content = String::new();
let version_regex = regex::Regex::new(pattern).unwrap();
for line in reader.lines() {
let line = line?;
let new_line = if version_regex.is_match(&line) {
version_regex.replace(&line, new_version).to_string()
} else {
line
};
content.push_str(&new_line);
content.push('\n');
}
fs::write(file_path, content.as_bytes())?;
Ok(())
}
/// Regex to dynamically capture the world name after 'world'
fn extract_world(data: &str) -> Option<String> {
let re = regex::Regex::new(r"world\s+([^\s\{]+)").unwrap();
re.captures(data)
.and_then(|caps| caps.get(1).map(|match_| match_.as_str().to_string()))
}
fn extract_worlds_from_files(directory: &Path) -> Vec<String> {
let mut worlds = vec![];
// Safe to return early if directory reading fails
let entries = match fs::read_dir(directory) {
Ok(entries) => entries,
Err(_) => return worlds,
};
for entry in entries.filter_map(Result::ok) {
let path = entry.path();
if !path.is_file()
|| Some("kinode.wit") == path.file_name().and_then(|s| s.to_str())
|| Some("wit") != path.extension().and_then(|s| s.to_str())
{
continue;
}
let contents = fs::read_to_string(&path).unwrap_or_default();
if let Some(world) = extract_world(&contents) {
worlds.push(world);
}
}
worlds
}
fn get_world_or_default(directory: &Path, default_world: &str) -> String {
let worlds = extract_worlds_from_files(directory);
if worlds.len() == 1 {
return worlds[0].clone();
}
warn!(
"Found {} worlds in {directory:?}; defaulting to {default_world}",
worlds.len()
);
default_world.to_string()
}
#[instrument(level = "trace", skip_all)]
fn copy_dir(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
if !dst.exists() {
fs::create_dir_all(dst)?;
}
for entry in fs::read_dir(src)? {
let entry = entry?;
let src_path = entry.path();
let dst_path = dst.join(entry.file_name());
if src_path.is_dir() {
copy_dir(&src_path, &dst_path)?;
} else {
fs::copy(&src_path, &dst_path)?;
}
}
Ok(())
}
fn file_with_extension_exists(dir: &Path, extension: &str) -> bool {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.filter_map(Result::ok) {
let path = entry.path();
if path.is_file() && path.extension().and_then(|ext| ext.to_str()) == Some(extension) {
return true;
}
}
}
false
}
#[instrument(level = "trace", skip_all)]
fn parse_version_from_url(url: &str) -> Result<semver::VersionReq> {
let re = regex::Regex::new(r"\?tag=v([0-9]+\.[0-9]+\.[0-9]+)$").unwrap();
if let Some(caps) = re.captures(url) {
if let Some(version) = caps.get(1) {
return Ok(semver::VersionReq::parse(&format!(
"^{}",
version.as_str()
))?);
}
}
Err(eyre!("No valid version found in the URL"))
}
#[instrument(level = "trace", skip_all)]
fn find_crate_versions(
crate_name: &str,
packages: &HashMap<cargo_metadata::PackageId, &cargo_metadata::Package>,
) -> Result<HashMap<semver::VersionReq, Vec<String>>> {
let mut versions = HashMap::new();
// Iterate over all packages
for package in packages.values() {
// Check each dependency of the package
for dependency in &package.dependencies {
if dependency.name == crate_name {
let version = if dependency.req != semver::VersionReq::default() {
dependency.req.clone()
} else {
if let Some(ref source) = dependency.source {
match parse_version_from_url(source) {
Ok(v) => v,
Err(e) => {
warn!("Error parsing import version: {e}");
continue;
}
}
} else {
semver::VersionReq::default()
}
};
versions
.entry(version)
.or_insert_with(Vec::new)
.push(package.name.clone());
}
}
}
Ok(versions)
}
#[instrument(level = "trace", skip_all)]
fn check_process_lib_version(cargo_toml_path: &Path) -> Result<()> {
let metadata = match cargo_metadata::MetadataCommand::new()
.manifest_path(cargo_toml_path)
.exec()
{
Ok(m) => m,
Err(_) => {
warn!(
"Couldn't find Cargo.toml where expected: {:?}; continuing.",
cargo_toml_path,
);
return Ok(());
}
};
let packages: HashMap<cargo_metadata::PackageId, &cargo_metadata::Package> = metadata
.packages
.iter()
.map(|package| (package.id.clone(), package))
.collect();
let versions = find_crate_versions(KINODE_PROCESS_LIB_CRATE_NAME, &packages)?;
if versions.len() > 1 {
return Err(eyre!(
"Found different versions of {} in different crates:{}",
KINODE_PROCESS_LIB_CRATE_NAME,
versions.iter().fold(String::new(), |s, (version, crates)| {
format!("{s}\n{version}\t{crates:?}")
})
)
.with_suggestion(|| {
format!(
"Set all {} versions to be the same to avoid hard-to-debug errors.",
KINODE_PROCESS_LIB_CRATE_NAME,
)
}));
}
Ok(())
}
/// Scans all .rs files in a directory recursively and returns the most recent
/// modification time of any included file
pub fn get_latest_include_mod_time<P: AsRef<Path>>(dir: P) -> Result<Option<SystemTime>> {
let includes = scan_includes(dir)?;
let mut latest_time = None;
for path in includes {
match get_file_modified_time(&path) {
Ok(mod_time) => {
latest_time = Some(match latest_time {
Some(current_latest) => std::cmp::max(current_latest, mod_time),
None => mod_time,
});
}
Err(e) => warn!("Could not get modification time for {path:?}: {e}"),
}
}
Ok(latest_time)
}
/// Scans all .rs files in a directory recursively and returns arguments
/// to include!, include_str!, and include_bytes! macros
#[instrument(level = "trace", skip_all)]
pub fn scan_includes<P: AsRef<Path>>(dir: P) -> Result<Vec<PathBuf>> {
let mut includes = Vec::new();
let include_regex =
regex::Regex::new(r#"(?:include|include_str|include_bytes)!\s*\(\s*"([^"]+)"\s*\)"#)?;
// Recursively walk directory
visit_dirs(dir.as_ref(), &include_regex, &mut includes)?;
Ok(includes)
}
#[instrument(level = "trace", skip_all)]
fn visit_dirs(dir: &Path, regex: ®ex::Regex, includes: &mut Vec<PathBuf>) -> Result<()> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_dirs(&path, regex, includes)?;
} else if let Some(ext) = path.extension() {
if ext == "rs" {
scan_file(&path, regex, includes)?;
}
}
}
}
Ok(())
}
#[instrument(level = "trace", skip_all)]
fn scan_file(file: &Path, regex: ®ex::Regex, includes: &mut Vec<PathBuf>) -> Result<()> {
let contents = fs::read_to_string(file)?;
for cap in regex.captures_iter(&contents) {
if let Some(path) = cap.get(1) {
includes.push(file.parent().unwrap().join(path.as_str()));
}
}
Ok(())
}
#[instrument(level = "trace", skip_all)]
fn get_most_recent_modified_time(
dir: &Path,
exclude_files: &HashSet<&str>,
exclude_extensions: &HashSet<&str>,
exclude_dirs: &HashSet<&str>,
must_exist_dirs: &mut HashSet<&str>,
is_recursion: bool,
) -> Result<(Option<SystemTime>, Option<SystemTime>)> {
let mut most_recent: Option<SystemTime> = None;
let mut most_recent_excluded: Option<SystemTime> = None;
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
let file_name = path
.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default();
if exclude_files.contains(file_name) {
let file_time = get_file_modified_time(&path)?;
most_recent_excluded =
Some(most_recent_excluded.map_or(file_time, |t| t.max(file_time)));
continue;
}
if path.is_dir() {
let dir_name = path
.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default();
must_exist_dirs.remove(dir_name);
if exclude_dirs.contains(dir_name) {
continue;
}
let (sub_time, sub_time_excluded) = get_most_recent_modified_time(
&path,
exclude_files,
exclude_extensions,
exclude_dirs,
must_exist_dirs,
true,
)?;
if let Some(st) = sub_time {
most_recent = Some(most_recent.map_or(st, |t| t.max(st)));
}
if let Some(ste) = sub_time_excluded {
most_recent_excluded = Some(most_recent_excluded.map_or(ste, |t| t.max(ste)));
}
} else {
if let Some(extension) = path.extension() {
if exclude_extensions.contains(&extension.to_str().unwrap_or_default()) {
let file_time = get_file_modified_time(&path)?;
most_recent_excluded =
Some(most_recent_excluded.map_or(file_time, |t| t.max(file_time)));
continue;
}
}
let file_time = get_file_modified_time(&path)?;
most_recent = Some(most_recent.map_or(file_time, |t| t.max(file_time)));
}
}
if !is_recursion && !must_exist_dirs.is_empty() {
return Err(eyre!("Didn't find required dirs: {must_exist_dirs:?}"));
}
debug!("get_most_recent_modified_time: most_recent: {most_recent:?}, most_recent_excluded: {most_recent_excluded:?}");
Ok((most_recent, most_recent_excluded))
}
#[instrument(level = "trace", skip_all)]
fn get_file_modified_time(file_path: &Path) -> Result<SystemTime> {
let metadata = fs::metadata(file_path)?;
Ok(metadata.modified()?)
}
#[instrument(level = "trace", skip_all)]
fn get_cargo_package_path(package: &cargo_metadata::Package) -> Result<PathBuf> {
match package
.manifest_path
.parent()
.map(|p| p.as_std_path().to_path_buf())
{
Some(p) => Ok(p),
None => Err(eyre!(
"Cargo manifest path {} has no parent",
package.manifest_path
)),
}
}
#[instrument(level = "trace", skip_all)]
fn is_up_to_date(
build_with_features_path: &Path,
build_with_cludes_path: &Path,
features: &str,
cludes: &str,
package_dir: &Path,
) -> Result<bool> {
let old_features = fs::read_to_string(&build_with_features_path).ok();
let old_cludes = fs::read_to_string(&build_with_cludes_path).ok();
debug!(
"is_up_to_date({package_dir:?}):
old_features == Some(features.to_string()): {}
old_cludes == Some(cludes.to_string()): {}
package_dir.join(\"Cargo.lock\").exists(): {}
package_dir.join(\"pkg\").exists(): {}
package_dir.join(\"pkg\").join(\"api.zip\").exists(): {}
file_with_extension_exists(&package_dir.join(\"pkg\"), \"wasm\"): {}",
old_features == Some(features.to_string()),
old_cludes == Some(cludes.to_string()),
package_dir.join("Cargo.lock").exists(),
package_dir.join("pkg").exists(),
package_dir.join("pkg").join("api.zip").exists(),
file_with_extension_exists(&package_dir.join("pkg"), "wasm"),
);
if old_features == Some(features.to_string())
&& old_cludes == Some(cludes.to_string())
&& package_dir.join("Cargo.lock").exists()
&& package_dir.join("pkg").exists()
&& package_dir.join("pkg").join("api.zip").exists()
&& file_with_extension_exists(&package_dir.join("pkg"), "wasm")
{
let (mut source_time, build_time) = match get_most_recent_modified_time(
package_dir,
&HashSet::from(["Cargo.lock", "api.zip"]),
&HashSet::from(["wasm"]),
&HashSet::from(["target"]),
&mut HashSet::from(["target"]),
false,
) {
Ok(v) => v,
Err(e) => {
if e.to_string().starts_with("Didn't find required dirs:") {
debug!("is_up_to_date first {e}");
return Ok(false);
} else {
return Err(e);
}
}
};
let Some(build_time) = build_time else {
debug!("is_up_to_date: no built files: not up-to-date");
return Ok(false);
};
// update source to most recent of package_dir
// or package_dir's local deps
let metadata = cargo_metadata::MetadataCommand::new()
.manifest_path(package_dir.join("Cargo.toml"))
.exec()?;
for package in metadata.packages.iter().filter(|p| p.source.is_none()) {
let dep_package_dir = get_cargo_package_path(&package)?;
let (dep_source_time, _) = match get_most_recent_modified_time(
&dep_package_dir,
&HashSet::from(["Cargo.lock", "api.zip"]),
&HashSet::from(["wasm"]),
&HashSet::from(["target"]),
&mut HashSet::from(["target"]),
false,
) {
Ok(v) => v,
Err(e) => {
if e.to_string().starts_with("Didn't find required dirs:") {
debug!("is_up_to_date second {e}");
return Ok(false);
} else {
return Err(e);
}
}
};
// TODO: refactor source time updating along with get_latest_include_mode_time to map_or
match source_time {
None => source_time = dep_source_time,
Some(ref st) => {
if let Some(ref dst) = dep_source_time {
if dst.duration_since(st.clone()).is_ok() {
// dep has more recent changes than source
// -> update source_time to dep_source_time
source_time = dep_source_time;
}
}
}
}
}
// update source to most recent of above or include!s
let include_source_time = get_latest_include_mod_time(package_dir)?;
// TODO: refactor source time updating along with get_latest_include_mode_time to map_or
match source_time {
None => source_time = include_source_time,
Some(ref st) => {
if let Some(ref ist) = include_source_time {
if ist.duration_since(st.clone()).is_ok() {
// includes have more recent changes than source
// -> update source_time to include_source_time
source_time = include_source_time;
}
}
}
}
if let Some(source_time) = source_time {
if build_time.duration_since(source_time).is_ok() {
// build_time - source_time >= 0
// -> current build is up-to-date: don't rebuild
info!("Build up-to-date.");
return Ok(true);
}
}
}
Ok(false)
}
#[instrument(level = "trace", skip_all)]
async fn compile_javascript_wasm_process(
process_dir: &Path,
valid_node: Option<String>,
world: &str,
verbose: bool,
) -> Result<()> {
info!(
"Compiling Javascript Kinode process in {:?}...",
process_dir
);
let wasm_file_name = process_dir.file_name().and_then(|s| s.to_str()).unwrap();
let world_name = get_world_or_default(&process_dir.join("target").join("wit"), world);
let install = "npm install".to_string();
let componentize = format!("node componentize.mjs {wasm_file_name} {world_name}");
let (install, componentize) = valid_node
.map(|valid_node| {
(
format!(
"source ~/.nvm/nvm.sh && nvm use {} && {}",
valid_node, install
),
format!(
"source ~/.nvm/nvm.sh && nvm use {} && {}",
valid_node, componentize
),
)
})
.unwrap_or_else(|| (install, componentize));
run_command(
Command::new("bash")
.args(&["-c", &install])
.current_dir(process_dir),
verbose,
)?;
run_command(
Command::new("bash")
.args(&["-c", &componentize])
.current_dir(process_dir),
verbose,
)?;
info!(
"Done compiling Javascript Kinode process in {:?}.",
process_dir
);
Ok(())
}
#[instrument(level = "trace", skip_all)]
async fn compile_python_wasm_process(
process_dir: &Path,
python: &str,
world: &str,
verbose: bool,
) -> Result<()> {
info!("Compiling Python Kinode process in {:?}...", process_dir);
let wasm_file_name = process_dir.file_name().and_then(|s| s.to_str()).unwrap();
let world_name = get_world_or_default(&process_dir.join("target").join("wit"), world);
let source = format!("source ../{PY_VENV_NAME}/bin/activate");
let install = format!("pip install {REQUIRED_PY_PACKAGE}");
let componentize = format!(
"componentize-py -d ../target/wit/ -w {} componentize lib -o ../../pkg/{}.wasm",
world_name, wasm_file_name,
);
run_command(
Command::new(python)
.args(&["-m", "venv", PY_VENV_NAME])
.current_dir(process_dir),
verbose,
)?;
run_command(
Command::new("bash")
.args(&["-c", &format!("{source} && {install} && {componentize}")])
.current_dir(process_dir.join("src")),
verbose,
)?;
info!("Done compiling Python Kinode process in {:?}.", process_dir);
Ok(())
}
#[instrument(level = "trace", skip_all)]
async fn compile_rust_wasm_process(
process_dir: &Path,
features: &str,
verbose: bool,
) -> Result<()> {
info!("Compiling Rust Kinode process in {:?}...", process_dir);
// Paths
let wit_dir = process_dir.join("target").join("wit");
let bindings_dir = process_dir
.join("target")
.join("bindings")
.join(process_dir.file_name().unwrap());
fs::create_dir_all(&bindings_dir)?;
// Check and download wasi_snapshot_preview1.wasm if it does not exist
let wasi_snapshot_file = process_dir
.join("target")
.join("wasi_snapshot_preview1.wasm");
let wasi_snapshot_url = format!(
"https://github.com/bytecodealliance/wasmtime/releases/download/v{}/wasi_snapshot_preview1.reactor.wasm",
WASI_VERSION,
);
download_file(&wasi_snapshot_url, &wasi_snapshot_file).await?;
// Copy wit directory to bindings
fs::create_dir_all(&bindings_dir.join("wit"))?;
for entry in fs::read_dir(&wit_dir)? {
let entry = entry?;
fs::copy(
entry.path(),
bindings_dir.join("wit").join(entry.file_name()),
)?;
}
// Build the module using Cargo
let mut args = vec![
"+nightly",
"build",
"--release",
"--no-default-features",
"--target",
"wasm32-wasip1",
"--target-dir",
"target",
"--color=always",
];
let test_only = features == "test";
let features: Vec<&str> = features.split(',').collect();
let original_length = if is_only_empty_string(&features) {
0
} else {
features.len()
};
let features = remove_missing_features(&process_dir.join("Cargo.toml"), features)?;
if !test_only && original_length != features.len() {
info!(
"process {:?} missing features; using {:?}",
process_dir, features
);
};
let features = features.join(",");
if !features.is_empty() {
args.push("--features");
args.push(&features);
}
let result = run_command(
Command::new("cargo").args(&args).current_dir(process_dir),
verbose,
)?;
if let Some((stdout, stderr)) = result {
if stdout.contains("warning") {
warn!("{}", stdout);
}
if stderr.contains("warning") {
warn!("{}", stderr);
}
}
// Adapt the module using wasm-tools
// For use inside of process_dir
// Run `wasm-tools component new`, putting output in pkg/
// and rewriting all `_`s to `-`s
// cargo hates `-`s and so outputs with `_`s; Kimap hates
// `_`s and so we convert to and enforce all `-`s
let wasm_file_name_cab = process_dir
.file_name()
.and_then(|s| s.to_str())
.unwrap()
.replace("-", "_");
let wasm_file_name_hep = wasm_file_name_cab.replace("_", "-");
let wasm_file_prefix = Path::new("target/wasm32-wasip1/release");
let wasm_file_cab = wasm_file_prefix.join(&format!("{wasm_file_name_cab}.wasm"));
let wasm_file_pkg = format!("../pkg/{wasm_file_name_hep}.wasm");
let wasm_file_pkg = Path::new(&wasm_file_pkg);
let wasi_snapshot_file = Path::new("target/wasi_snapshot_preview1.wasm");