Something went wrong. Try again.
POC of simple editor based on Automerge
Something went wrong. Try again.
2.4 kB · 65 lines
Rust
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566//! Startup options and the choice of local replica directory.use simple_editor::replica::{Replica, catalog_id};use std::path::PathBuf;
#[derive(Clone)]pub struct Options { replica: Option<String>, data_dir: PathBuf, pub server: String,}
impl Options { pub fn from_args() -> Result<Self, String> { let mut options = Self { replica: None, data_dir: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".simple-editor"), server: "ws://localhost:3030".into(), }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { if arg == "--help" { println!( "simple-editor [--replica alice] [--data-dir PATH] [--server ws://localhost:3030]" ); std::process::exit(0); } let value = args .next() .ok_or_else(|| format!("Missing value for {arg}"))?; match arg.as_str() { "--replica" if valid_name(&value) => options.replica = Some(value), "--data-dir" => options.data_dir = value.into(), "--server" => options.server = value, _ => return Err(format!("Invalid option: {arg}. Use --help.")), } } Ok(options) }
pub fn open_replica(&self) -> Result<Replica, String> { if let Some(name) = &self.replica { return Replica::open(self.data_dir.join(name), name.clone(), catalog_id()); }
// Without --replica, two launches should get different storage directories. // A locked directory belongs to another running editor, so try the next slot. for slot in 1..=32 { let name = format!("replica-{slot}"); let result = Replica::open(self.data_dir.join(&name), name, catalog_id()); match result { Err(error) if error.contains("is already open") => continue, result => return result, } } Err("All replica slots are in use".into()) }}
fn valid_name(name: &str) -> bool { // Replica names become directory names. Keep them to one simple path component. !name.is_empty() && name .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')}