Compare commits
12 Commits
7e69f872a7
...
67210377b7
| Author | SHA1 | Date | |
|---|---|---|---|
|
67210377b7
|
|||
|
ffdabe0b6c
|
|||
|
7a3b5aa6a3
|
|||
|
300e692fc7
|
|||
|
3a36e8e9e3
|
|||
|
81ef6f689b
|
|||
|
b359b5123e
|
|||
|
3f3f887cfe
|
|||
|
8207ab958d
|
|||
|
884d4bee1f
|
|||
|
747e962bc9
|
|||
|
a9942002b2
|
22
.github/actions/cargo-tarpaulin-action/action.yml
vendored
Normal file
22
.github/actions/cargo-tarpaulin-action/action.yml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: 'cargo tarpaulin'
|
||||
description: 'Gather Rust code coverage information with Tarpaulin'
|
||||
inputs:
|
||||
version:
|
||||
description: 'The version of cargo-tarpaulin to install'
|
||||
required: true
|
||||
default: '0.19.0'
|
||||
|
||||
args:
|
||||
required: false
|
||||
description: 'Extra command line arguments passed to cargo-tarpaulin'
|
||||
|
||||
out-type:
|
||||
description: 'Output format of coverage report [possible values: Json, Toml, Stdout, Xml, Html, Lcov]'
|
||||
required: false
|
||||
default: 'Xml'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- run: ${{ github.action_path }}/cargo-tarpaulin.sh ${{ inputs.out-type }} ${{ inputs.version }} ${{ inputs.args }}
|
||||
shell: bash
|
||||
15
.github/actions/cargo-tarpaulin-action/cargo-tarpaulin.sh
vendored
Executable file
15
.github/actions/cargo-tarpaulin-action/cargo-tarpaulin.sh
vendored
Executable file
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
|
||||
sudo apt-get update -y
|
||||
sudo apt-get install -y --no-install-recommends openssl taskwarrior
|
||||
|
||||
out_type="$1"
|
||||
version="$2"
|
||||
args="$3"
|
||||
tar_file="cargo-tarpaulin-${version}-travis.tar.gz"
|
||||
|
||||
wget "https://github.com/xd009642/tarpaulin/releases/download/${version}/${tar_file}"
|
||||
tar zxvf "$tar_file"
|
||||
chmod +x cargo-tarpaulin
|
||||
|
||||
exec env RUST_LOG=debug ./cargo-tarpaulin tarpaulin --ignore-tests -o "$out_type" $args
|
||||
16
.github/workflows/audit.yml
vendored
Normal file
16
.github/workflows/audit.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
name: Security audit
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- '**/Cargo.toml'
|
||||
- '**/Cargo.lock'
|
||||
|
||||
jobs:
|
||||
security_audit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/audit-check@v1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
57
.github/workflows/ci.yml
vendored
Normal file
57
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
on: [push]
|
||||
|
||||
name: CI
|
||||
|
||||
jobs:
|
||||
format:
|
||||
name: rustfmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
components: rustfmt
|
||||
override: true
|
||||
- uses: LoliGothick/rustfmt-check@v0.2
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
flags: --all
|
||||
options: --manifest-path=Cargo.toml
|
||||
|
||||
build_and_test:
|
||||
name: Build & test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
args: --release --all-features
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --tests -- -D warnings
|
||||
|
||||
- name: Run cargo-tarpaulin
|
||||
uses: ./.github/actions/cargo-tarpaulin-action/
|
||||
with:
|
||||
args: '-- --test-threads 1'
|
||||
|
||||
- name: Upload to codecov.io
|
||||
uses: codecov/codecov-action@v1.0.2
|
||||
with:
|
||||
token: ${{secrets.CODECOV_TOKEN}}
|
||||
|
||||
- name: Archive code coverage results
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: code-coverage-report
|
||||
path: cobertura.xml
|
||||
7
.pre-commit-config.yaml
Normal file
7
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
repos:
|
||||
- repo: https://github.com/doublify/pre-commit-rust
|
||||
rev: v1.0
|
||||
hooks:
|
||||
- id: fmt
|
||||
- id: cargo-check
|
||||
- id: clippy
|
||||
808
Cargo.lock
generated
808
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
37
Cargo.toml
37
Cargo.toml
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "contextswitch"
|
||||
name = "contextswitch-api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["David Rousselie <david@rousselie.name>"]
|
||||
@@ -9,22 +9,31 @@ path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "contextswitch"
|
||||
name = "contextswitch-api"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "=4.0.0-beta.10"
|
||||
actix-http = "=3.0.0-beta.11"
|
||||
serde = "1.0.130"
|
||||
serde_json = "1.0.71"
|
||||
uuid = { version = "0.8.2", features = ["serde"] }
|
||||
chrono = { version = "0.4.19", features = ["serde"] }
|
||||
mktemp = "0.4.1"
|
||||
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"] }
|
||||
serde = { version = "1.0.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
uuid = { version = "0.8.0", features = ["serde"] }
|
||||
chrono = { version = "0.4.0", features = ["serde"] }
|
||||
mktemp = "0.4.0"
|
||||
configparser = "3.0.0"
|
||||
env_logger = "0.9.0"
|
||||
dotenv = "0.15.0"
|
||||
listenfd = "0.3.5"
|
||||
listenfd = "0.3.0"
|
||||
tracing = { version = "0.1.0", features = ["log"] }
|
||||
tracing-subscriber = { version = "0.3.0", features = ["std", "env-filter", "fmt", "json"] }
|
||||
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]
|
||||
actix-rt = "2"
|
||||
reqwest = "0.11.6"
|
||||
tokio = "1"
|
||||
reqwest = { version = "0.11.0", features = ["json"] }
|
||||
rstest = "0.12.0"
|
||||
|
||||
52
src/contextswitch/api.rs
Normal file
52
src/contextswitch/api.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
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()
|
||||
}
|
||||
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::*;
|
||||
267
src/contextswitch/taskwarrior.rs
Normal file
267
src/contextswitch/taskwarrior.rs
Normal file
@@ -0,0 +1,267 @@
|
||||
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 })?;
|
||||
|
||||
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
|
||||
))
|
||||
})
|
||||
}
|
||||
90
src/lib.rs
90
src/lib.rs
@@ -1,71 +1,39 @@
|
||||
use actix_web::{dev::Server, middleware::Logger, web, App, HttpResponse, HttpServer};
|
||||
use chrono::{DateTime, Utc};
|
||||
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
|
||||
use listenfd::ListenFd;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::Error;
|
||||
use std::env;
|
||||
use std::net::TcpListener;
|
||||
use uuid::Uuid;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
|
||||
pub mod taskwarrior;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TaskQuery {
|
||||
filter: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Task {
|
||||
pub uuid: Uuid,
|
||||
pub id: u32,
|
||||
#[serde(with = "taskwarrior::tw_date_format")]
|
||||
pub entry: DateTime<Utc>,
|
||||
#[serde(with = "taskwarrior::tw_date_format")]
|
||||
pub modified: DateTime<Utc>,
|
||||
pub status: taskwarrior::Status,
|
||||
pub description: String,
|
||||
pub urgency: f64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "taskwarrior::opt_tw_date_format"
|
||||
)]
|
||||
pub due: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "taskwarrior::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<taskwarrior::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<taskwarrior::ContextSwitchMetadata>,
|
||||
}
|
||||
|
||||
async fn list_tasks(task_query: web::Query<TaskQuery>) -> Result<HttpResponse, Error> {
|
||||
let tasks = taskwarrior::export(task_query.filter.split(' ').collect())?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&tasks)?))
|
||||
}
|
||||
|
||||
async fn health_check() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
pub mod contextswitch;
|
||||
pub mod observability;
|
||||
pub mod routes;
|
||||
|
||||
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
||||
let mut server = HttpServer::new(|| {
|
||||
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(Logger::default())
|
||||
.route("/ping", web::get().to(health_check))
|
||||
.route("/tasks", web::get().to(list_tasks))
|
||||
.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",
|
||||
web::method(http::Method::OPTIONS).to(routes::option_task),
|
||||
)
|
||||
})
|
||||
.keep_alive(60)
|
||||
.shutdown_timeout(60);
|
||||
|
||||
15
src/main.rs
15
src/main.rs
@@ -1,21 +1,20 @@
|
||||
extern crate dotenv;
|
||||
extern crate env_logger;
|
||||
extern crate listenfd;
|
||||
|
||||
use contextswitch::run;
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::{contextswitch::taskwarrior, run};
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use std::net::TcpListener;
|
||||
|
||||
pub mod taskwarrior;
|
||||
|
||||
#[actix_web::main]
|
||||
#[tokio::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
let subscriber = get_subscriber("info".into());
|
||||
init_subscriber(subscriber);
|
||||
|
||||
dotenv().ok();
|
||||
|
||||
let port = env::var("PORT").unwrap_or("8000".to_string());
|
||||
let port = env::var("PORT").unwrap_or_else(|_| "8000".to_string());
|
||||
taskwarrior::load_config(None);
|
||||
|
||||
let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).expect("Failed to bind port");
|
||||
|
||||
22
src/observability.rs
Normal file
22
src/observability.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
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: String) -> 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");
|
||||
}
|
||||
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::*;
|
||||
54
src/routes/tasks.rs
Normal file
54
src/routes/tasks.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use configparser::ini::Ini;
|
||||
use serde::{de, Deserialize, Deserializer, Serialize};
|
||||
use serde_json;
|
||||
use std::env;
|
||||
use std::io::Error;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::str;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Recurrence {
|
||||
Daily,
|
||||
Weekly,
|
||||
Monthly,
|
||||
Yearly,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Pending,
|
||||
Completed,
|
||||
Recurring,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ContextSwitchMetadata {
|
||||
pub test: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Task {
|
||||
pub uuid: Uuid,
|
||||
pub id: u32,
|
||||
#[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 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<Recurrence>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tags: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "deserialize_from_json"
|
||||
)]
|
||||
pub contextswitch: Option<ContextSwitchMetadata>,
|
||||
}
|
||||
|
||||
fn deserialize_from_json<'de, D>(deserializer: D) -> Result<Option<ContextSwitchMetadata>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s: String = Deserialize::deserialize(deserializer)?;
|
||||
serde_json::from_str(&s).map_err(de::Error::custom)
|
||||
}
|
||||
|
||||
pub mod tw_date_format {
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
|
||||
const FORMAT: &'static 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: &'static 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)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
.expect(&format!("Cannot load taskrc file {}", taskrc_location));
|
||||
return taskrc.get("default", "data.location").expect(&format!(
|
||||
"'data.location' must be set in taskrc file {}",
|
||||
taskrc_location
|
||||
));
|
||||
}
|
||||
|
||||
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 mut taskrc = Ini::new();
|
||||
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("{}"));
|
||||
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();
|
||||
|
||||
env::set_var("TASKRC", taskrc_location);
|
||||
|
||||
return data_location;
|
||||
}
|
||||
|
||||
pub fn export(filters: Vec<&str>) -> Result<Vec<Task>, Error> {
|
||||
let mut args = vec!["export"];
|
||||
args.extend(filters);
|
||||
let export_output = Command::new("task").args(args).output()?;
|
||||
|
||||
let tasks: Vec<Task> = serde_json::from_slice(&export_output.stdout)?;
|
||||
|
||||
return Ok(tasks);
|
||||
}
|
||||
|
||||
pub fn add(add_args: Vec<&str>) -> Result<(), Error> {
|
||||
let mut args = vec!["add"];
|
||||
args.extend(add_args);
|
||||
Command::new("task").args(args).output()?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
pub mod test_helper;
|
||||
use rstest::*;
|
||||
use test_helper::app_address;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn health_check_works() {
|
||||
let address = test_helper::spawn_app();
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let response = client
|
||||
.get(&format!("{}/ping", &address))
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn health_check_works(app_address: &str) {
|
||||
let response = reqwest::Client::new()
|
||||
.get(&format!("{}/ping", &app_address))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request.");
|
||||
|
||||
@@ -1,27 +1,55 @@
|
||||
pub mod test_helper;
|
||||
|
||||
use contextswitch::taskwarrior;
|
||||
use contextswitch::Task;
|
||||
use contextswitch_api::contextswitch;
|
||||
use contextswitch_types::{ContextSwitchMetadata, NewTask, Task, TaskId};
|
||||
use rstest::*;
|
||||
use test_helper::app_address;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn list_tasks() {
|
||||
let task_data_path = test_helper::setup_tasks();
|
||||
let address = test_helper::spawn_app();
|
||||
let client = reqwest::Client::new();
|
||||
taskwarrior::add(vec!["test1", "contextswitch:'{\"test\": 1}'"]).unwrap();
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn list_tasks(app_address: &str) {
|
||||
let task = contextswitch::add_task(vec!["test", "list_tasks", "contextswitch:'{\"test\": 1}'"])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = client
|
||||
.get(&format!("{}/tasks?filter=ls", &address))
|
||||
let tasks: Vec<Task> = reqwest::Client::new()
|
||||
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request.");
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
test_helper::clear_tasks(task_data_path);
|
||||
let text_body = response.text_with_charset("utf-8").await.unwrap();
|
||||
let tasks: Vec<Task> = serde_json::from_str(&text_body).unwrap();
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].description, "test1");
|
||||
|
||||
assert_eq!(tasks[0].description, "test list_tasks");
|
||||
let cs_metadata = tasks[0].contextswitch.as_ref().unwrap();
|
||||
assert_eq!(cs_metadata.test, 1);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn add_task(app_address: &str) {
|
||||
let response: serde_json::Value = reqwest::Client::new()
|
||||
.post(&format!("{}/tasks", &app_address))
|
||||
.json(&NewTask {
|
||||
definition: "test add_task contextswitch:{\"test\":1}".to_string(),
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.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();
|
||||
|
||||
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 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
use contextswitch_api::taskwarrior;
|
||||
use contextswitch_api::contextswitch::taskwarrior;
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use mktemp::Temp;
|
||||
use rstest::*;
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use tracing::info;
|
||||
|
||||
pub fn spawn_app() -> String {
|
||||
fn setup_tracing() {
|
||||
info!("Setting up tracing");
|
||||
let subscriber = get_subscriber("debug".to_string());
|
||||
init_subscriber(subscriber);
|
||||
}
|
||||
|
||||
fn setup_server() -> String {
|
||||
info!("Setting up server");
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
|
||||
@@ -12,14 +22,23 @@ pub fn spawn_app() -> String {
|
||||
format!("http://127.0.0.1:{}", port)
|
||||
}
|
||||
|
||||
pub fn setup_tasks() -> String {
|
||||
fn setup_taskwarrior() -> String {
|
||||
info!("Setting up TW");
|
||||
let tmp_dir = Temp::new_dir().unwrap();
|
||||
let task_data_location = taskwarrior::load_config(tmp_dir.to_str());
|
||||
tmp_dir.release();
|
||||
|
||||
return task_data_location;
|
||||
task_data_location
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user