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
use anyhow::{anyhow, Result};
use cid::Cid;
use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
use libipld_cbor::DagCborCodec;
use noosphere_core::{
authority::{restore_ed25519_key, Author, Authorization},
data::{BodyChunkIpld, ContentType, Did, Header, MemoIpld},
view::Sphere,
};
use noosphere_fs::SphereFs;
use noosphere_storage::{
db::SphereDb,
interface::{BlockStore, Store},
native::{NativeStorageInit, NativeStorageProvider, NativeStore},
};
use pathdiff::diff_paths;
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
str::FromStr,
};
use subtext::util::to_slug;
use tokio::{
fs::{self, File},
io::copy,
};
use tokio_stream::StreamExt;
use ucan_key_support::ed25519::Ed25519KeyMaterial;
use url::Url;
use super::commands::config::{Config, ConfigContents};
const NOOSPHERE_DIRECTORY: &str = ".noosphere";
const SPHERE_DIRECTORY: &str = ".sphere";
const BLOCKS_DIRECTORY: &str = "blocks";
const KEYS_DIRECTORY: &str = "keys";
const AUTHORIZATION_FILE: &str = "AUTHORIZATION";
const KEY_FILE: &str = "KEY";
const IDENTITY_FILE: &str = "IDENTITY";
const CONFIG_FILE: &str = "config.toml";
#[derive(Default)]
pub struct ContentChanges {
pub new: BTreeMap<String, Option<ContentType>>,
pub updated: BTreeMap<String, Option<ContentType>>,
pub removed: BTreeMap<String, Option<ContentType>>,
pub unchanged: BTreeSet<String>,
}
impl ContentChanges {
pub fn is_empty(&self) -> bool {
self.new.is_empty() && self.updated.is_empty() && self.removed.is_empty()
}
}
#[derive(Default)]
pub struct Content {
pub matched: BTreeMap<String, FileReference>,
pub ignored: BTreeSet<String>,
}
impl Content {
pub fn is_empty(&self) -> bool {
self.matched.is_empty()
}
}
pub struct FileReference {
pub cid: Cid,
pub content_type: ContentType,
pub extension: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Workspace {
root: PathBuf,
sphere: PathBuf,
blocks: PathBuf,
noosphere: PathBuf,
keys: PathBuf,
authorization: PathBuf,
key: PathBuf,
identity: PathBuf,
config: PathBuf,
}
impl Workspace {
pub async fn read_local_content<S: BlockStore>(
&self,
pattern: Option<GlobMatcher>,
store: &mut S,
) -> Result<Content> {
self.expect_local_directories()?;
let root_path = self.root_path();
let mut directories = vec![(None, tokio::fs::read_dir(root_path).await?)];
let ignore_patterns = self.get_ignored_patterns().await?;
let mut content = Content::default();
while let Some((slug_prefix, mut directory)) = directories.pop() {
while let Some(entry) = directory.next_entry().await? {
let path = entry.path();
let relative_path = diff_paths(&path, root_path)
.ok_or_else(|| anyhow!("Could not determine relative path to {:?}", path))?;
if ignore_patterns.is_match(&relative_path) {
continue;
}
if path.is_dir() {
let slug_prefix = relative_path.to_string_lossy().to_string();
directories.push((Some(slug_prefix), tokio::fs::read_dir(path).await?));
continue;
}
let mut ignored = false;
if let Some(pattern) = &pattern {
if !pattern.is_match(&relative_path) {
ignored = true;
}
}
let name = match path.file_stem() {
Some(name) => name.to_string_lossy(),
None => continue,
};
let name = match &slug_prefix {
Some(prefix) => format!("{}/{}", prefix, name),
None => name.to_string(),
};
let slug = match to_slug(&name) {
Ok(slug) if slug == name => slug,
_ => continue,
};
if ignored {
content.ignored.insert(slug);
continue;
}
let extension = path
.extension()
.map(|extension| String::from(extension.to_string_lossy()));
let content_type = match &extension {
Some(extension) => self.infer_content_type(extension).await?,
None => ContentType::Bytes,
};
let file_bytes = fs::read(path).await?;
let body_cid = BodyChunkIpld::store_bytes(&file_bytes, store).await?;
content.matched.insert(
slug,
FileReference {
cid: body_cid,
content_type,
extension,
},
);
}
}
Ok(content)
}
pub async fn get_local_content_changes<Sa: Store, Sb: Store>(
&self,
pattern: Option<GlobMatcher>,
db: &SphereDb<Sa>,
new_blocks: &mut Sb,
) -> Result<Option<(Content, ContentChanges)>> {
let sphere_did = self.get_local_identity().await?;
let sphere_cid = match db.get_version(&sphere_did).await? {
Some(cid) => cid,
None => {
return Ok(None);
}
};
let content = self.read_local_content(pattern, new_blocks).await?;
let sphere_fs = SphereFs::at(&sphere_did, &sphere_cid, &Author::anonymous(), db).await?;
let sphere = Sphere::at(&sphere_cid, db);
let links = sphere.try_get_links().await?;
let mut stream = links.stream().await?;
let mut changes = ContentChanges::default();
while let Some(Ok((slug, cid))) = stream.next().await {
if content.ignored.contains(slug) {
continue;
}
match content.matched.get(slug) {
Some(FileReference {
cid: body_cid,
content_type,
extension: _,
}) => {
let sphere_file = sphere_fs.read(slug).await?.ok_or_else(|| {
anyhow!(
"Expected sphere file at slug {:?} but it was missing!",
slug
)
})?;
if &sphere_file.memo.body == body_cid {
changes.unchanged.insert(slug.clone());
continue;
}
changes
.updated
.insert(slug.clone(), Some(content_type.clone()));
}
None => {
let memo = db.load::<DagCborCodec, MemoIpld>(cid).await?;
changes.removed.insert(slug.clone(), memo.content_type());
}
}
}
for (slug, FileReference { content_type, .. }) in &content.matched {
if changes.updated.contains_key(slug)
|| changes.removed.contains_key(slug)
|| changes.unchanged.contains(slug)
{
continue;
}
changes.new.insert(slug.clone(), Some(content_type.clone()));
}
Ok(Some((content, changes)))
}
pub async fn render<S: Store>(&self, db: &mut SphereDb<S>) -> Result<()> {
let sphere_did = self.get_local_identity().await?;
let sphere_cid = db.require_version(&sphere_did).await?;
let sphere_fs = SphereFs::at(&sphere_did, &sphere_cid, &Author::anonymous(), db).await?;
let sphere = Sphere::at(&sphere_cid, db);
let links = sphere.try_get_links().await?;
let mut stream = links.stream().await?;
while let Some(Ok((slug, _cid))) = stream.next().await {
debug!("Rendering {}...", slug);
let mut sphere_file = match sphere_fs.read(slug).await? {
Some(file) => file,
None => {
println!("Warning: could not resolve content for {}", slug);
continue;
}
};
let extension = match sphere_file
.memo
.get_first_header(&Header::FileExtension.to_string())
{
Some(extension) => Some(extension),
None => match sphere_file.memo.content_type() {
Some(content_type) => self.infer_file_extension(content_type).await,
None => {
println!("Warning: no content type specified for {}; it will be rendered without a file extension", slug);
None
}
},
};
let file_fragment = match extension {
Some(extension) => [slug.as_str(), &extension].join("."),
None => slug.into(),
};
let file_path = self.root.join(file_fragment);
let file_directory = file_path
.parent()
.ok_or_else(|| anyhow!("Unable to determine root directory for {}", slug))?;
fs::create_dir_all(&file_directory).await?;
let mut fs_file = File::create(file_path).await?;
copy(&mut sphere_file.contents, &mut fs_file).await?;
}
Ok(())
}
pub async fn infer_content_type(&self, extension: &str) -> Result<ContentType> {
Ok(match extension {
"subtext" => ContentType::Subtext,
"sphere" => ContentType::Sphere,
_ => ContentType::from_str(
mime_guess::from_ext(extension)
.first_raw()
.unwrap_or("raw/bytes"),
)?,
})
}
pub async fn infer_file_extension(&self, content_type: ContentType) -> Option<String> {
match content_type {
ContentType::Subtext => Some("subtext".into()),
ContentType::Sphere => Some("sphere".into()),
ContentType::Bytes => None,
ContentType::Unknown(content_type) => {
match mime_guess::get_mime_extensions_str(&content_type) {
Some(extensions) => extensions.first().map(|str| String::from(*str)),
None => None,
}
}
}
}
pub async fn get_ignored_patterns(&self) -> Result<GlobSet> {
self.expect_local_directories()?;
let ignored_patterns = vec!["@*", ".*"];
let mut builder = GlobSetBuilder::new();
for pattern in ignored_patterns {
builder.add(Glob::new(pattern)?);
}
Ok(builder.build()?)
}
pub fn root_path(&self) -> &PathBuf {
&self.root
}
pub fn sphere_path(&self) -> &PathBuf {
&self.sphere
}
pub fn blocks_path(&self) -> &PathBuf {
&self.blocks
}
pub fn noosphere_path(&self) -> &PathBuf {
&self.noosphere
}
pub fn keys_path(&self) -> &PathBuf {
&self.keys
}
pub fn authorization_path(&self) -> &PathBuf {
&self.authorization
}
pub fn key_path(&self) -> &PathBuf {
&self.key
}
pub fn identity_path(&self) -> &PathBuf {
&self.identity
}
pub fn config_path(&self) -> &PathBuf {
&self.config
}
pub async fn get_local_gateway_url(&self) -> Result<Url> {
match Config::from(self).read().await? {
ConfigContents {
gateway_url: Some(url),
..
} => Ok(url.clone()),
_ => Err(anyhow!(
"No gateway URL configured; set it with: orb config set gateway-url <URL>"
)),
}
}
pub async fn get_local_authorization(&self) -> Result<Authorization> {
self.expect_local_directories()?;
Authorization::from_str(&fs::read_to_string(&self.authorization).await?)
}
pub async fn get_local_db(&self) -> Result<SphereDb<NativeStore>> {
self.expect_local_directories()?;
let storage_provider =
NativeStorageProvider::new(NativeStorageInit::Path(self.blocks_path().clone()))?;
SphereDb::new(&storage_provider).await
}
pub async fn get_local_key(&self) -> Result<Ed25519KeyMaterial> {
self.expect_global_directories()?;
self.expect_local_directories()?;
let local_key_did = fs::read_to_string(&self.key).await?;
let keys = self.get_all_keys().await?;
for (key, did) in keys {
if did == local_key_did {
let private_key_mnemonic = self.get_key_mnemonic(&key).await?;
return restore_ed25519_key(&private_key_mnemonic);
}
}
Err(anyhow!(
"Could not resolve private key material for {:?}",
local_key_did
))
}
pub async fn get_local_identity(&self) -> Result<Did> {
self.expect_local_directories()?;
Ok(Did(fs::read_to_string(&self.identity).await?))
}
pub async fn get_key_did(&self, name: &str) -> Result<String> {
Ok(fs::read_to_string(self.keys.join(name).with_extension("public")).await?)
}
async fn get_key_mnemonic(&self, name: &str) -> Result<String> {
Ok(fs::read_to_string(self.keys.join(name).with_extension("private")).await?)
}
pub async fn is_root_empty(&self) -> Result<bool> {
let mut directory = fs::read_dir(&self.root).await?;
Ok(if let Some(_) = directory.next_entry().await? {
false
} else {
true
})
}
pub async fn get_all_keys(&self) -> Result<BTreeMap<String, String>> {
self.expect_global_directories()?;
let mut key_names = BTreeMap::<String, String>::new();
let mut directory = fs::read_dir(&self.keys).await?;
while let Some(entry) = directory.next_entry().await? {
let key_path = entry.path();
let key_name = key_path.file_stem().map(|stem| stem.to_str());
let extension = key_path.extension().map(|extension| extension.to_str());
match (key_name, extension) {
(Some(Some(key_name)), Some(Some("public"))) => {
let did = self.get_key_did(key_name).await?;
key_names.insert(key_name.to_string(), did);
}
_ => continue,
};
}
Ok(key_names)
}
pub async fn unambiguous_default_key_name(&self) -> Result<String> {
if self.expect_global_directories().is_ok() {
let keys = self.get_all_keys().await?;
if keys.len() > 1 {
let key_names = keys
.into_iter()
.map(|(name, _)| name)
.collect::<Vec<String>>()
.join("\n");
return Err(anyhow!(
r#"There is more than one key; you should specify a key to use by name
The available keys are:
{}"#,
key_names
));
} else if let Some((key_name, _)) = keys.iter().next() {
return Ok(key_name.clone());
}
}
Err(anyhow!("No keys found; have you created any yet?"))
}
fn has_sphere_directory(path: &Path) -> bool {
path.is_absolute() && path.join(SPHERE_DIRECTORY).is_dir()
}
pub fn expect_local_directories(&self) -> Result<()> {
if !self.root.is_dir() {
return Err(anyhow!(
"Configured sphere root {:?} is not a directory!",
self.root
));
}
if !Workspace::has_sphere_directory(&self.root) {
return Err(anyhow!(
"The {:?} folder within {:?} is missing or corrupted",
SPHERE_DIRECTORY,
self.root
));
}
Ok(())
}
pub fn expect_global_directories(&self) -> Result<()> {
if !self.noosphere.is_dir() || !self.keys.is_dir() {
return Err(anyhow!(
"The Noosphere config directory ({:?}) is missing or corrupted",
self.noosphere
));
}
Ok(())
}
pub async fn initialize_local_directories(&self) -> Result<()> {
if self.expect_local_directories().is_ok() {
return Err(anyhow!(
r#"Cannot initialize the sphere; a sphere is already initialized in {:?}
Unexpected (bad) things will happen if you try to nest spheres this way!"#,
self.root,
))?;
}
fs::create_dir_all(&self.sphere).await?;
fs::write(self.config_path(), "").await?;
Ok(())
}
pub async fn initialize_global_directories(&self) -> Result<()> {
fs::create_dir_all(&self.keys).await?;
Ok(())
}
pub fn new(
current_working_directory: &PathBuf,
noosphere_global_root: Option<&PathBuf>,
) -> Result<Self> {
if !current_working_directory.is_absolute() {
return Err(anyhow!(
"Ambiguous working directory: {:?} (must be an absolute path)",
current_working_directory
));
}
let mut root = current_working_directory.clone();
loop {
match root.parent() {
Some(parent) => {
root = parent.to_path_buf();
if Workspace::has_sphere_directory(&root) {
break;
}
}
None => {
root = current_working_directory.clone();
break;
}
}
}
let sphere = root.join(SPHERE_DIRECTORY);
let blocks = sphere.join(BLOCKS_DIRECTORY);
let authorization = sphere.join(AUTHORIZATION_FILE);
let key = sphere.join(KEY_FILE);
let identity = sphere.join(IDENTITY_FILE);
let config = sphere.join(CONFIG_FILE);
let noosphere = match noosphere_global_root {
Some(custom_root) => custom_root.clone(),
None => home::home_dir()
.ok_or_else(|| {
anyhow!(
"Could not discover home directory for {}",
whoami::username()
)
})?
.join(NOOSPHERE_DIRECTORY),
};
let keys = noosphere.join(KEYS_DIRECTORY);
Ok(Workspace {
root,
sphere,
blocks,
authorization,
key,
identity,
noosphere,
keys,
config,
})
}
#[cfg(test)]
pub fn temporary() -> Result<Self> {
use temp_dir::TempDir;
let root = TempDir::new()?;
let global_root = TempDir::new()?;
Workspace::new(
&root.path().to_path_buf(),
Some(&global_root.path().to_path_buf()),
)
}
}
#[cfg(test)]
mod tests {
use crate::native::commands::{key, sphere};
use tokio::fs;
use super::Workspace;
#[tokio::test]
async fn it_chooses_an_ancestor_sphere_directory_as_root_if_one_exists() {
let workspace = Workspace::temporary().unwrap();
key::key_create("FOO", &workspace).await.unwrap();
sphere::sphere_create("FOO", &workspace).await.unwrap();
let subdirectory = workspace.root_path().join("foo/bar");
fs::create_dir_all(&subdirectory).await.unwrap();
let new_workspace =
Workspace::new(&subdirectory, Some(workspace.noosphere_path())).unwrap();
assert_eq!(workspace.root_path(), new_workspace.root_path());
}
}