Compare commits

..

1 Commits

Author SHA1 Message Date
46b29c28e4 Add new task endpoint 2022-01-13 21:49:15 +01:00
17 changed files with 299 additions and 536 deletions

View File

@@ -38,7 +38,7 @@ jobs:
- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --tests -- -D warnings
args: -- -D warnings
- name: Run cargo-tarpaulin
uses: ./.github/actions/cargo-tarpaulin-action/

72
Cargo.lock generated
View File

@@ -216,12 +216,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "anyhow"
version = "1.0.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"
[[package]]
name = "autocfg"
version = "1.0.1"
@@ -331,7 +325,6 @@ version = "0.1.0"
dependencies = [
"actix-http",
"actix-web",
"anyhow",
"chrono",
"configparser",
"contextswitch-types",
@@ -339,16 +332,14 @@ dependencies = [
"lazy_static",
"listenfd",
"mktemp",
"once_cell",
"regex",
"reqwest",
"rstest",
"serde",
"serde_json",
"thiserror",
"tokio",
"tracing",
"tracing-actix-web",
"tracing-bunyan-formatter",
"tracing-log",
"tracing-subscriber",
"uuid",
@@ -357,6 +348,7 @@ dependencies = [
[[package]]
name = "contextswitch-types"
version = "0.1.0"
source = "git+https://github.com/dax/contextswitch-types.git#79b61a96b5ba708769715d603bb1cbe3c14a0045"
dependencies = [
"chrono",
"serde",
@@ -570,16 +562,6 @@ dependencies = [
"version_check",
]
[[package]]
name = "gethostname"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4addc164932852d066774c405dbbdb7914742d2b39e39e1a7ca949c856d054d1"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "getrandom"
version = "0.2.3"
@@ -1221,19 +1203,6 @@ dependencies = [
"winreg",
]
[[package]]
name = "rstest"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d912f35156a3f99a66ee3e11ac2e0b3f34ac85a07e05263d05a7e2c8810d616f"
dependencies = [
"cfg-if",
"proc-macro2",
"quote",
"rustc_version",
"syn",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
@@ -1413,26 +1382,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "thiserror"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "thread_local"
version = "1.1.3"
@@ -1581,23 +1530,6 @@ dependencies = [
"syn",
]
[[package]]
name = "tracing-bunyan-formatter"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd99ff040622c69c0fc4bd3ea5fe16630ce46400a79bd41339391b2d416ea24c"
dependencies = [
"gethostname",
"log",
"serde",
"serde_json",
"time 0.3.5",
"tracing",
"tracing-core",
"tracing-log",
"tracing-subscriber",
]
[[package]]
name = "tracing-core"
version = "0.1.21"

View File

@@ -12,8 +12,7 @@ path = "src/main.rs"
name = "contextswitch-api"
[dependencies]
#contextswitch-types = { git = "https://github.com/dax/contextswitch-types.git" }
contextswitch-types = { path = "../types" }
contextswitch-types = { git = "https://github.com/dax/contextswitch-types.git" }
actix-web = "=4.0.0-beta.19"
actix-http = "=3.0.0-beta.18"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
@@ -31,13 +30,7 @@ tracing-log = "0.1.0"
tracing-actix-web = "=0.5.0-beta.9"
regex = "1.5.0"
lazy_static = "1.4.0"
tracing-bunyan-formatter = "0.3.2"
thiserror = "1.0.30"
anyhow = "1.0.53"
[dev-dependencies]
once_cell = "1.0"
reqwest = { version = "0.11.0", features = ["json"] }
rstest = "0.12.0"
[profile.dev.package.backtrace]
opt-level = 3

49
src/contextswitch.rs Normal file
View File

@@ -0,0 +1,49 @@
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 fn add(add_args: Vec<&str>) -> Result<u64, Error> {
taskwarrior::add(add_args)
}

View File

@@ -1,52 +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 metadata: {metadata}")]
InvalidMetadataError {
#[source]
source: serde_json::Error,
metadata: String,
},
#[error(transparent)]
UnexpectedError(#[from] anyhow::Error),
}
#[tracing::instrument(level = "debug")]
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<Task>, ContextswitchError> {
let tasks: Result<Vec<Task>, ContextswitchError> = taskwarrior::list_tasks(filters)
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?
.iter()
.map(Task::try_from)
.collect();
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()))?;
(&taskwarrior_task).try_into()
}

View File

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

View File

@@ -1,270 +0,0 @@
use crate::contextswitch::ContextswitchError;
use anyhow::{anyhow, Context};
use chrono::{DateTime, Utc};
use configparser::ini::Ini;
use contextswitch_types::{ContextSwitchMetadata, 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;
use uuid::Uuid;
#[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)
}
}
#[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<Uuid>,
#[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 TryFrom<&TaskwarriorTask> for Task {
type Error = ContextswitchError;
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>, ContextswitchError> {
if cs_string.is_empty() || cs_string == "{}" {
Ok(None)
} else {
Some(serde_json::from_str(&cs_string))
.transpose()
.map_err(|e| ContextswitchError::InvalidMetadataError {
source: e,
metadata: cs_string.to_string(),
})
}
},
)?;
Ok(Task {
id: (&task.uuid).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,
project: task.project.clone(),
priority: task.priority,
recur: task.recur,
tags: task.tags.clone(),
contextswitch: cs_metadata,
})
}
}
#[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),
}
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("Context Switch metadata"),
);
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(task_data_location: Option<&str>) -> String {
if let Ok(taskrc_location) = env::var("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
)
});
debug!(
"Extracted data location `{}` from existing taskrc `{}`",
data_location, taskrc_location
);
data_location
} else {
let data_location = task_data_location
.map(|s| s.to_string())
.unwrap_or_else(|| {
env::var("TASK_DATA_LOCATION")
.expect("Expecting TASKRC or TASK_DATA_LOCATION environment variable value")
});
let taskrc_location = write_default_config(&data_location);
env::set_var("TASKRC", &taskrc_location);
debug!("Default taskrc written in `{}`", &taskrc_location);
data_location
}
}
#[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: 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 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();
static ref LOCK: Mutex<u32> = Mutex::new(0);
}
let _lock = LOCK.lock().await;
let mut args = vec!["add"];
args.extend(add_args);
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
))
})
}

