macro_rules! print {
($($arg:tt)*) => { $crate::print_out(format_args!($($arg)*)) };
}
macro_rules! println {
() => { print!("\n") };
($($arg:tt)*) => { print!("{}\n", format_args!($($arg)*)) };
}
mod account;
mod debug;
mod edit;
mod imex;
mod input;
mod lb_fs;
mod list;
mod migrate;
mod share;
mod stream;
use std::env;
use std::path::PathBuf;
use std::str::FromStr;
use account::ApiUrl;
use cli_rs::arg::Arg;
use cli_rs::cli_error::{CliError, CliResult, Exit};
use cli_rs::command::Command;
use cli_rs::flag::Flag;
use cli_rs::parser::Cmd;
use colored::Colorize;
use input::find_file;
use lb_rs::model::core_config::Config;
use lb_rs::model::errors::LbErrKind;
use lb_rs::model::path_ops::Filter;
use lb_rs::service::events::{Event, SyncIncrement};
use lb_rs::{Lb, Uuid};
use tokio::sync::broadcast::error::RecvError;
fn run() -> CliResult<()> {
Command::name("lockbook")
.description("The private, polished note-taking platform.")
.version(env!("CARGO_PKG_VERSION"))
.subcommand(
Command::name("account")
.description("account management commands")
.subcommand(
Command::name("new")
.input(Arg::str("username").description("your desired username."))
.input(Flag::<ApiUrl>::new("api_url")
.description("location of the lockbook server you're trying to use. If not provided will check the API_URL env var, and then fall back to https://app.lockbook.net"))
.handler(|username, api_url| {
account::new(username.get(), api_url.get())
})
)
.subcommand(
Command::name("import").description("import an existing account from a key or phrase")
.input(Flag::<ApiUrl>::new("api_url")
.description("location of the lockbook server you're trying to use. If not provided will check the API_URL env var, and then fall back to https://app.lockbook.net"))
.handler(|api_url| {
account::import(api_url.get())
})
)
.subcommand(
Command::name("export").description("reveal your account key or account phrase")
.input(Flag::bool("skip-check").description("don't ask for confirmation to reveal the secret"))
.input(Flag::bool("phrase").description("export the 24-word account phrase instead of the compact account key"))
.handler(|skip_check, phrase| account::export(skip_check.get(), phrase.get()))
)
.subcommand(
Command::name("subscribe").description("start a monthly subscription for massively increased storage")
.handler(account::subscribe)
)
.subcommand(
Command::name("unsubscribe").description("cancel an existing subscription")
.handler(account::unsubscribe)
)
.subcommand(
Command::name("status").description("show your account status")
.handler(account::status)
)
)
.subcommand(
Command::name("import").description("import files from your file system into lockbook")
.input(Arg::<PathBuf>::name("disk-path").description("path of file on disk"))
.input(Arg::str("dest")
.description("the path or id of a folder within lockbook to place the file.")
.completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
.handler(|disk, parent| imex::import(disk.get(), parent.get()))
)
.subcommand(
Command::name("debug").description("investigative commands")
.subcommand(
Command::name("validate").description("helps find invalid states within your lockbook")
.handler(debug::validate)
)
.subcommand(
Command::name("info").description("print metadata associated with a file")
.input(Arg::str("target").description("id or path of file to debug")
.completor(|prompt| input::file_completor(prompt, None)))
.handler(|target| debug::info(target.get()))
)
.subcommand(
Command::name("whoami").description("print who is logged into this lockbook")
.handler(debug::whoami)
)
.subcommand(
Command::name("whereami").description("print information about where this lockbook is stored and it's server url")
.handler(debug::whereami)
)
.subcommand(
Command::name("debuginfo").description("retrieve the debug-info string to help a lockbook engineer diagnose a problem")
.handler(debug::debug_info)
)
)
.subcommand(
Command::name("delete").description("delete a file")
.input(Flag::bool("force"))
.input(Arg::str("target").description("path of id of file to delete")
.completor(|prompt| input::file_completor(prompt, None)))
.handler(|force, target| delete(force.get(), target.get()))
)
.subcommand(
Command::name("duplicate").description("duplicate a document in place (same folder, auto-named copy)")
.input(Arg::str("target").description("path or id of document to duplicate")
.completor(|prompt| input::file_completor(prompt, None)))
.handler(|target| duplicate(target.get()))
)
.subcommand(
Command::name("edit").description("edit a document")
.input(edit::editor_flag())
.input(Arg::str("target").description("path or id of file to edit")
.completor(|prompt| input::file_completor(prompt, None)))
.handler(|editor, target| edit::edit(editor.get(), target.get()))
)
.subcommand(
Command::name("export").description("export a lockbook file to your file system")
.input(Arg::str("target")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Arg::<PathBuf>::name("dest").description("directory, or file path when exporting a single document"))
.input(Flag::bool("force").description("overwrite existing files on disk"))
.input(Flag::bool("contents").description("when exporting a folder, place its children in dest (rsync src/ semantics) instead of dest/<folder-name>"))
.handler(|target, dest, force, contents| {
imex::export(target.get(), dest.get(), force.get(), contents.get())
})
)
.subcommand(
Command::name("fs")
.description("use your lockbook files with your local filesystem by mounting an NFS drive to /tmp/lockbook")
.handler(lb_fs::mount)
)
.subcommand(
Command::name("list").description("list files and file information")
.input(Flag::bool("long").description("long listing: id, type, size, modified time, and share info (short: -l)"))
.input(Flag::bool("recursive").description("include all children recursively; implies --paths (short: -r/-R)"))
.input(Flag::bool("paths").description("display the full path of each entry (short: -p)"))
.input(Arg::str("target").description("file path location whose files will be listed")
.completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly)))
.default("/".to_string()))
.handler(|long, recur, paths, target| list::list(long.get(), recur.get(), paths.get(), target.get()))
)
.subcommand(
Command::name("move").description("move a file to a new parent")
.input(Arg::str("src-target").description("lockbook file path or ID of the file to move")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Arg::str("dest").description("lockbook file path or ID of the new parent folder")
.completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
.handler(|src, dst| move_file(src.get(), dst.get()))
)
.subcommand(
Command::name("new").description("create a new file at the given path or do nothing if it exists")
.input(Arg::str("path").description("create a new file at the given path or do nothing if it exists")
.completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
.handler(|target| create_file(target.get()))
)
.subcommand(
Command::name("cat")
.description("print a document to stdout")
.input(Arg::str("target").description("lockbook file path or ID")
.completor(|prompt| input::file_completor(prompt, None)))
.handler(|target| stream::stdout(target.get()))
)
.subcommand(
Command::name("write")
.description("write stdin to a document, creating it if it does not exist")
.input(Arg::str("target").description("lockbook file path or ID")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Flag::bool("append").description("don't overwrite the specified lb file, append to it"))
.handler(|target, append| stream::stdin(target.get(), append.get()))
)
.subcommand(
Command::name("rename").description("rename a file")
.input(Arg::str("target").description("lockbook file path or ID of file to rename")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Arg::str("new_name"))
.handler(|target, new_name| rename(target.get(), new_name.get()))
)
.subcommand(
Command::name("share").description("sharing related commands")
.subcommand(
Command::name("new").description("share a file with someone")
.input(Arg::str("target").description("lockbook file path or ID of file to rename")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Arg::str("username")
.completor(input::username_completor))
.input(Flag::bool("read-only"))
.handler(|target, username, ro| share::new(target.get(), username.get(), ro.get()))
)
.subcommand(
Command::name("remove").description("stop sharing a file with someone")
.input(Arg::str("target").description("lockbook file path or ID of the shared file")
.completor(|prompt| input::file_completor(prompt, None)))
.input(Arg::str("username")
.completor(input::username_completor))
.handler(|target, username| share::remove(target.get(), username.get()))
)
.subcommand(
Command::name("pending").description("list pending shares")
.handler(share::pending)
)
.subcommand(
Command::name("accept").description("accept a pending share by adding it to your file tree")
.input(Arg::<Uuid>::name("pending-share-id").description("ID of pending share")
.completor(share::pending_share_completor))
.input(Arg::str("target").description("lockbook file path or ID of the folder you want to place this shared file")
.completor(|prompt| input::file_completor(prompt, Some(Filter::FoldersOnly))))
.handler(|id, dest| share::accept(&id.get(), dest.get()))
)
.subcommand(
Command::name("delete").description("delete a pending share")
.input(Arg::<Uuid>::name("share-id").description("ID of pending share to delete")
.completor(share::pending_share_completor))
.handler(|target| share::delete(target.get()))
)
)
.subcommand(
Command::name("search").description("search file paths and document contents")
.input(Arg::str("query"))
.handler(|query| search(&query.get()))
)
.subcommand(
Command::name("migrate-from").description("transfer files from an existing platform")
.subcommand(
Command::name("bear").description("migrate your files from https://bear.app/ Export as md and using the 'export attachments' option.")
.input(Arg::<PathBuf>::name("disk-path").description("location of a bear export of files."))
.handler(|path| migrate::bear(path.get()))
)
)
.subcommand(
Command::name("sync").description("sync your local changes back to lockbook servers") .handler(sync)
)
.with_completions()
.parse()
}
fn print_out(args: std::fmt::Arguments) {
use std::io::Write;
let mut stdout = std::io::stdout().lock();
if let Err(err) = stdout.write_fmt(args).and_then(|()| stdout.flush()) {
if err.kind() == std::io::ErrorKind::BrokenPipe {
return;
}
panic!("failed printing to stdout: {err}");
}
}
fn main() {
run().exit();
}
pub async fn core() -> CliResult<Lb> {
Lb::init(Config::cli_config("cli"))
.await
.map_err(|err| CliError::from(err.to_string()))
}
fn search(query: &str) -> CliResult<()> {
let lb = lb_rs::blocking::Lb::init(Config::cli_config("cli"))
.map_err(|err| CliError::from(err.to_string()))?;
lb.get_account()
.map_err(|err| CliError::from(err.to_string()))?;
let mut path_searcher = lb.path_searcher();
path_searcher.query(query);
let path_results = path_searcher.results();
println!("{}", "Files".bold().underline());
if path_results.is_empty() {
println!(" no matches");
}
for result in path_results.iter().take(10) {
println!(" {}", full_path(&result.parent_path, &result.filename).green());
}
println!();
let mut content_searcher = lb.content_searcher();
content_searcher.query(query);
let content_results = content_searcher.results();
println!("{}", "Content".bold().underline());
if content_results.is_empty() {
println!(" no matches");
}
for result in content_results.iter().take(10) {
println!(
" {}",
full_path(&result.parent_path, &result.filename)
.bold()
.blue()
);
for content_match in result.content_matches.iter().take(3) {
if let Some((prefix, matched, suffix)) =
content_searcher.snippet(result.id, &content_match.range, 40)
{
println!(
" …{}{}{}…",
one_line(prefix),
one_line(matched).underline(),
one_line(suffix)
);
}
}
}
Ok(())
}
fn full_path(parent_path: &str, filename: &str) -> String {
if parent_path == "/" || parent_path.is_empty() {
format!("/{filename}")
} else {
format!("{parent_path}/{filename}")
}
}
fn one_line(s: &str) -> String {
s.chars()
.map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
.collect()
}
#[tokio::main]
async fn sync() -> CliResult<()> {
let lb = &core().await?;
ensure_account(lb)?;
let mut receiver = lb.subscribe();
let monitor_lb = lb.clone();
let monitor = tokio::spawn(async move {
let get_name = async |id| {
monitor_lb
.get_file_by_id(id)
.await
.map(|file| file.name)
.unwrap_or(format!("{id} (new file)"))
};
loop {
let event = match receiver.recv().await {
Ok(event) => event,
Err(RecvError::Lagged(skipped)) => {
println!("{skipped} progress updates skipped");
continue;
}
Err(RecvError::Closed) => return,
};
if let Event::Sync(sync_increment) = event {
match sync_increment {
SyncIncrement::SyncStarted => println!("Sync Started!"),
SyncIncrement::PullingDocument(uuid, true) => {
println!("Downloading {}", get_name(uuid).await)
}
SyncIncrement::PullingDocument(uuid, false) => {
println!("Downloaded {}", get_name(uuid).await)
}
SyncIncrement::PushingDocument(uuid, true) => {
println!("Uploading {}", get_name(uuid).await)
}
SyncIncrement::PushingDocument(uuid, false) => {
println!("Uploaded {}", get_name(uuid).await)
}
SyncIncrement::SyncFinished(lb_err_kind) => {
match lb_err_kind {
Some(err) => eprintln!("Sync completed with an error: {err}"),
None => println!("Sync successful"),
};
return;
}
}
}
}
});
lb.sync().await?;
monitor.await?;
Ok(())
}
#[tokio::main]
async fn delete(force: bool, target: String) -> Result<(), CliError> {
let lb = &core().await?;
ensure_account_and_root(lb).await?;
let f = find_file(lb, &target).await?;
if !force {
let mut phrase = format!("delete '{target}'");
if f.is_folder() {
let count = lb
.get_and_get_children_recursively(&f.id)
.await
.unwrap_or_default()
.len() as u64
- 1;
match count {
0 => {}
1 => phrase = format!("{phrase} and its 1 child"),
_ => phrase = format!("{phrase} and its {count} children"),
};
}
let answer: String = input::std_in(format!("are you sure you want to {phrase}? [y/n]: "))?;
if answer != "y" && answer != "Y" {
println!("aborted.");
return Ok(());
}
}
lb.delete(&f.id).await?;
Ok(())
}
#[tokio::main]
async fn move_file(src: String, dest: String) -> CliResult<()> {
let lb = &core().await?;
ensure_account_and_root(lb).await?;
let src = find_file(lb, &src).await?;
let dest = find_file(lb, &dest).await?;
lb.move_file(&src.id, &dest.id).await?;
Ok(())
}
#[tokio::main]
async fn create_file(path: String) -> CliResult<()> {
let lb = &core().await?;
ensure_account_and_root(lb).await?;
if Uuid::from_str(&path).is_ok() {
return Err(CliError::from("cannot create a file using ids"));
}
match lb.get_by_path(&path).await {
Ok(_f) => Ok(()),
Err(err) => match err.kind {
LbErrKind::FileNonexistent => match lb.create_at_path(&path).await {
Ok(_f) => Ok(()),
Err(err) => Err(err.into()),
},
_ => Err(err.into()),
},
}
}
#[tokio::main]
async fn rename(target: String, new_name: String) -> Result<(), CliError> {
let lb = &core().await?;
ensure_account_and_root(lb).await?;
let id = find_file(lb, &target).await?.id;
lb.rename_file(&id, &new_name).await?;
Ok(())
}
#[tokio::main]
async fn duplicate(target: String) -> CliResult<()> {
let lb = &core().await?;
ensure_account_and_root(lb).await?;
let f = find_file(lb, &target).await?;
let copy = lb.duplicate_file(&f.id).await?;
let path = lb.get_path_by_id(copy.id).await?;
println!("duplicated to {path}");
Ok(())
}
fn ensure_account(lb: &Lb) -> CliResult<()> {
if let Err(e) = lb.get_account() {
if e.kind == LbErrKind::AccountNonexistent {
return Err(CliError::from("no account found, run lockbook account import"));
}
}
Ok(())
}
async fn ensure_account_and_root(lb: &Lb) -> CliResult<()> {
ensure_account(lb)?;
if let Err(e) = lb.root().await {
if e.kind == LbErrKind::RootNonexistent {
return Err(CliError::from("no root found, have you synced yet?"));
}
}
Ok(())
}