Use cargo workspaces
This commit is contained in:
@@ -1,42 +0,0 @@
|
||||
use config::{Config, ConfigError, Environment, File};
|
||||
use serde::Deserialize;
|
||||
use std::env;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Settings {
|
||||
pub application: ApplicationSettings,
|
||||
pub taskwarrior: TaskwarriorSettings,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ApplicationSettings {
|
||||
pub port: u16,
|
||||
pub log_directive: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TaskwarriorSettings {
|
||||
pub data_location: Option<String>,
|
||||
pub taskrc: Option<String>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn new_from_file(file: Option<String>) -> Result<Self, ConfigError> {
|
||||
let config_file_required = file.is_some();
|
||||
let config_file =
|
||||
file.unwrap_or_else(|| env::var("CONFIG").unwrap_or_else(|_| "dev".into()));
|
||||
|
||||
let config = Config::builder()
|
||||
.add_source(File::with_name("config/default"))
|
||||
.add_source(File::with_name("config/local").required(false))
|
||||
.add_source(File::with_name(&config_file).required(config_file_required))
|
||||
.add_source(Environment::with_prefix("cs"))
|
||||
.build()?;
|
||||
|
||||
config.try_deserialize()
|
||||
}
|
||||
|
||||
pub fn new() -> Result<Self, ConfigError> {
|
||||
Settings::new_from_file(None)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
use crate::contextswitch::taskwarrior;
|
||||
use contextswitch_types::Task;
|
||||
use serde_json;
|
||||
|
||||
fn error_chain_fmt(
|
||||
e: &impl std::error::Error,
|
||||
f: &mut std::fmt::Formatter<'_>,
|
||||
) -> std::fmt::Result {
|
||||
writeln!(f, "{}\n", e)?;
|
||||
let mut current = e.source();
|
||||
while let Some(cause) = current {
|
||||
writeln!(f, "Caused by:\n\t{}", cause)?;
|
||||
current = cause.source();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ContextswitchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
error_chain_fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error)]
|
||||
pub enum ContextswitchError {
|
||||
#[error("Invalid Contextswitch data")]
|
||||
InvalidDataError(#[from] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
UnexpectedError(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<Task>, ContextswitchError> {
|
||||
let tasks: Vec<Task> = taskwarrior::list_tasks(filters)
|
||||
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?
|
||||
.iter()
|
||||
.map(Task::from)
|
||||
.collect();
|
||||
Ok(tasks)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn add_task(add_args: Vec<&str>) -> Result<Task, ContextswitchError> {
|
||||
let taskwarrior_task = taskwarrior::add_task(add_args)
|
||||
.await
|
||||
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?;
|
||||
Ok(taskwarrior_task.into())
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn update_task(task_to_update: Task) -> Result<Task, ContextswitchError> {
|
||||
let taskwarrior_task = taskwarrior::update_task(task_to_update.try_into()?)
|
||||
.await
|
||||
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?;
|
||||
Ok(taskwarrior_task.into())
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
mod api;
|
||||
pub mod taskwarrior;
|
||||
|
||||
pub use api::*;
|
||||
@@ -1,633 +0,0 @@
|
||||
use crate::configuration::TaskwarriorSettings;
|
||||
use anyhow::{anyhow, Context};
|
||||
use chrono::{DateTime, Utc};
|
||||
use configparser::ini::Ini;
|
||||
use contextswitch_types::{ContextswitchData, Task, TaskId};
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
use std::env;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::str;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::ContextswitchError;
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<TaskwarriorTask>, TaskwarriorError> {
|
||||
let args = [filters, vec!["export"]].concat();
|
||||
let export_output = Command::new("task")
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(TaskwarriorError::ExecutionError)?;
|
||||
|
||||
let output =
|
||||
String::from_utf8(export_output.stdout).context("Failed to read Taskwarrior output")?;
|
||||
|
||||
let tasks: Vec<TaskwarriorTask> = serde_json::from_str(&output)
|
||||
.map_err(|e| TaskwarriorError::OutputParsingError { source: e, output })?;
|
||||
|
||||
Ok(tasks)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn get_task_by_local_id(
|
||||
id: &TaskwarriorTaskLocalId,
|
||||
) -> Result<Option<TaskwarriorTask>, TaskwarriorError> {
|
||||
let mut tasks: Vec<TaskwarriorTask> = list_tasks(vec![&id.to_string()])?;
|
||||
if tasks.len() > 1 {
|
||||
return Err(TaskwarriorError::UnexpectedError(anyhow!(
|
||||
"Found more than 1 task when searching for task with local ID {}",
|
||||
id
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(tasks.pop())
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn get_task_by_id(
|
||||
uuid: &TaskwarriorTaskId,
|
||||
) -> Result<Option<TaskwarriorTask>, TaskwarriorError> {
|
||||
let mut tasks: Vec<TaskwarriorTask> = list_tasks(vec![&uuid.to_string()])?;
|
||||
if tasks.len() > 1 {
|
||||
return Err(TaskwarriorError::UnexpectedError(anyhow!(
|
||||
"Found more than 1 task when searching for task with UUID {}",
|
||||
uuid
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(tasks.pop())
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref RE: Regex = Regex::new(r"Modified 1 task.").unwrap();
|
||||
static ref TW_WRITE_LOCK: Mutex<u32> = Mutex::new(0);
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn add_task(add_args: Vec<&str>) -> Result<TaskwarriorTask, TaskwarriorError> {
|
||||
lazy_static! {
|
||||
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
|
||||
}
|
||||
let _lock = TW_WRITE_LOCK.lock().await;
|
||||
|
||||
let args = [vec!["add"], add_args].concat();
|
||||
let add_output = Command::new("task")
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(TaskwarriorError::ExecutionError)?;
|
||||
let output =
|
||||
String::from_utf8(add_output.stdout).context("Failed to read Taskwarrior output")?;
|
||||
let task_id_capture = RE
|
||||
.captures(&output)
|
||||
.ok_or_else(|| anyhow!("Cannot extract task ID from: {}", &output))?;
|
||||
let task_id_str = task_id_capture
|
||||
.name("id")
|
||||
.ok_or_else(|| anyhow!("Cannot extract task ID value from: {}", &output))?
|
||||
.as_str();
|
||||
|
||||
let task_id = TaskwarriorTaskLocalId(
|
||||
task_id_str
|
||||
.parse::<u64>()
|
||||
.context("Cannot parse task ID value")?,
|
||||
);
|
||||
|
||||
let task = get_task_by_local_id(&task_id)?;
|
||||
task.ok_or_else(|| {
|
||||
TaskwarriorError::UnexpectedError(anyhow!(
|
||||
"Newly created task with ID {} was not found",
|
||||
task_id
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn update_task(action: TaskwarriorAction) -> Result<TaskwarriorTask, TaskwarriorError> {
|
||||
lazy_static! {
|
||||
static ref RE: Regex = Regex::new(r"Modified 1 task.").unwrap();
|
||||
}
|
||||
|
||||
let _lock = TW_WRITE_LOCK.lock().await;
|
||||
let args = [
|
||||
vec![action.uuid.to_string(), "mod".to_string()],
|
||||
action.args,
|
||||
]
|
||||
.concat();
|
||||
Command::new("task")
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(TaskwarriorError::ExecutionError)?;
|
||||
|
||||
let updated_task = get_task_by_id(&action.uuid)?;
|
||||
updated_task.ok_or_else(|| {
|
||||
TaskwarriorError::UnexpectedError(anyhow!(
|
||||
"Updated task with UUID {} was not found",
|
||||
action.uuid
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
// Types
|
||||
// TaskwarriorTask
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct TaskwarriorTaskLocalId(pub u64);
|
||||
|
||||
impl fmt::Display for TaskwarriorTaskLocalId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct TaskwarriorTaskId(pub Uuid);
|
||||
|
||||
impl fmt::Display for TaskwarriorTaskId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TaskwarriorTaskId> for TaskId {
|
||||
fn from(task: TaskwarriorTaskId) -> Self {
|
||||
TaskId(task.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TaskId> for TaskwarriorTaskId {
|
||||
fn from(task: TaskId) -> Self {
|
||||
TaskwarriorTaskId(task.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TaskwarriorTask {
|
||||
pub uuid: TaskwarriorTaskId,
|
||||
pub id: TaskwarriorTaskLocalId,
|
||||
#[serde(with = "contextswitch_types::tw_date_format")]
|
||||
pub entry: DateTime<Utc>,
|
||||
#[serde(with = "contextswitch_types::tw_date_format")]
|
||||
pub modified: DateTime<Utc>,
|
||||
pub status: contextswitch_types::Status,
|
||||
pub description: String,
|
||||
pub urgency: f64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch_types::opt_tw_date_format"
|
||||
)]
|
||||
pub due: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch_types::opt_tw_date_format"
|
||||
)]
|
||||
pub start: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch_types::opt_tw_date_format"
|
||||
)]
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch_types::opt_tw_date_format"
|
||||
)]
|
||||
pub wait: Option<DateTime<Utc>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<TaskwarriorTaskId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub project: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub priority: Option<contextswitch_types::Priority>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recur: Option<contextswitch_types::Recurrence>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tags: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub contextswitch: Option<String>,
|
||||
}
|
||||
|
||||
impl From<TaskwarriorTask> for Task {
|
||||
fn from(task: TaskwarriorTask) -> Self {
|
||||
(&task).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&TaskwarriorTask> for Task {
|
||||
fn from(task: &TaskwarriorTask) -> Self {
|
||||
let cs_data =
|
||||
task.contextswitch
|
||||
.as_ref()
|
||||
.and_then(|cs_string| -> Option<ContextswitchData> {
|
||||
let contextswitch_data_result = serde_json::from_str(cs_string);
|
||||
if contextswitch_data_result.is_err() {
|
||||
warn!(
|
||||
"Invalid Contextswitch data found in {}: {}",
|
||||
&task.uuid, cs_string
|
||||
);
|
||||
}
|
||||
contextswitch_data_result.ok()
|
||||
});
|
||||
|
||||
Task {
|
||||
id: task.uuid.clone().into(),
|
||||
entry: task.entry,
|
||||
modified: task.modified,
|
||||
status: task.status,
|
||||
description: task.description.clone(),
|
||||
urgency: task.urgency,
|
||||
due: task.due,
|
||||
start: task.start,
|
||||
end: task.end,
|
||||
wait: task.wait,
|
||||
parent: task.parent.clone().map(|id| id.into()),
|
||||
project: task.project.clone(),
|
||||
priority: task.priority,
|
||||
recur: task.recur,
|
||||
tags: task.tags.clone(),
|
||||
contextswitch: cs_data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TaskwarriorAction
|
||||
#[derive(Debug)]
|
||||
pub struct TaskwarriorAction {
|
||||
pub uuid: TaskwarriorTaskId,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
fn to_arg(arg: &str) -> impl Fn(String) -> String + '_ {
|
||||
move |value: String| format!("{}:{}", arg, value)
|
||||
}
|
||||
|
||||
fn format_date(date: DateTime<Utc>) -> String {
|
||||
date.format("%Y-%m-%dT%H:%M:%SZ").to_string()
|
||||
}
|
||||
|
||||
impl TryFrom<Task> for TaskwarriorAction {
|
||||
type Error = ContextswitchError;
|
||||
|
||||
fn try_from(task: Task) -> Result<Self, Self::Error> {
|
||||
(&task).try_into()
|
||||
}
|
||||
}
|
||||
|
||||
fn format_json<T>(data_opt: &Option<T>) -> Result<Option<String>, ContextswitchError>
|
||||
where
|
||||
T: Sized + Serialize,
|
||||
{
|
||||
data_opt
|
||||
.as_ref()
|
||||
.map(|data| serde_json::to_string(data).map_err(ContextswitchError::InvalidDataError))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
impl TryFrom<&Task> for TaskwarriorAction {
|
||||
type Error = ContextswitchError;
|
||||
|
||||
fn try_from(task: &Task) -> Result<Self, Self::Error> {
|
||||
let args = vec![task.description.clone()];
|
||||
let tags_args = task
|
||||
.tags
|
||||
.clone()
|
||||
.map(|tags| {
|
||||
tags.iter()
|
||||
.map(|tag| format!("+{}", tag)) // TODO remove tags
|
||||
.collect::<Vec<String>>()
|
||||
})
|
||||
.unwrap_or_else(Vec::new);
|
||||
let opt_args = [
|
||||
task.due
|
||||
.map(format_date)
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("due")),
|
||||
task.start
|
||||
.map(format_date)
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("start")),
|
||||
task.end
|
||||
.map(format_date)
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("end")),
|
||||
task.wait
|
||||
.map(format_date)
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("wait")),
|
||||
task.parent
|
||||
.as_ref()
|
||||
.map(|id| id.to_string())
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("parent")),
|
||||
task.project
|
||||
.clone()
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("project")),
|
||||
task.priority
|
||||
.map(|priority| priority.to_string())
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("priority")),
|
||||
task.recur
|
||||
.map(|recur| recur.to_string())
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("recur")),
|
||||
format_json(&task.contextswitch)?
|
||||
.or_else(|| Some("".to_string()))
|
||||
.map(to_arg("contextswitch")),
|
||||
];
|
||||
|
||||
Ok(TaskwarriorAction {
|
||||
uuid: task.id.clone().into(),
|
||||
args: [
|
||||
args,
|
||||
tags_args,
|
||||
opt_args
|
||||
.iter()
|
||||
.filter_map(|arg| arg.clone())
|
||||
.collect::<Vec<String>>(),
|
||||
]
|
||||
.concat(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Errors
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum TaskwarriorError {
|
||||
#[error("Error while executing Taskwarrior")]
|
||||
ExecutionError(#[from] std::io::Error),
|
||||
#[error("Error while parsing Taskwarrior output")]
|
||||
OutputParsingError {
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
output: String,
|
||||
},
|
||||
#[error(transparent)]
|
||||
UnexpectedError(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
// Taskwarrior config functions
|
||||
fn write_default_config(data_location: &str) -> String {
|
||||
let mut taskrc = Ini::new();
|
||||
taskrc.setstr("default", "data.location", Some(data_location));
|
||||
taskrc.setstr("default", "uda.contextswitch.type", Some("string"));
|
||||
taskrc.setstr(
|
||||
"default",
|
||||
"uda.contextswitch.label",
|
||||
Some("Contextswitch data"),
|
||||
);
|
||||
taskrc.setstr("default", "uda.contextswitch.default", Some("{}"));
|
||||
|
||||
let taskrc_path = Path::new(&data_location).join(".taskrc");
|
||||
let taskrc_location = taskrc_path.to_str().unwrap();
|
||||
taskrc.write(taskrc_location).unwrap();
|
||||
|
||||
taskrc_location.into()
|
||||
}
|
||||
|
||||
pub fn load_config(settings: &TaskwarriorSettings) -> String {
|
||||
if let Some(taskrc_location) = &settings.taskrc {
|
||||
let mut taskrc = Ini::new();
|
||||
taskrc
|
||||
.load(&taskrc_location)
|
||||
.unwrap_or_else(|_| panic!("Cannot load taskrc file {}", taskrc_location));
|
||||
let data_location = taskrc.get("default", "data.location").unwrap_or_else(|| {
|
||||
panic!(
|
||||
"'data.location' must be set in taskrc file {}",
|
||||
taskrc_location
|
||||
)
|
||||
});
|
||||
|
||||
env::set_var("TASKRC", &taskrc_location);
|
||||
debug!(
|
||||
"Extracted data location `{}` from existing taskrc `{}`",
|
||||
data_location, taskrc_location
|
||||
);
|
||||
|
||||
data_location
|
||||
} else {
|
||||
let data_location = settings
|
||||
.data_location
|
||||
.as_ref()
|
||||
.expect("Expecting taskwarrior.taskrc or taskwarrior.data_location setting to be set")
|
||||
.to_string();
|
||||
let taskrc_location = write_default_config(&data_location);
|
||||
|
||||
env::set_var("TASKRC", &taskrc_location);
|
||||
debug!("Default taskrc written in `{}`", &taskrc_location);
|
||||
|
||||
data_location
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
mod from_taskwarrior_task_to_contextswitch_task {
|
||||
use super::super::*;
|
||||
use chrono::TimeZone;
|
||||
use contextswitch_types::Bookmark;
|
||||
use http::uri::Uri;
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn test_successful_full_convertion() {
|
||||
let tw_task = TaskwarriorTask {
|
||||
uuid: TaskwarriorTaskId(Uuid::new_v4()),
|
||||
id: TaskwarriorTaskLocalId(42),
|
||||
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
|
||||
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
|
||||
status: contextswitch_types::Status::Pending,
|
||||
description: "simple task".to_string(),
|
||||
urgency: 0.5,
|
||||
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),
|
||||
start: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 3)),
|
||||
end: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 4)),
|
||||
wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)),
|
||||
parent: Some(TaskwarriorTaskId(Uuid::new_v4())),
|
||||
project: Some("simple project".to_string()),
|
||||
priority: Some(contextswitch_types::Priority::H),
|
||||
recur: Some(contextswitch_types::Recurrence::Daily),
|
||||
tags: Some(vec!["tag1".to_string(), "tag2".to_string()]),
|
||||
contextswitch: Some(String::from(
|
||||
r#"{"bookmarks": [{"uri": "https://www.example.com/path"}]}"#,
|
||||
)),
|
||||
};
|
||||
let cs_task: Task = (&tw_task).into();
|
||||
|
||||
assert_eq!(tw_task.uuid.0, cs_task.id.0);
|
||||
assert_eq!(tw_task.entry, cs_task.entry);
|
||||
assert_eq!(tw_task.modified, cs_task.modified);
|
||||
assert_eq!(tw_task.status, cs_task.status);
|
||||
assert_eq!(tw_task.description, cs_task.description);
|
||||
assert_eq!(tw_task.urgency, cs_task.urgency);
|
||||
assert_eq!(tw_task.due, cs_task.due);
|
||||
assert_eq!(tw_task.start, cs_task.start);
|
||||
assert_eq!(tw_task.end, cs_task.end);
|
||||
assert_eq!(tw_task.wait, cs_task.wait);
|
||||
assert_eq!(
|
||||
tw_task.parent.map(|id| id.to_string()),
|
||||
cs_task.parent.map(|id| id.to_string())
|
||||
);
|
||||
assert_eq!(tw_task.project, cs_task.project);
|
||||
assert_eq!(tw_task.priority, cs_task.priority);
|
||||
assert_eq!(tw_task.recur, cs_task.recur);
|
||||
assert_eq!(tw_task.tags, cs_task.tags);
|
||||
assert_eq!(
|
||||
Some(ContextswitchData {
|
||||
bookmarks: vec![Bookmark {
|
||||
uri: "https://www.example.com/path".parse::<Uri>().unwrap(),
|
||||
content: None
|
||||
}]
|
||||
}),
|
||||
cs_task.contextswitch
|
||||
);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn test_conversion_with_invalid_contextswitch_data_format(cs_data in ".*") {
|
||||
let tw_task = TaskwarriorTask {
|
||||
uuid: TaskwarriorTaskId(Uuid::new_v4()),
|
||||
id: TaskwarriorTaskLocalId(42),
|
||||
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
|
||||
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
|
||||
status: contextswitch_types::Status::Pending,
|
||||
description: "simple task".to_string(),
|
||||
urgency: 0.5,
|
||||
due: None,
|
||||
start: None,
|
||||
end: None,
|
||||
wait: None,
|
||||
parent: None,
|
||||
project: None,
|
||||
priority: None,
|
||||
recur: None,
|
||||
tags: None,
|
||||
contextswitch: Some(cs_data),
|
||||
};
|
||||
let cs_task: Task = (&tw_task).into();
|
||||
|
||||
assert_eq!(tw_task.uuid.0, cs_task.id.0);
|
||||
assert_eq!(tw_task.entry, cs_task.entry);
|
||||
assert_eq!(tw_task.modified, cs_task.modified);
|
||||
assert_eq!(tw_task.status, cs_task.status);
|
||||
assert_eq!(tw_task.description, cs_task.description);
|
||||
assert_eq!(tw_task.urgency, cs_task.urgency);
|
||||
assert_eq!(None, cs_task.contextswitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod from_contextswitch_task_to_taskwarrior_action {
|
||||
use super::super::*;
|
||||
use chrono::TimeZone;
|
||||
use contextswitch_types::{Bookmark, Priority, Recurrence};
|
||||
use http::Uri;
|
||||
|
||||
#[test]
|
||||
fn test_successful_convertion() {
|
||||
let task = Task {
|
||||
id: TaskId(Uuid::new_v4()),
|
||||
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
|
||||
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
|
||||
status: contextswitch_types::Status::Pending,
|
||||
description: "simple task".to_string(),
|
||||
urgency: 0.5,
|
||||
due: None,
|
||||
start: None,
|
||||
end: None,
|
||||
wait: None,
|
||||
parent: None,
|
||||
project: None,
|
||||
priority: None,
|
||||
recur: None,
|
||||
tags: None,
|
||||
contextswitch: None,
|
||||
};
|
||||
let action: TaskwarriorAction = (&task)
|
||||
.try_into()
|
||||
.expect("Failed to convert Task into TaskwarriorAction");
|
||||
|
||||
assert_eq!(task.id.0, action.uuid.0);
|
||||
assert_eq!(
|
||||
vec![
|
||||
task.description,
|
||||
"due:".to_string(),
|
||||
"start:".to_string(),
|
||||
"end:".to_string(),
|
||||
"wait:".to_string(),
|
||||
"parent:".to_string(),
|
||||
"project:".to_string(),
|
||||
"priority:".to_string(),
|
||||
"recur:".to_string(),
|
||||
"contextswitch:".to_string(),
|
||||
],
|
||||
action.args
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_successful_full_convertion() {
|
||||
let task = Task {
|
||||
id: TaskId(Uuid::new_v4()),
|
||||
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
|
||||
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
|
||||
status: contextswitch_types::Status::Pending,
|
||||
description: "simple task".to_string(),
|
||||
urgency: 0.5,
|
||||
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),
|
||||
start: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 3)),
|
||||
end: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 4)),
|
||||
wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)),
|
||||
parent: Some(TaskId(Uuid::new_v4())),
|
||||
project: Some("myproject".to_string()),
|
||||
priority: Some(Priority::H),
|
||||
recur: Some(Recurrence::Monthly),
|
||||
tags: Some(vec!["tag1".to_string(), "tag2".to_string()]),
|
||||
contextswitch: Some(ContextswitchData {
|
||||
bookmarks: vec![
|
||||
Bookmark {
|
||||
uri: "https://www.example.com/path".parse::<Uri>().unwrap(),
|
||||
content: None,
|
||||
},
|
||||
Bookmark {
|
||||
uri: "https://www.example.com/path2".parse::<Uri>().unwrap(),
|
||||
content: None,
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
let action: TaskwarriorAction = (&task)
|
||||
.try_into()
|
||||
.expect("Failed to convert Task into TaskwarriorAction");
|
||||
|
||||
assert_eq!(task.id.0, action.uuid.0);
|
||||
assert_eq!(
|
||||
vec![
|
||||
task.description,
|
||||
"+tag1".to_string(),
|
||||
"+tag2".to_string(),
|
||||
"due:2022-01-01T01:00:02Z".to_string(),
|
||||
"start:2022-01-01T01:00:03Z".to_string(),
|
||||
"end:2022-01-01T01:00:04Z".to_string(),
|
||||
"wait:2022-01-01T01:00:05Z".to_string(),
|
||||
format!("parent:{}", task.parent.unwrap()),
|
||||
"project:myproject".to_string(),
|
||||
"priority:H".to_string(),
|
||||
"recur:monthly".to_string(),
|
||||
String::from(
|
||||
r#"contextswitch:{"bookmarks":[{"uri":"https://www.example.com/path"},{"uri":"https://www.example.com/path2"}]}"#
|
||||
)
|
||||
],
|
||||
action.args
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
250
src/lib.rs
250
src/lib.rs
@@ -1,52 +1,202 @@
|
||||
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
|
||||
use listenfd::ListenFd;
|
||||
use std::env;
|
||||
use std::net::TcpListener;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
use chrono::{DateTime, Utc};
|
||||
use http::uri::Uri;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
pub mod configuration;
|
||||
pub mod contextswitch;
|
||||
pub mod observability;
|
||||
pub mod routes;
|
||||
|
||||
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
||||
let cs_front_base_url =
|
||||
env::var("CS_FRONT_BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string());
|
||||
let mut server = HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(TracingLogger::default())
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new()
|
||||
.add(("Access-Control-Allow-Origin", cs_front_base_url.as_bytes()))
|
||||
.add((
|
||||
"Access-Control-Allow-Methods",
|
||||
"POST, GET, OPTIONS".as_bytes(),
|
||||
))
|
||||
.add(("Access-Control-Allow-Headers", "content-type".as_bytes())),
|
||||
)
|
||||
.route("/ping", web::get().to(routes::ping))
|
||||
.route("/tasks", web::get().to(routes::list_tasks))
|
||||
.route("/tasks", web::post().to(routes::add_task))
|
||||
.route("/tasks/{task_id}", web::put().to(routes::update_task))
|
||||
.route(
|
||||
"/tasks",
|
||||
web::method(http::Method::OPTIONS).to(routes::option_task),
|
||||
)
|
||||
})
|
||||
.keep_alive(60)
|
||||
.shutdown_timeout(60);
|
||||
|
||||
let mut listenfd = ListenFd::from_env();
|
||||
|
||||
server = if let Some(fdlistener) = listenfd.take_tcp_listener(0)? {
|
||||
server.listen(fdlistener)?
|
||||
} else {
|
||||
server.listen(listener)?
|
||||
};
|
||||
|
||||
Ok(server.run())
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Recurrence {
|
||||
Daily,
|
||||
Weekly,
|
||||
Monthly,
|
||||
Yearly,
|
||||
}
|
||||
|
||||
impl fmt::Display for Recurrence {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", format!("{:?}", self).to_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Pending,
|
||||
Completed,
|
||||
Recurring,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
impl fmt::Display for Status {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", format!("{:?}", self).to_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
pub enum Priority {
|
||||
H,
|
||||
M,
|
||||
L,
|
||||
}
|
||||
|
||||
impl fmt::Display for Priority {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct Bookmark {
|
||||
#[serde(with = "uri")]
|
||||
pub uri: Uri,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<BookmarkContent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct BookmarkContent {
|
||||
pub title: String,
|
||||
pub content_preview: Option<String>,
|
||||
}
|
||||
|
||||
pub mod uri {
|
||||
use http::uri::Uri;
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S>(uri: &Uri, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let uri_str = uri.to_string();
|
||||
serializer.serialize_str(&uri_str)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Uri, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
s.parse::<Uri>().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct ContextswitchData {
|
||||
pub bookmarks: Vec<Bookmark>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
|
||||
pub struct TaskId(pub Uuid);
|
||||
|
||||
impl fmt::Display for TaskId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
pub struct Task {
|
||||
pub id: TaskId,
|
||||
#[serde(with = "tw_date_format")]
|
||||
pub entry: DateTime<Utc>,
|
||||
#[serde(with = "tw_date_format")]
|
||||
pub modified: DateTime<Utc>,
|
||||
pub status: Status,
|
||||
pub description: String,
|
||||
pub urgency: f64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "opt_tw_date_format"
|
||||
)]
|
||||
pub due: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "opt_tw_date_format"
|
||||
)]
|
||||
pub start: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "opt_tw_date_format"
|
||||
)]
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "opt_tw_date_format"
|
||||
)]
|
||||
pub wait: Option<DateTime<Utc>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<TaskId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub project: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub priority: Option<Priority>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recur: Option<Recurrence>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tags: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub contextswitch: Option<ContextswitchData>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct NewTask {
|
||||
pub definition: String,
|
||||
}
|
||||
|
||||
pub mod tw_date_format {
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
|
||||
const FORMAT: &str = "%Y%m%dT%H%M%SZ";
|
||||
|
||||
pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let s = format!("{}", date.format(FORMAT));
|
||||
serializer.serialize_str(&s)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Utc.datetime_from_str(&s, FORMAT)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod opt_tw_date_format {
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
|
||||
const FORMAT: &str = "%Y%m%dT%H%M%SZ";
|
||||
|
||||
pub fn serialize<S>(date: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
if let Some(ref d) = *date {
|
||||
return serializer.serialize_str(&d.format(FORMAT).to_string());
|
||||
}
|
||||
|
||||
serializer.serialize_none()
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Utc.datetime_from_str(&s, FORMAT)
|
||||
.map(Some)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
19
src/main.rs
19
src/main.rs
@@ -1,19 +0,0 @@
|
||||
extern crate listenfd;
|
||||
|
||||
use contextswitch_api::configuration::Settings;
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::{contextswitch::taskwarrior, run};
|
||||
use std::net::TcpListener;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let settings = Settings::new().expect("Cannot load Contextswitch configuration");
|
||||
let subscriber = get_subscriber(&settings.application.log_directive);
|
||||
init_subscriber(subscriber);
|
||||
|
||||
taskwarrior::load_config(&settings.taskwarrior);
|
||||
|
||||
let listener = TcpListener::bind(format!("0.0.0.0:{}", settings.application.port))
|
||||
.expect("Failed to bind port");
|
||||
run(listener)?.await
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
use tracing::{subscriber::set_global_default, Subscriber};
|
||||
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
|
||||
use tracing_log::LogTracer;
|
||||
use tracing_subscriber::fmt::TestWriter;
|
||||
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
||||
|
||||
pub fn get_subscriber(env_filter_str: &str) -> impl Subscriber + Send + Sync {
|
||||
let formatting_layer = BunyanFormattingLayer::new("contextswitch-api".into(), TestWriter::new);
|
||||
|
||||
let env_filter =
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter_str));
|
||||
|
||||
tracing_subscriber::registry()
|
||||
.with(env_filter)
|
||||
.with(JsonStorageLayer)
|
||||
.with(formatting_layer)
|
||||
}
|
||||
|
||||
pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {
|
||||
LogTracer::init().expect("Failed to set logger");
|
||||
set_global_default(subscriber).expect("Failed to set subscriber");
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use actix_web::HttpResponse;
|
||||
|
||||
pub async fn ping() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
mod health_check;
|
||||
mod tasks;
|
||||
|
||||
pub use health_check::*;
|
||||
pub use tasks::*;
|
||||
@@ -1,70 +0,0 @@
|
||||
use crate::contextswitch;
|
||||
use actix_web::{http::StatusCode, web, HttpResponse, ResponseError};
|
||||
use anyhow::Context;
|
||||
use contextswitch_types::{NewTask, Task, TaskId};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TaskQuery {
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
impl ResponseError for contextswitch::ContextswitchError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
contextswitch::ContextswitchError::InvalidDataError { .. } => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
contextswitch::ContextswitchError::UnexpectedError(_) => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(filter = %task_query.filter.as_ref().unwrap_or(&"".to_string())))]
|
||||
pub async fn list_tasks(
|
||||
task_query: web::Query<TaskQuery>,
|
||||
) -> Result<HttpResponse, contextswitch::ContextswitchError> {
|
||||
let filter = task_query
|
||||
.filter
|
||||
.as_ref()
|
||||
.map_or(vec![], |filter| filter.split(' ').collect());
|
||||
let tasks: Vec<Task> = contextswitch::list_tasks(filter)?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&tasks).context("Cannot serialize Contextswitch task")?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(definition = %new_task.definition))]
|
||||
pub async fn add_task(
|
||||
new_task: web::Json<NewTask>,
|
||||
) -> Result<HttpResponse, contextswitch::ContextswitchError> {
|
||||
let task: Task = contextswitch::add_task(new_task.definition.split(' ').collect()).await?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&task).context("Cannot serialize Contextswitch task")?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all)]
|
||||
pub async fn update_task(
|
||||
path: web::Path<TaskId>,
|
||||
task: web::Json<Task>,
|
||||
) -> Result<HttpResponse, contextswitch::ContextswitchError> {
|
||||
let task_to_update = task.into_inner();
|
||||
if path.into_inner() != task_to_update.id {
|
||||
return Ok(HttpResponse::BadRequest().finish());
|
||||
}
|
||||
let task_updated: Task = contextswitch::update_task(task_to_update).await?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&task_updated).context("Cannot serialize Contextswitch task")?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn option_task() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
Reference in New Issue
Block a user