use clap::{Parser, Subcommand};
use hermes_ipfs::{HermesIpfs, IpfsBuilder};
use lipsum::lipsum_with_rng;
use rand::thread_rng;
use rust_ipfs::IpfsPath;
#[derive(Debug, Parser)] #[command(name = "hermes-ipfs-cli")]
#[command(about = "Hermes IPFS Virtual File Manager", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
#[command(name = "ls")]
ListFiles,
#[command(name = "add")]
AddFile,
#[command(name = "cat")]
GetFile {
ipfs_path_str: String,
},
#[command(name = "rm")]
UnPinFile {
ipfs_path_str: String,
},
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Cli::parse();
let base_dir = dirs::data_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
let ipfs_data_path = base_dir.as_path().join("hermes/ipfs");
let builder = IpfsBuilder::new()
.with_default()
.set_default_listener()
.set_disk_storage(ipfs_data_path);
let hermes_node: HermesIpfs = builder.start().await?.into();
match args.command {
Commands::ListFiles => {
println!("Listing files");
let cids = hermes_node.list_pins().await?;
for cid in &cids {
println!("{}", IpfsPath::from(cid));
}
},
Commands::AddFile => {
println!("Adding file");
let contents = lipsum_with_rng(thread_rng(), 42);
let ipfs_path = hermes_node
.add_ipfs_file(contents.into_bytes().into())
.await?;
println!("Added file: {ipfs_path}");
},
Commands::GetFile { ipfs_path_str } => {
println!("Getting file");
let ipfs_path: IpfsPath = ipfs_path_str.parse()?;
let get_file_bytes = hermes_node.get_ipfs_file(ipfs_path.into()).await?;
println!("* Got file, {} bytes:", get_file_bytes.len());
let get_file = String::from_utf8(get_file_bytes)?;
println!("* FILE CONTENTS:");
println!("{get_file}\n");
},
Commands::UnPinFile { ipfs_path_str } => {
println!("Un-pinning file {ipfs_path_str}");
let ipfs_path: IpfsPath = ipfs_path_str.parse()?;
let cid = ipfs_path.root().cid().ok_or(anyhow::anyhow!(
"ERROR! Could not extract CID from IPFS path."
))?;
hermes_node.remove_pin(cid).await?;
},
}
hermes_node.stop().await;
Ok(())
}