noosphere_cli/native/commands/sphere/
save.rs

1use anyhow::{anyhow, Result};
2use cid::Cid;
3use libipld_cbor::DagCborCodec;
4use noosphere_core::context::{HasMutableSphereContext, SphereContentWrite, SphereCursor};
5use noosphere_core::data::Header;
6use noosphere_storage::BlockStore;
7
8use crate::native::{
9    content::{Content, FileReference},
10    workspace::Workspace,
11};
12
13/// TODO(#105): We may want to change this to take an optional list of paths to
14/// consider, and allow the user to rely on their shell for glob filtering
15pub async fn save(render_depth: Option<u32>, workspace: &Workspace) -> Result<()> {
16    workspace.ensure_sphere_initialized()?;
17
18    let mut db = workspace.db().await?;
19
20    let sphere_context = workspace.sphere_context().await?;
21
22    let mut has_unsaved_changes = sphere_context.has_unsaved_changes().await?;
23
24    if let Some((content, content_changes, memory_store)) = Content::read_changes(workspace).await?
25    {
26        let content_entries = memory_store.entries.lock().await;
27
28        for (cid_bytes, block) in content_entries.iter() {
29            let cid = Cid::try_from(cid_bytes.as_slice())?;
30            db.put_block(&cid, block).await?;
31            db.put_links::<DagCborCodec>(&cid, block).await?;
32        }
33
34        let mut sphere_context = workspace.sphere_context().await?;
35
36        for (slug, _) in content_changes
37            .new
38            .iter()
39            .chain(content_changes.updated.iter())
40        {
41            if let Some(FileReference {
42                cid,
43                content_type,
44                extension,
45            }) = content.matched.get(slug)
46            {
47                info!("Saving '{slug}'...");
48
49                let headers = extension
50                    .as_ref()
51                    .map(|extension| vec![(Header::FileExtension.to_string(), extension.clone())]);
52
53                sphere_context
54                    .link(slug, content_type, cid, headers)
55                    .await?;
56            }
57        }
58
59        for slug in content_changes.removed.keys() {
60            info!("Removing '{slug}'...");
61            sphere_context.remove(slug).await?;
62        }
63
64        has_unsaved_changes = true;
65    }
66
67    if has_unsaved_changes {
68        let cid = SphereCursor::latest(sphere_context).save(None).await?;
69        info!("Save complete!\nThe latest sphere revision is {cid}");
70
71        workspace.render(render_depth, false).await?;
72
73        Ok(())
74    } else {
75        Err(anyhow!("No changes to save"))
76    }
77}