Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code to search for bookmarks or folders #3

Merged
merged 4 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,39 @@ A Rust-written cli tool for [Floccus](www.floccus.org)
* cargo build
* ./target/debug/floccus_cli --help

Print bookmarks:
### Print bookmarks

* Init floccus_cli:
* ./target/debug/floccus_cli -r https://github.com/your_username/your_repo.git print
* After:
* ./target/debug/floccus-cli print

Add a new bookmark (EXPERIMENTAL, Default: append to root):
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" --disable-push
### Add a new bookmark (EXPERIMENTAL, Default: append to root)

* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" --disable-push

* Add a bookmark after a given id (folder or bookmark)
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u after=3 --disable-push
* Add a bookmark in a given folder id (append)
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u 2 --disable-push
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u append=2 --disable-push
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u 2 --disable-push
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u append=2 --disable-push
* Add a bookmark in a given folder id (prepend)
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u prepend=2 --disable-push
* ./target/debug/floccus-cli add -b https://example.com -t "Example www site" -u prepend=2 --disable-push

Note:
* Pushing (git push) by floccus-cli is experimental - for now use --disable-push && push manually

### Remove a bookmark / folder (EXPERIMENTAL)

* Remove a bookmark using a given id
* ./target/debug/floccus-cli rm -i 14 --disable-push

Note:
* Pushing (git push) by floccus-cli is experimental - for now use --disable-push && push manually

### Find a bookmark or folder

* Find a bookmark
* ./target/debug/floccus-cli find "FOO"
* ./target/debug/floccus-cli find --bookmark "FOO"
* ./target/debug/floccus-cli find --bookmark --title "FOO"
163 changes: 163 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod git;
mod xbel;

// std
use std::borrow::Cow;
use std::error::Error;
use std::path::PathBuf;
use std::str::FromStr;
Expand Down Expand Up @@ -49,6 +50,8 @@ pub(crate) enum Commands {
Add(AddArgs),
#[command(about = "Remove bookmark(s)")]
Rm(RemoveArgs),
#[command(about = "Find bookmark(s)")]
Find(FindArgs),
}

#[derive(Debug, Clone, PartialEq, Args)]
Expand Down Expand Up @@ -156,6 +159,44 @@ pub struct RemoveArgs {
dry_run: bool,
}

#[derive(Debug, Clone, PartialEq, Args)]
pub struct FindArgs {
#[arg(
short = 't',
long = "title",
help = "Only search in folder or bookmark titles (Default: search on url & titles)",
action,
required = false
)]
title: bool,
#[arg(
short = 'u',
long = "url",
help = "Only search in folder or bookmark url (Default: search on url & titles)",
action,
required = false
)]
url: bool,
#[arg(
short = 'f',
long = "folder",
help = "Perform search only for folders",
action,
required = false
)]
folder: bool,
#[arg(
short = 'b',
long = "bookmark",
help = "Perform search only for bookmarks",
action,
required = false
)]
bookmark: bool,
/// What to find
find: String,
}

fn main() -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
println!("cli: {:?}", cli);
Expand Down Expand Up @@ -218,6 +259,14 @@ fn main() -> Result<(), Box<dyn Error>> {
Commands::Rm(rm_args) => {
let res = bookmark_rm(&rm_args, repository_folder, &repo, cli.repository_url);

if let Err(e) = res {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
Commands::Find(find_args) => {
let res = bookmark_find(&find_args, repository_folder);

if let Err(e) = res {
eprintln!("Error: {}", e);
std::process::exit(1);
Expand Down Expand Up @@ -439,3 +488,117 @@ fn bookmark_rm(

Ok(())
}

#[derive(Error, Debug)]
enum BookmarkFindError {
#[error(transparent)]
XbelReadError(#[from] XbelError),
}

enum FindKind {
All,
Folder,
Bookmark,
}

enum FindWhere {
All,
Title,
Url,
}

fn bookmark_find(
find_args: &FindArgs,
repository_folder: PathBuf,
) -> Result<(), BookmarkFindError> {
let find_kind = if find_args.folder {
FindKind::Folder
} else if find_args.bookmark {
FindKind::Bookmark
} else {
FindKind::All
};

let find_where = if find_args.title {
FindWhere::Title
} else if find_args.url {
FindWhere::Url
} else {
FindWhere::All
};

// Read xbel file
let bookmark_file_path_xbel = PathBuf::from("bookmarks.xbel");
let bookmark_file_path = repository_folder.join(bookmark_file_path_xbel.as_path());
let xbel = Xbel::from_file(&bookmark_file_path)?;

let found_in_title = |item: &XbelItem, to_match: &str| item.get_title().text.contains(to_match);
let found_in_url = |item: &XbelItem, to_match: &str| {
item.get_url().unwrap_or(&"".to_string()).contains(to_match)
};
let items: Vec<&XbelItem> = xbel
.into_iter()
.filter(|i| {
let match_kind = match find_kind {
FindKind::Folder => matches!(i, XbelItem::Folder(_)),
FindKind::Bookmark => matches!(i, XbelItem::Bookmark(_)),
FindKind::All => true,
};

if !match_kind {
false
} else {
match find_where {
FindWhere::Title => found_in_title(i, find_args.find.as_str()),
FindWhere::Url => found_in_url(i, find_args.find.as_str()),
FindWhere::All => {
let to_find = find_args.find.as_str();
found_in_title(i, to_find) || found_in_url(i, to_find)
}
}
}
})
.collect();

if items.is_empty() {
let msg = match find_kind {
FindKind::All => "Found 0 bookmark or folder",
FindKind::Folder => "Found 0 folder",
FindKind::Bookmark => "Found 0 bookmark",
};
println!("{}", msg);
} else {
let msg = match find_kind {
FindKind::All => format!(
"Found {} {} or {}:",
items.len(),
pluralize("folder", items.len()),
pluralize("bookmark", items.len()),
),
FindKind::Folder => format!(
"Found {} {}:",
items.len(),
pluralize("folder", items.len())
),
FindKind::Bookmark => format!(
"Found {} {}:",
items.len(),
pluralize("bookmark", items.len())
),
};

println!("{}", msg);
for (idx, i) in items.iter().enumerate() {
println!("{}- {:?}", idx, i);
}
}

Ok(())
}

fn pluralize(s: &str, count: usize) -> Cow<'_, str> {
match count {
0 | 1 => Cow::Borrowed(s),
_ => Cow::Owned(format!("{}s", s)),
}
}
6 changes: 6 additions & 0 deletions src/xbel/xbel_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ impl XbelItem {
XbelItem::Bookmark(b) => &b.id,
}
}
pub(crate) fn get_url(&self) -> Option<&String> {
match self {
XbelItem::Folder(_f) => None,
XbelItem::Bookmark(b) => Some(&b.href),
}
}
}

#[derive(Debug, PartialEq, Default, Serialize, Deserialize)]
Expand Down