Skip to content

Commit

Permalink
19: Print URLs (ARK-Builders#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
alvinosh authored and tareknaser committed Mar 14, 2024
1 parent 8133b6d commit 95f7fad
Show file tree
Hide file tree
Showing 11 changed files with 655 additions and 373 deletions.
13 changes: 7 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 23 additions & 11 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ $ ark-cli list ~/Pictures/
```

But it's a bit boring and doesn't really tell anything, right? Various flags should be used to gain more knowledge about your collections of resources:
* `--entry=id|path|both` to show the path,the id or both of a resource
* `--entry=id|path|both|link` to show the path,the id or both of a resource
* `--timestamp=true` to show or not the last modified timestamp of a resource
* `--tags=true` to show or not the tags for every resource
* `--scores=true` to show or not the scores for every resource
Expand All @@ -85,28 +85,40 @@ For instance, you can list files with their paths and attached tags:
```
$ ark-cli list -pt
30-4257856154 with tags search
18-1909444406 with tags hello
22-207093268 with tags search,engine
38-103010298 with tags NO_TAGS
30-4257856154 search
18-1909444406 hello
22-207093268 search,engine
38-103010298 NO_TAGS
```

You Can list the links of the files

```
$ark-cli list -l
https://google.com
https://news.ycombinator.com
https://youtube.com
https://github.com
```

Or, sort by score:
```
$ ark-cli list -s --sort=asc
30-4257856154 with score NO_SCORE
18-1909444406 with score 2
38-103010298 with score 10
22-207093268 with score 15
30-4257856154 NO_SCORE
18-1909444406 2
38-103010298 10
22-207093268 15
```

Finally, you can filter resources using their tags:
```
$ /tmp/ark-cli list -t --filter=search
30-4257856154 with tags search
22-207093268 with tags search,engine
30-4257856154 search
22-207093268 search,engine
```

## :zap: Low-level utilities :zap:
Expand Down
38 changes: 18 additions & 20 deletions src/commands/file.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
use crate::error::AppError;
use crate::models::{format, format::Format};
use arklib::{modify, modify_json, AtomicFile};
use arklib::{modify, modify_json, AtomicFile, Result as ArklibResult};

pub fn file_append(
atomic_file: &AtomicFile,
content: &str,
format: Format,
) -> Result<(), String> {
) -> Result<(), AppError> {
match format {
Format::Raw => modify(&atomic_file, |current| {
Format::Raw => Ok(modify(atomic_file, |current| {
let mut combined_vec: Vec<u8> = current.to_vec();
combined_vec.extend_from_slice(content.as_bytes());
combined_vec
})
.map_err(|_| "ERROR: Could not append string".to_string()),
})?),
Format::KeyValue => {
let values = format::key_value_to_str(&content)
.map_err(|_| "ERROR: Could not parse json".to_string())?;
let values = format::key_value_to_str(content)?;

append_json(&atomic_file, values.to_vec())
.map_err(|_| "ERROR: Could not append json".to_string())
Ok(append_json(atomic_file, values.to_vec())?)
}
}
}
Expand All @@ -27,16 +25,16 @@ pub fn file_insert(
atomic_file: &AtomicFile,
content: &str,
format: Format,
) -> Result<(), String> {
) -> Result<(), AppError> {
match format {
Format::Raw => modify(&atomic_file, |_| content.as_bytes().to_vec())
.map_err(|_| "ERROR: Could not insert string".to_string()),
Format::Raw => {
Ok(modify(atomic_file, |_| content.as_bytes().to_vec())?)
}
Format::KeyValue => {
let values = format::key_value_to_str(&content)
.map_err(|_| "ERROR: Could not parse json".to_string())?;
let values = format::key_value_to_str(content)?;

modify_json(
&atomic_file,
atomic_file,
|current: &mut Option<serde_json::Value>| {
let mut new = serde_json::Map::new();
for (key, value) in &values {
Expand All @@ -48,16 +46,16 @@ pub fn file_insert(
*current = Some(serde_json::Value::Object(new));
},
)
.map_err(|e| e.to_string())
.map_err(|e| AppError::FileOperationError(e.to_string()))
}
}
}

fn append_json(
atomic_file: &AtomicFile,
data: Vec<(String, String)>,
) -> arklib::Result<()> {
modify_json(&atomic_file, |current: &mut Option<serde_json::Value>| {
) -> ArklibResult<()> {
modify_json(atomic_file, |current: &mut Option<serde_json::Value>| {
let current_data = match current {
Some(current) => {
if let Ok(value) = serde_json::to_value(current) {
Expand All @@ -74,7 +72,7 @@ fn append_json(
};
let mut new = serde_json::Map::new();

if let None = current_data {
if current_data.is_none() {
for (key, value) in &data {
new.insert(
key.clone(),
Expand Down Expand Up @@ -128,7 +126,7 @@ pub fn format_file(file: &AtomicFile) -> Option<String> {
.expect("Not a file")
.to_str()
.unwrap()
.split("_");
.split('_');

let name = split.next().unwrap();

Expand Down
31 changes: 17 additions & 14 deletions src/commands/link.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,54 @@
use std::path::PathBuf;

use arklib::{id::ResourceId, link::Link};
use std::path::PathBuf;
use url::Url;

use crate::util::provide_index;
use crate::error::AppError;
use crate::util::provide_index; // Import your custom AppError type

pub async fn create_link(
root: &PathBuf,
url: &str,
title: &str,
desc: Option<String>,
) -> Result<(), String> {
let url = Url::parse(url).map_err(|_| "Invalid url")?;
) -> Result<(), AppError> {
let url = Url::parse(url)
.map_err(|_| AppError::LinkCreationError("Invalid url".to_owned()))?;
let link: Link = Link::new(url, title.to_owned(), desc.to_owned());
link.save(&root, true)
link.save(root, true)
.await
.map_err(|e| e.to_string())
.map_err(|e| AppError::LinkCreationError(e.to_string()))
}

pub fn load_link(
root: &PathBuf,
file_path: &Option<PathBuf>,
id: &Option<ResourceId>,
) -> Result<Link, String> {
) -> Result<Link, AppError> {
let path_from_index = id.map(|id| {
let index = provide_index(&root);
let index = provide_index(root);
index.id2path[&id].as_path().to_path_buf()
});
let path_from_user = file_path;

let path = match (path_from_user, path_from_index) {
(Some(path), Some(path2)) => {
if path.canonicalize().unwrap() != path2 {
Err(format!(
if path.canonicalize()? != path2 {
Err(AppError::LinkLoadError(format!(
"Path {:?} was requested. But id {} maps to path {:?}",
path,
id.unwrap(),
path2,
))
)))
} else {
Ok(path.to_path_buf())
}
}
(Some(path), None) => Ok(path.to_path_buf()),
(None, Some(path)) => Ok(path),
(None, None) => Err("Provide a path or id for request.".to_owned())?,
(None, None) => Err(AppError::LinkLoadError(
"Provide a path or id for request.".to_owned(),
))?,
}?;

arklib::link::Link::load(root, &path).map_err(|e| e.to_string())
Ok(arklib::link::Link::load(root, &path)?)
}
57 changes: 57 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use arklib::ArklibError;
use std::io;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum InlineJsonParseError {
#[error("Invalid JSON: entries must be key-value pairs seperated by ':'")]
InvalidKeyValPair,
}

#[derive(Debug, Error)]
pub enum AppError {
#[error("Couldn't retrieve home directory!")]
HomeDirNotFound,

#[error("Couldn't create .ark directory: {0}")]
ArkDirectoryCreationError(String),

#[error("Couldn't load app id: {0}")]
AppIdLoadError(String),

#[error("Could not provide/read index: {0}")]
IndexError(String),

#[error("Could not create storage: {0}")]
StorageCreationError(String),

#[error("Failed to create link: {0}")]
LinkCreationError(String),

#[error("Could not load link: {0}")]
LinkLoadError(String),

#[error("File operation error: {0}")]
FileOperationError(String),

#[error("Failed to create backup: {0}")]
BackupCreationError(String),

#[error("Unknown render option")]
InvalidRenderOption,

#[error("Storage not found: {0}")]
StorageNotFound(String),

#[error("Invalid entry option")]
InvalidEntryOption,

#[error(transparent)]
IoError(#[from] io::Error),

#[error(transparent)]
ArklibError(#[from] ArklibError),

#[error(transparent)]
InlineJsonParseError(#[from] InlineJsonParseError),
}
Loading

0 comments on commit 95f7fad

Please sign in to comment.