View File

@@ -1,6 +1,9 @@
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
use actix_web::{dev::Server, middleware, web, App, HttpResponse, HttpServer};
use listenfd::ListenFd;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::env;
use std::io::Error;
use std::net::TcpListener;
use tracing_actix_web::TracingLogger;
@@ -9,7 +12,43 @@ extern crate lazy_static;
pub mod contextswitch;
pub mod observability;
pub mod routes;
pub mod taskwarrior;
#[derive(Deserialize)]
struct TaskQuery {
filter: Option<String>,
}
#[derive(Deserialize, Serialize)]
pub struct TaskDefinition {
pub definition: 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())?;
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(json!({ "id": task_id }).to_string()))
}
async fn health_check() -> HttpResponse {
HttpResponse::Ok().finish()
}
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let cs_front_base_url =
@@ -20,20 +59,11 @@ pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
.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",
web::method(http::Method::OPTIONS).to(routes::option_task),
.add(("Access-Control-Allow-Origin", cs_front_base_url.as_bytes())),
)
.route("/ping", web::get().to(health_check))
.route("/tasks", web::get().to(list_tasks))
.route("/tasks", web::post().to(add_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::{contextswitch::taskwarrior, run};
use contextswitch_api::{run, taskwarrior};
use dotenv::dotenv;
use std::env;
use std::net::TcpListener;

View File

@@ -1,19 +1,33 @@
use tracing::Level;
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};
use tracing_subscriber::{filter, fmt, fmt::format, layer::SubscriberExt, EnvFilter, Layer};
pub fn get_subscriber(env_filter_str: String) -> impl Subscriber + Send + Sync {
let formatting_layer = BunyanFormattingLayer::new("contextswitch-api".into(), TestWriter::new);
let fmt_layer = fmt::layer()
.event_format(format::Format::default().json())
.fmt_fields(format::JsonFields::new())
.flatten_event(true)
.with_test_writer();
let access_log_layer = fmt::layer()
.event_format(format::Format::default().json())
.fmt_fields(format::JsonFields::new())
.flatten_event(true)
.with_test_writer()
.with_span_events(format::FmtSpan::CLOSE)
.with_span_list(false)
.with_filter(
filter::Targets::new().with_target("tracing_actix_web::root_span_builder", Level::INFO),
);
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter_str));
tracing_subscriber::registry()
.with(fmt_layer)
.with(access_log_layer)
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}
pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {

View File

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

View File

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

View File

@@ -1,54 +0,0 @@
use crate::contextswitch;
use actix_web::{http::StatusCode, web, HttpResponse, ResponseError};
use anyhow::Context;
use contextswitch_types::{NewTask, Task};
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::InvalidMetadataError { .. } => {
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 = %task.definition))]
pub async fn add_task(
task: web::Json<NewTask>,
) -> Result<HttpResponse, contextswitch::ContextswitchError> {
let task: Task = contextswitch::add_task(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")]
pub fn option_task() -> HttpResponse {
HttpResponse::Ok().finish()
}

139
src/taskwarrior.rs Normal file
View File

@@ -0,0 +1,139 @@
use chrono::{DateTime, Utc};
use configparser::ini::Ini;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json;
use std::env;
use std::io::{Error, ErrorKind};
use std::path::Path;
use std::process::Command;
use std::str;
use tracing::debug;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Task {
pub uuid: Uuid,
pub id: u64,
#[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 end: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<Uuid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<String>,
#[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>,
}
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("Context Switch metadata"),
);
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(task_data_location: Option<&str>) -> String {
if let Ok(taskrc_location) = env::var("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
)
});
debug!(
"Extracted data location `{}` from existing taskrc `{}`",
data_location, taskrc_location
);
data_location
} else {
let data_location = task_data_location
.map(|s| s.to_string())
.unwrap_or_else(|| {
env::var("TASK_DATA_LOCATION")
.expect("Expecting TASKRC or TASK_DATA_LOCATION environment variable value")
});
let taskrc_location = write_default_config(&data_location);
env::set_var("TASKRC", &taskrc_location);
debug!("Default taskrc written in `{}`", &taskrc_location);
data_location
}
}
#[tracing::instrument(level = "debug")]
pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, 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)?;
Ok(tasks)
}
#[tracing::instrument(level = "debug")]
pub fn add(add_args: Vec<&str>) -> Result<u64, Error> {
let mut args = vec!["add"];
args.extend(add_args);
let add_output = Command::new("task").args(args).output()?;
let output = String::from_utf8(add_output.stdout).unwrap();
lazy_static! {
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
}
let task_id_capture = RE.captures(&output).ok_or_else(|| {
Error::new(
ErrorKind::Other,
format!("Cannot extract task ID from: {}", &output),
)
})?;
let task_id_str = task_id_capture
.name("id")
.ok_or_else(|| {
Error::new(
ErrorKind::Other,
format!("Cannot extract task ID value from: {}", &output),
)
})?
.as_str();
task_id_str
.parse::<u64>()
.map_err(|_| Error::new(ErrorKind::Other, "Cannot parse task ID value"))
}

