Refactor modules

This commit is contained in:
2022-01-17 19:54:49 +01:00
parent 267cdb89c6
commit c52b573d15
11 changed files with 126 additions and 108 deletions

View File

@@ -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
View 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
View File

@@ -0,0 +1,4 @@
mod api;
pub mod taskwarrior;
pub use api::*;

View File

@@ -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);

View File

@@ -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);

View File

@@ -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;

View File

@@ -0,0 +1,5 @@
use actix_web::HttpResponse;
pub async fn ping() -> HttpResponse {
HttpResponse::Ok().finish()
}

5
src/routes/mod.rs Normal file
View File

@@ -0,0 +1,5 @@
mod health_check;
mod tasks;
pub use health_check::*;
pub use tasks::*;

38
src/routes/tasks.rs Normal file
View 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()
}