Refactor modules
This commit is contained in:
@@ -1,49 +0,0 @@
|
||||
use crate::taskwarrior;
|
||||
use contextswitch_types::{ContextSwitchMetadata, Task};
|
||||
use std::io::Error;
|
||||
|
||||
impl TryFrom<&taskwarrior::Task> for Task {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(task: &taskwarrior::Task) -> Result<Self, Self::Error> {
|
||||
let cs_metadata = task.contextswitch.as_ref().map_or(
|
||||
Ok(None),
|
||||
|cs_string| -> Result<Option<ContextSwitchMetadata>, serde_json::Error> {
|
||||
if cs_string.is_empty() || cs_string == "{}" {
|
||||
Ok(None)
|
||||
} else {
|
||||
Some(serde_json::from_str(cs_string)).transpose()
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(Task {
|
||||
uuid: task.uuid,
|
||||
id: task.id,
|
||||
entry: task.entry,
|
||||
modified: task.modified,
|
||||
status: task.status,
|
||||
description: task.description.clone(),
|
||||
urgency: task.urgency,
|
||||
due: task.due,
|
||||
end: task.end,
|
||||
parent: task.parent,
|
||||
project: task.project.clone(),
|
||||
recur: task.recur,
|
||||
tags: task.tags.clone(),
|
||||
contextswitch: cs_metadata,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
|
||||
let tasks: Result<Vec<Task>, Error> = taskwarrior::export(filters)?
|
||||
.iter()
|
||||
.map(Task::try_from)
|
||||
.collect();
|
||||
tasks
|
||||
}
|
||||
|
||||
pub async fn add(add_args: Vec<&str>) -> Result<u64, Error> {
|
||||
taskwarrior::add(add_args).await
|
||||
}
|
||||
17
src/contextswitch/api.rs
Normal file
17
src/contextswitch/api.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use crate::contextswitch::taskwarrior;
|
||||
use contextswitch_types::Task;
|
||||
use std::io::Error;
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
|
||||
let tasks: Result<Vec<Task>, Error> = taskwarrior::list_tasks(filters)?
|
||||
.iter()
|
||||
.map(Task::try_from)
|
||||
.collect();
|
||||
tasks
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn add_task(add_args: Vec<&str>) -> Result<u64, Error> {
|
||||
taskwarrior::add_task(add_args).await
|
||||
}
|
||||
4
src/contextswitch/mod.rs
Normal file
4
src/contextswitch/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
mod api;
|
||||
pub mod taskwarrior;
|
||||
|
||||
pub use api::*;
|
||||
@@ -1,5 +1,7 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use configparser::ini::Ini;
|
||||
use contextswitch_types::ContextSwitchMetadata;
|
||||
use contextswitch_types::Task;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json;
|
||||
@@ -13,7 +15,7 @@ use tracing::debug;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Task {
|
||||
pub struct TaskwarriorTask {
|
||||
pub uuid: Uuid,
|
||||
pub id: u64,
|
||||
#[serde(with = "contextswitch_types::tw_date_format")]
|
||||
@@ -47,6 +49,40 @@ pub struct Task {
|
||||
pub contextswitch: Option<String>,
|
||||
}
|
||||
|
||||
impl TryFrom<&TaskwarriorTask> for Task {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(task: &TaskwarriorTask) -> Result<Self, Self::Error> {
|
||||
let cs_metadata = task.contextswitch.as_ref().map_or(
|
||||
Ok(None),
|
||||
|cs_string| -> Result<Option<ContextSwitchMetadata>, serde_json::Error> {
|
||||
if cs_string.is_empty() || cs_string == "{}" {
|
||||
Ok(None)
|
||||
} else {
|
||||
Some(serde_json::from_str(cs_string)).transpose()
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(Task {
|
||||
uuid: task.uuid,
|
||||
id: task.id,
|
||||
entry: task.entry,
|
||||
modified: task.modified,
|
||||
status: task.status,
|
||||
description: task.description.clone(),
|
||||
urgency: task.urgency,
|
||||
due: task.due,
|
||||
end: task.end,
|
||||
parent: task.parent,
|
||||
project: task.project.clone(),
|
||||
recur: task.recur,
|
||||
tags: task.tags.clone(),
|
||||
contextswitch: cs_metadata,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn write_default_config(data_location: &str) -> String {
|
||||
let mut taskrc = Ini::new();
|
||||
taskrc.setstr("default", "data.location", Some(data_location));
|
||||
@@ -100,17 +136,17 @@ pub fn load_config(task_data_location: Option<&str>) -> String {
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
|
||||
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<TaskwarriorTask>, Error> {
|
||||
let args = [filters, vec!["export"]].concat();
|
||||
let export_output = Command::new("task").args(args).output()?;
|
||||
|
||||
let tasks: Vec<Task> = serde_json::from_slice(&export_output.stdout)?;
|
||||
let tasks: Vec<TaskwarriorTask> = serde_json::from_slice(&export_output.stdout)?;
|
||||
|
||||
Ok(tasks)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub async fn add(add_args: Vec<&str>) -> Result<u64, Error> {
|
||||
pub async fn add_task(add_args: Vec<&str>) -> Result<u64, Error> {
|
||||
lazy_static! {
|
||||
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
|
||||
static ref LOCK: Mutex<u32> = Mutex::new(0);
|
||||
54
src/lib.rs
54
src/lib.rs
@@ -1,10 +1,6 @@
|
||||
use actix_web::{dev::Server, http, middleware, web, App, HttpResponse, HttpServer};
|
||||
use contextswitch_types::TaskDefinition;
|
||||
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
|
||||
use listenfd::ListenFd;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::env;
|
||||
use std::io::Error;
|
||||
use std::net::TcpListener;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
|
||||
@@ -13,42 +9,7 @@ extern crate lazy_static;
|
||||
|
||||
pub mod contextswitch;
|
||||
pub mod observability;
|
||||
pub mod taskwarrior;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TaskQuery {
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(filter = %task_query.filter.as_ref().unwrap_or(&"".to_string())))]
|
||||
async fn list_tasks(task_query: web::Query<TaskQuery>) -> Result<HttpResponse, Error> {
|
||||
let filter = task_query
|
||||
.filter
|
||||
.as_ref()
|
||||
.map_or(vec![], |filter| filter.split(' ').collect());
|
||||
let tasks = contextswitch::export(filter)?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&tasks)?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(definition = %task_definition.definition))]
|
||||
async fn add_task(task_definition: web::Json<TaskDefinition>) -> Result<HttpResponse, Error> {
|
||||
let task_id = contextswitch::add(task_definition.definition.split(' ').collect()).await?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(json!({ "id": task_id }).to_string()))
|
||||
}
|
||||
|
||||
async fn option_task() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
|
||||
async fn health_check() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
pub mod routes;
|
||||
|
||||
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
||||
let cs_front_base_url =
|
||||
@@ -66,10 +27,13 @@ pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
||||
))
|
||||
.add(("Access-Control-Allow-Headers", "content-type".as_bytes())),
|
||||
)
|
||||
.route("/ping", web::get().to(health_check))
|
||||
.route("/tasks", web::get().to(list_tasks))
|
||||
.route("/tasks", web::post().to(add_task))
|
||||
.route("/tasks", web::method(http::Method::OPTIONS).to(option_task))
|
||||
.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",
|
||||
web::method(http::Method::OPTIONS).to(routes::option_task),
|
||||
)
|
||||
})
|
||||
.keep_alive(60)
|
||||
.shutdown_timeout(60);
|
||||
|
||||
@@ -2,7 +2,7 @@ extern crate dotenv;
|
||||
extern crate listenfd;
|
||||
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::{run, taskwarrior};
|
||||
use contextswitch_api::{contextswitch::taskwarrior, run};
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use std::net::TcpListener;
|
||||
|
||||
5
src/routes/health_check.rs
Normal file
5
src/routes/health_check.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
use actix_web::HttpResponse;
|
||||
|
||||
pub async fn ping() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
5
src/routes/mod.rs
Normal file
5
src/routes/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
mod health_check;
|
||||
mod tasks;
|
||||
|
||||
pub use health_check::*;
|
||||
pub use tasks::*;
|
||||
38
src/routes/tasks.rs
Normal file
38
src/routes/tasks.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use crate::contextswitch;
|
||||
use actix_web::{web, HttpResponse};
|
||||
use contextswitch_types::TaskDefinition;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::io::Error;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TaskQuery {
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
#[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, Error> {
|
||||
let filter = task_query
|
||||
.filter
|
||||
.as_ref()
|
||||
.map_or(vec![], |filter| filter.split(' ').collect());
|
||||
let tasks = contextswitch::list_tasks(filter)?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&tasks)?))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(definition = %task_definition.definition))]
|
||||
pub async fn add_task(task_definition: web::Json<TaskDefinition>) -> Result<HttpResponse, Error> {
|
||||
let task_id = contextswitch::add_task(task_definition.definition.split(' ').collect()).await?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(json!({ "id": task_id }).to_string()))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn option_task() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
pub mod test_helper;
|
||||
|
||||
use contextswitch_api::taskwarrior;
|
||||
use contextswitch_api::contextswitch::taskwarrior;
|
||||
use contextswitch_types::Task;
|
||||
use contextswitch_types::TaskDefinition;
|
||||
use rstest::*;
|
||||
@@ -9,11 +9,11 @@ use test_helper::app_address;
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn list_tasks(app_address: &str) {
|
||||
let task_id = taskwarrior::add(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"])
|
||||
let task_id =
|
||||
taskwarrior::add_task(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
println!("LIST TASKS ID: {}", task_id);
|
||||
let tasks: Vec<Task> = reqwest::Client::new()
|
||||
.get(&format!("{}/tasks?filter={}", &app_address, task_id))
|
||||
.send()
|
||||
@@ -43,10 +43,8 @@ async fn add_task(app_address: &str) {
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
println!("ADD RESPONSE: {:?}", response);
|
||||
let new_task_id = response["id"].as_u64().unwrap();
|
||||
let tasks = taskwarrior::export(vec![&new_task_id.to_string()]).unwrap();
|
||||
println!("TASKS={:?}", tasks);
|
||||
let tasks = taskwarrior::list_tasks(vec![&new_task_id.to_string()]).unwrap();
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].id, new_task_id);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use contextswitch_api::contextswitch::taskwarrior;
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::taskwarrior;
|
||||
use mktemp::Temp;
|
||||
use rstest::*;
|
||||
use std::fs;
|
||||
|
||||
Reference in New Issue
Block a user