View File

@@ -1,12 +1,12 @@
pub mod test_helper;
use rstest::*;
use test_helper::app_address;
#[rstest]
#[tokio::test]
async fn health_check_works(app_address: &str) {
let response = reqwest::Client::new()
.get(&format!("{}/ping", &app_address))
async fn health_check_works() {
let address = test_helper::spawn_app();
let client = reqwest::Client::new();
let response = client
.get(&format!("{}/ping", &address))
.send()
.await
.expect("Failed to execute request.");

View File

@@ -1,20 +1,16 @@
pub mod test_helper;
use contextswitch_api::contextswitch;
use contextswitch_types::{ContextSwitchMetadata, NewTask, Task, TaskId};
use rstest::*;
use test_helper::app_address;
use uuid::Uuid;
use contextswitch_api::{taskwarrior, TaskDefinition};
use contextswitch_types::Task;
#[rstest]
#[tokio::test]
async fn list_tasks(app_address: &str) {
let task = contextswitch::add_task(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"])
.await
.unwrap();
async fn list_tasks() {
let address = test_helper::spawn_app();
let task_id =
taskwarrior::add(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"]).unwrap();
let tasks: Vec<Task> = reqwest::Client::new()
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
.get(&format!("{}/tasks?filter={}", &address, task_id))
.send()
.await
.expect("Failed to execute request")
@@ -28,12 +24,14 @@ async fn list_tasks(app_address: &str) {
assert_eq!(cs_metadata.test, 1);
}
#[rstest]
#[tokio::test]
async fn add_task(app_address: &str) {
async fn add_task() {
let address = test_helper::spawn_app();
println!("add_task address: {}", address);
let response: serde_json::Value = reqwest::Client::new()
.post(&format!("{}/tasks", &app_address))
.json(&NewTask {
.post(&format!("{}/tasks", &address))
.json(&TaskDefinition {
definition: "test add_task contextswitch:{\"test\":1}".to_string(),
})
.send()
@@ -42,14 +40,14 @@ async fn add_task(app_address: &str) {
.json()
.await
.expect("Cannot parse JSON result");
let new_task_id = TaskId(Uuid::parse_str(response["id"].as_str().unwrap()).unwrap());
let tasks = contextswitch::list_tasks(vec![&new_task_id.to_string()]).unwrap();
let new_task_id = response["id"].as_u64().unwrap();
let tasks = taskwarrior::export(vec![&new_task_id.to_string()]).unwrap();
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].id, new_task_id);
assert_eq!(tasks[0].description, "test add_task");
assert_eq!(
tasks[0].contextswitch.as_ref().unwrap(),
&ContextSwitchMetadata { test: 1 }
&"{\"test\":1}".to_string()
);
}

View File

@@ -1,44 +1,42 @@
use contextswitch_api::contextswitch::taskwarrior;
use contextswitch_api::observability::{get_subscriber, init_subscriber};
use contextswitch_api::taskwarrior;
use mktemp::Temp;
use rstest::*;
use once_cell::sync::Lazy;
use std::fs;
use std::net::TcpListener;
use tracing::info;
fn setup_tracing() {
info!("Setting up tracing");
let subscriber = get_subscriber("debug".to_string());
static TRACING: Lazy<()> = Lazy::new(|| {
let subscriber = get_subscriber("info".to_string());
init_subscriber(subscriber);
}
});
fn setup_server() -> String {
info!("Setting up server");
static SERVER_ADDRESS: Lazy<String> = Lazy::new(|| {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = contextswitch_api::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
});
fn setup_taskwarrior() -> String {
info!("Setting up TW");
static TASK_DATA_LOCATION: Lazy<String> = Lazy::new(|| {
let tmp_dir = Temp::new_dir().unwrap();
let task_data_location = taskwarrior::load_config(tmp_dir.to_str());
tmp_dir.release();
task_data_location
});
pub fn spawn_app() -> String {
Lazy::force(&TRACING);
setup_tasks();
Lazy::force(&SERVER_ADDRESS).to_string()
}
pub fn setup_tasks() -> String {
Lazy::force(&TASK_DATA_LOCATION).to_string()
}
pub fn clear_tasks(task_data_location: String) {
fs::remove_dir_all(task_data_location).unwrap();
}
#[fixture]
#[once]
pub fn app_address() -> String {
setup_tracing();
setup_taskwarrior();
setup_server()
}