Compare commits
7 Commits
main
..
be0fcb9a61
| Author | SHA1 | Date | |
|---|---|---|---|
|
be0fcb9a61
|
|||
|
c8baffb3dc
|
|||
|
77f66ed5d1
|
|||
|
747e962bc9
|
|||
|
a9942002b2
|
|||
|
4c94597e8b
|
|||
|
021d067d86
|
@@ -1,8 +0,0 @@
|
||||
.git
|
||||
.github
|
||||
.env
|
||||
target/
|
||||
tests/
|
||||
Dockerfile
|
||||
web/dist
|
||||
api/config/local.*
|
||||
@@ -10,15 +10,7 @@ jobs:
|
||||
security_audit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
override: true
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/audit-check@v1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+35
-103
@@ -1,126 +1,58 @@
|
||||
on: [push]
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
rustfmt:
|
||||
name: Rustfmt
|
||||
format:
|
||||
name: rustfmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
toolchain: nightly
|
||||
components: rustfmt
|
||||
- name: Check formatting
|
||||
uses: actions-rs/cargo@v1
|
||||
override: true
|
||||
- uses: LoliGothick/rustfmt-check@v0.2
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
flags: --all
|
||||
options: --manifest-path=Cargo.toml
|
||||
|
||||
build:
|
||||
name: Build
|
||||
build_and_test:
|
||||
name: contextswitch-api
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
- name: Install Wasm Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
target: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
with:
|
||||
sharedKey: ci
|
||||
components: clippy
|
||||
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
args: --all-features --workspace
|
||||
args: --release --all-features
|
||||
|
||||
test:
|
||||
needs: build
|
||||
name: Test Suite
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
- uses: awalsh128/cache-apt-pkgs-action@v1
|
||||
with:
|
||||
packages: taskwarrior
|
||||
version: 1.0
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
with:
|
||||
sharedKey: ci
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all-features --workspace
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: -- -D warnings
|
||||
|
||||
clippy:
|
||||
needs: build
|
||||
name: Clippy
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
with:
|
||||
sharedKey: ci
|
||||
- name: Clippy check
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: --all-targets --all-features --workspace -- -D warnings
|
||||
|
||||
coverage:
|
||||
name: Code coverage
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
- uses: awalsh128/cache-apt-pkgs-action@v1
|
||||
with:
|
||||
packages: taskwarrior
|
||||
version: 1.0
|
||||
- uses: Swatinem/rust-cache@v1
|
||||
- name: Run cargo-tarpaulin
|
||||
uses: actions-rs/tarpaulin@v0.1
|
||||
with:
|
||||
args: '--all-features --workspace --ignore-tests --out Lcov'
|
||||
- name: Upload to Coveralls
|
||||
# upload only if push
|
||||
if: ${{ github.event_name == 'push' }}
|
||||
uses: coverallsapp/github-action@master
|
||||
version: '0.15.0'
|
||||
args: '-- --test-threads 1'
|
||||
|
||||
- name: Upload to codecov.io
|
||||
uses: codecov/codecov-action@v1.0.2
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
path-to-lcov: './lcov.info'
|
||||
token: ${{secrets.CODECOV_TOKEN}}
|
||||
|
||||
- name: Archive code coverage results
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: code-coverage-report
|
||||
path: cobertura.xml
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
/target
|
||||
api/config/local.*
|
||||
web/dist
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: format
|
||||
name: format
|
||||
language: system
|
||||
pass_filenames: false
|
||||
entry: cargo make format-flow
|
||||
- id: format-toml
|
||||
name: format-toml
|
||||
language: system
|
||||
pass_filenames: false
|
||||
entry: cargo make format-toml-flow
|
||||
- id: check
|
||||
name: check
|
||||
language: system
|
||||
pass_filenames: false
|
||||
entry: cargo make check-tests
|
||||
- id: clippy
|
||||
name: clippy
|
||||
language: system
|
||||
pass_filenames: false
|
||||
entry: cargo make clippy-flow
|
||||
Generated
+222
-987
File diff suppressed because it is too large
Load Diff
+22
-6
@@ -1,18 +1,34 @@
|
||||
[package]
|
||||
name = "contextswitch"
|
||||
name = "contextswitch-api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["David Rousselie <david@rousselie.name>"]
|
||||
|
||||
[workspace]
|
||||
members = ["api", "web"]
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "contextswitch-api"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
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"] }
|
||||
http = "0.2.0"
|
||||
mktemp = "0.4.0"
|
||||
configparser = "3.0.0"
|
||||
dotenv = "0.15.0"
|
||||
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"
|
||||
|
||||
[dev-dependencies]
|
||||
once_cell = "1.0"
|
||||
reqwest = "0.11.0"
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
FROM lukemathwalker/cargo-chef:latest-rust-1.57.0 as chef
|
||||
WORKDIR /app
|
||||
|
||||
FROM chef as planner
|
||||
COPY . .
|
||||
RUN cargo chef prepare --recipe-path recipe.json
|
||||
|
||||
FROM chef as builder
|
||||
RUN cargo install cargo-make
|
||||
RUN cargo install trunk
|
||||
RUN rustup target add wasm32-unknown-unknown
|
||||
COPY --from=planner /app/recipe.json recipe.json
|
||||
RUN cargo chef cook -p contextswitch --release --recipe-path recipe.json
|
||||
RUN cargo chef cook -p contextswitch-api --release --recipe-path recipe.json
|
||||
RUN cargo chef cook -p contextswitch-web --release --recipe-path recipe.json --target wasm32-unknown-unknown
|
||||
COPY . .
|
||||
RUN cargo make build-release
|
||||
RUN sed -i 's#http://localhost:8000/api#/api#' web/dist/snippets/contextswitch-web-*/js/api.js
|
||||
|
||||
FROM debian:bullseye-slim AS runtime
|
||||
WORKDIR /app
|
||||
RUN mkdir /data
|
||||
RUN apt-get update -y \
|
||||
&& apt-get install -y --no-install-recommends openssl taskwarrior \
|
||||
&& apt-get autoremove -y \
|
||||
&& apt-get clean -y \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=builder /app/target/release/contextswitch-api contextswitch
|
||||
COPY --from=builder /app/api/config/default.toml config/default.toml
|
||||
COPY --from=builder /app/web/dist/ .
|
||||
ENV CS_TASKWARRIOR.DATA_LOCATION /data
|
||||
ENV CS_APPLICATION.API_PATH /api
|
||||
ENV CS_APPLICATION.STATIC_PATH /
|
||||
CMD ["/app/contextswitch"]
|
||||
@@ -6,187 +6,59 @@
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright 2022 David Rousselie
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
[env]
|
||||
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
|
||||
CARGO_MAKE_COVERAGE_PROVIDER = "tarpaulin"
|
||||
CARGO_MAKE_CLIPPY_ARGS = "--tests -- -D warnings"
|
||||
|
||||
[tasks.default]
|
||||
clear = true
|
||||
alias = "watch"
|
||||
|
||||
[tasks.test]
|
||||
install_crate = "cargo-nextest"
|
||||
args = [
|
||||
"nextest",
|
||||
"run",
|
||||
"@@remove-empty(CARGO_MAKE_CARGO_VERBOSE_FLAGS)",
|
||||
"@@split(CARGO_MAKE_CARGO_BUILD_TEST_FLAGS, )",
|
||||
]
|
||||
|
||||
[tasks.audit]
|
||||
condition = {}
|
||||
workspace = false
|
||||
|
||||
[tasks.run-api]
|
||||
command = "bash"
|
||||
args = ["-c", "cd api; cargo make run"]
|
||||
workspace = false
|
||||
watch = { watch = ["./api/"], no_git_ignore = true }
|
||||
|
||||
[tasks.run-web]
|
||||
command = "bash"
|
||||
args = ["-c", "cd web; cargo make run"]
|
||||
workspace = false
|
||||
|
||||
[tasks.run]
|
||||
run_task = { name = ["run-api", "run-web"], parallel = true, fork = true }
|
||||
workspace = false
|
||||
|
||||
[tasks.watch-api]
|
||||
command = "bash"
|
||||
args = ["-c", "cd api; cargo make dev-test-flow"]
|
||||
workspace = false
|
||||
watch = { watch = ["./api/"], no_git_ignore = true }
|
||||
|
||||
[tasks.watch-web]
|
||||
command = "bash"
|
||||
args = ["-c", "cd web; cargo make dev-test-flow"]
|
||||
workspace = false
|
||||
watch = { watch = ["./web/"], no_git_ignore = true }
|
||||
|
||||
[tasks.watch-root]
|
||||
watch = { watch = ["./src/"], no_git_ignore = true }
|
||||
run_task = "dev-test-flow"
|
||||
workspace = false
|
||||
|
||||
[tasks.watch]
|
||||
run_task = { name = ["watch-api", "watch-web", "watch-root"], parallel = true, fork = true }
|
||||
workspace = false
|
||||
@@ -1,100 +1,2 @@
|
||||
# Contextswitch
|
||||
# contextswitch
|
||||
|
||||
[](https://www.apache.org/licenses/)
|
||||
[](https://coveralls.io/github/dax/contextswitch?branch=main)
|
||||
[](https://github.com/dax/contextswitch/actions)
|
||||
|
||||
Contextswitch is a todo list application linking bookmarks to a task.
|
||||
Integrations with third parties applications add context to a task:
|
||||
- a link to a note taking application to add notes to a task
|
||||
- a link to a Slack thread
|
||||
- a link to a Github issue, pull request or discussion related to the task
|
||||
- ...
|
||||
|
||||
It is intended to be based on existing todo applications and augment them.
|
||||
|
||||
## Features
|
||||
|
||||
- [X] list tasks
|
||||
- [ ] add a task
|
||||
- [ ] add a bookmark to a task
|
||||
- [ ] augment a task with third party integration
|
||||
- [ ] update a task status (waiting, done, ...)
|
||||
- [ ] schedule a task
|
||||
- [ ] update a task status based on bookmarks notifications
|
||||
|
||||
### Integrations
|
||||
|
||||
Todo application backend:
|
||||
- [X] taskwarrior
|
||||
- [ ] todoist
|
||||
|
||||
Third parties integrations:
|
||||
- [ ] Github
|
||||
- [ ] Slack
|
||||
|
||||
Frontend integrations:
|
||||
- [X] Contextswitch
|
||||
- [ ] [Sidebery](https://github.com/mbnuqw/sidebery) Firefox add-ons
|
||||
|
||||
## Installation
|
||||
|
||||
### Using cargo (for development)
|
||||
|
||||
```bash
|
||||
cargo make run
|
||||
```
|
||||
|
||||
### Manual
|
||||
|
||||
1. Get the code
|
||||
|
||||
```bash
|
||||
git clone https://github.com/dax/contextswitch
|
||||
```
|
||||
|
||||
2. Build api and web release assets
|
||||
|
||||
```bash
|
||||
cargo make build-release
|
||||
```
|
||||
|
||||
It will produce a `target/release/contextswitch-api` backend binary and frontend assets in the `web/dist` directory.
|
||||
|
||||
3. Deploy assets
|
||||
|
||||
```bash
|
||||
mkdir -p $DEPLOY_DIR/config
|
||||
cp -a target/release/contextswitch-api $DEPLOY_DIR
|
||||
cp -a web/dist/* $DEPLOY_DIR
|
||||
cp -a api/config/{default.toml, prod.toml} $DEPLOY_DIR/config
|
||||
```
|
||||
|
||||
4. Run server
|
||||
|
||||
```bash
|
||||
cd $DEPLOY_DIR
|
||||
env CONFIG_FILE=$DEPLOY_DIR/config/prod.toml ./contextswitch-api
|
||||
```
|
||||
|
||||
### Using Docker
|
||||
|
||||
#### Build Docker image
|
||||
|
||||
```bash
|
||||
docker build -t contextswitch .
|
||||
```
|
||||
|
||||
#### Run Contextswitch using Docker
|
||||
|
||||
```bash
|
||||
docker run --rm -ti -p 8000:8000 contextswitch
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Access Contextswitch using [http://localhost:8000](http://localhost:8000)
|
||||
|
||||
## License
|
||||
|
||||
[AGPL](LICENSE)
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
[package]
|
||||
name = "contextswitch-api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["David Rousselie <david@rousselie.name>"]
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "contextswitch-api"
|
||||
|
||||
[dependencies]
|
||||
contextswitch = { path = ".." }
|
||||
actix-web = "4.0.0"
|
||||
actix-http = "3.0.0"
|
||||
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"
|
||||
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"
|
||||
regex = "1.5.0"
|
||||
lazy_static = "1.4.0"
|
||||
tracing-bunyan-formatter = "0.3.0"
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
http = "0.2.0"
|
||||
config = "0.12.0"
|
||||
actix-files = "0.6.0"
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = "1.0.0"
|
||||
reqwest = { version = "0.11.0", features = ["json"] }
|
||||
rstest = "0.12.0"
|
||||
@@ -1,8 +0,0 @@
|
||||
extend = "../Makefile.toml"
|
||||
|
||||
[tasks.run]
|
||||
clear = true
|
||||
install_crate = { crate_name = "bunyan", binary = "bunyan" }
|
||||
env = { "TASKRC" = "$PWD/taskrc" }
|
||||
command = "bash"
|
||||
args = ["-c", "cargo run | bunyan"]
|
||||
@@ -1,9 +0,0 @@
|
||||
[application]
|
||||
port = 8000
|
||||
# See https://docs.rs/tracing-subscriber/latest/tracing_subscriber/struct.EnvFilter.html
|
||||
log_directive = "info"
|
||||
api_path = ""
|
||||
front_base_url = "http://localhost:8080"
|
||||
|
||||
[taskwarrior]
|
||||
data_location = "/tmp"
|
||||
@@ -1,5 +0,0 @@
|
||||
[application]
|
||||
log_directive = "debug"
|
||||
static_dir = "../web/dist"
|
||||
api_path = "/api"
|
||||
static_path = ""
|
||||
@@ -1,4 +0,0 @@
|
||||
[application]
|
||||
static_dir = "."
|
||||
api_path = "/api"
|
||||
static_path = ""
|
||||
@@ -1,2 +0,0 @@
|
||||
[application]
|
||||
log_directive = "debug"
|
||||
@@ -1,55 +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,
|
||||
pub front_base_url: String,
|
||||
pub api_path: String,
|
||||
pub static_path: Option<String>,
|
||||
pub static_dir: Option<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_path = env::var("CONFIG_PATH").unwrap_or_else(|_| "config".into());
|
||||
let config_file = file.unwrap_or_else(|| {
|
||||
env::var("CONFIG_FILE").unwrap_or_else(|_| format!("{}/dev", &config_path))
|
||||
});
|
||||
|
||||
let default_config_file = format!("{}/default", config_path);
|
||||
let local_config_file = format!("{}/local", config_path);
|
||||
println!(
|
||||
"Trying to load {:?} config files",
|
||||
vec![&default_config_file, &local_config_file, &config_file]
|
||||
);
|
||||
|
||||
let config = Config::builder()
|
||||
.add_source(File::with_name(&default_config_file))
|
||||
.add_source(File::with_name(&local_config_file).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::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::{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::tw_date_format")]
|
||||
pub entry: DateTime<Utc>,
|
||||
#[serde(with = "contextswitch::tw_date_format")]
|
||||
pub modified: DateTime<Utc>,
|
||||
pub status: contextswitch::Status,
|
||||
pub description: String,
|
||||
pub urgency: f64,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch::opt_tw_date_format"
|
||||
)]
|
||||
pub due: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch::opt_tw_date_format"
|
||||
)]
|
||||
pub start: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch::opt_tw_date_format"
|
||||
)]
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "contextswitch::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::Priority>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recur: Option<contextswitch::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::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::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::Priority::H),
|
||||
recur: Some(contextswitch::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::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::{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::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::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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
use actix_files as fs;
|
||||
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
|
||||
use configuration::Settings;
|
||||
use core::time::Duration;
|
||||
use std::net::TcpListener;
|
||||
use tracing::info;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
pub mod configuration;
|
||||
pub mod contextswitch;
|
||||
pub mod observability;
|
||||
pub mod routes;
|
||||
|
||||
pub fn run(listener: TcpListener, settings: &Settings) -> Result<Server, std::io::Error> {
|
||||
let api_path = settings.application.api_path.clone();
|
||||
let front_base_url = settings.application.front_base_url.clone();
|
||||
let static_path = settings.application.static_path.clone();
|
||||
let static_dir = settings
|
||||
.application
|
||||
.static_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| ".".to_string());
|
||||
|
||||
let server = HttpServer::new(move || {
|
||||
info!(
|
||||
"Mounting API on {}",
|
||||
if api_path.is_empty() { "/" } else { &api_path }
|
||||
);
|
||||
let api_scope = web::scope(&api_path)
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new()
|
||||
.add(("Access-Control-Allow-Origin", 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("/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),
|
||||
);
|
||||
|
||||
let mut app = App::new()
|
||||
.wrap(TracingLogger::default())
|
||||
.wrap(middleware::Compress::default())
|
||||
.route("/ping", web::get().to(routes::ping))
|
||||
.service(api_scope);
|
||||
if let Some(path) = &static_path {
|
||||
info!(
|
||||
"Mounting static files on {}",
|
||||
if path.is_empty() { "/" } else { path }
|
||||
);
|
||||
let static_scope = fs::Files::new(path, &static_dir)
|
||||
.use_last_modified(true)
|
||||
.index_file("index.html");
|
||||
app = app.service(static_scope);
|
||||
}
|
||||
app
|
||||
})
|
||||
.keep_alive(http::KeepAlive::Timeout(Duration::from_secs(60)))
|
||||
.shutdown_timeout(60)
|
||||
.listen(listener)?;
|
||||
|
||||
Ok(server.run())
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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, &settings)?.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,66 +0,0 @@
|
||||
use crate::contextswitch as cs;
|
||||
use actix_web::{http::StatusCode, web, HttpResponse, ResponseError};
|
||||
use anyhow::Context;
|
||||
use contextswitch::{NewTask, Task, TaskId};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TaskQuery {
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
impl ResponseError for cs::ContextswitchError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
cs::ContextswitchError::InvalidDataError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
cs::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, cs::ContextswitchError> {
|
||||
let filter = task_query
|
||||
.filter
|
||||
.as_ref()
|
||||
.map_or(vec![], |filter| filter.split(' ').collect());
|
||||
let tasks: Vec<Task> = cs::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, cs::ContextswitchError> {
|
||||
let task: Task = cs::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, cs::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 = cs::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 async fn option_task() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
use crate::helpers::app_address;
|
||||
use rstest::*;
|
||||
|
||||
#[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.");
|
||||
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(Some(0), response.content_length());
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
use contextswitch_api::configuration::Settings;
|
||||
use contextswitch_api::contextswitch::taskwarrior;
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use mktemp::Temp;
|
||||
use rstest::*;
|
||||
use std::net::TcpListener;
|
||||
use tracing::info;
|
||||
|
||||
fn setup_tracing(settings: &Settings) {
|
||||
info!("Setting up tracing");
|
||||
let subscriber = get_subscriber(&settings.application.log_directive);
|
||||
init_subscriber(subscriber);
|
||||
}
|
||||
|
||||
fn setup_server(settings: &Settings) -> 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();
|
||||
|
||||
let server = contextswitch_api::run(listener, settings).expect("Failed to bind address");
|
||||
let _ = tokio::spawn(server);
|
||||
format!("http://127.0.0.1:{}", port)
|
||||
}
|
||||
|
||||
fn setup_taskwarrior(mut settings: Settings) -> String {
|
||||
info!("Setting up Taskwarrior");
|
||||
let tmp_dir = Temp::new_dir().unwrap();
|
||||
settings.taskwarrior.data_location = tmp_dir.to_str().map(String::from);
|
||||
let task_data_location = taskwarrior::load_config(&settings.taskwarrior);
|
||||
tmp_dir.release();
|
||||
|
||||
task_data_location
|
||||
}
|
||||
|
||||
#[fixture]
|
||||
#[once]
|
||||
pub fn app_address() -> String {
|
||||
let settings = Settings::new_from_file(Some("config/test".to_string()))
|
||||
.expect("Cannot load test configuration");
|
||||
setup_tracing(&settings);
|
||||
let address = setup_server(&settings);
|
||||
setup_taskwarrior(settings);
|
||||
address
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
mod health_check;
|
||||
mod helpers;
|
||||
mod tasks;
|
||||
@@ -1,178 +0,0 @@
|
||||
use crate::helpers::app_address;
|
||||
use contextswitch::{Bookmark, ContextswitchData, NewTask, Task};
|
||||
use contextswitch_api::contextswitch as cs;
|
||||
use http::uri::Uri;
|
||||
use rstest::*;
|
||||
|
||||
mod list_tasks {
|
||||
use super::*;
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn list_tasks(app_address: &str) {
|
||||
let task = cs::add_task(vec![
|
||||
"test",
|
||||
"list_tasks",
|
||||
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let tasks: Vec<Task> = reqwest::Client::new()
|
||||
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].description, "test list_tasks");
|
||||
let cs_data = tasks[0].contextswitch.as_ref().unwrap();
|
||||
assert_eq!(cs_data.bookmarks.len(), 1);
|
||||
assert_eq!(cs_data.bookmarks[0].content, None);
|
||||
assert_eq!(
|
||||
cs_data.bookmarks[0].uri,
|
||||
"https://example.com/path?filter=1".parse::<Uri>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn list_tasks_with_unknown_cs_data(app_address: &str) {
|
||||
let task = cs::add_task(vec![
|
||||
"test",
|
||||
"list_tasks_with_unknown_cs_data",
|
||||
"contextswitch:'{\"unknown\": 1}'",
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let tasks: Vec<Task> = reqwest::Client::new()
|
||||
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].description, "test list_tasks_with_unknown_cs_data");
|
||||
assert!(tasks[0].contextswitch.is_none());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn list_tasks_with_invalid_cs_data(app_address: &str) {
|
||||
let task = cs::add_task(vec![
|
||||
"test",
|
||||
"list_tasks_with_invalid_contextswitch_data",
|
||||
"contextswitch:'}'",
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let tasks: Vec<Task> = reqwest::Client::new()
|
||||
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(
|
||||
tasks[0].description,
|
||||
"test list_tasks_with_invalid_contextswitch_data"
|
||||
);
|
||||
assert!(tasks[0].contextswitch.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
mod add_task {
|
||||
use super::*;
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn add_task(app_address: &str) {
|
||||
let task: Task = reqwest::Client::new()
|
||||
.post(&format!("{}/tasks", &app_address))
|
||||
.json(&NewTask {
|
||||
definition:
|
||||
"test add_task contextswitch:{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}"
|
||||
.to_string(),
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
assert_eq!(task.description, "test add_task");
|
||||
assert_eq!(
|
||||
task.contextswitch.as_ref().unwrap(),
|
||||
&ContextswitchData {
|
||||
bookmarks: vec![Bookmark {
|
||||
uri: "https://example.com/path?filter=1".parse::<Uri>().unwrap(),
|
||||
content: None
|
||||
}]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod update_task {
|
||||
use super::*;
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn update_task(app_address: &str) {
|
||||
let mut task = cs::add_task(vec![
|
||||
"test",
|
||||
"update_task",
|
||||
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
task.description = "updated task description".to_string();
|
||||
let cs_data = task.contextswitch.as_mut().unwrap();
|
||||
cs_data.bookmarks.push(Bookmark {
|
||||
uri: "https://example.com/path2".parse::<Uri>().unwrap(),
|
||||
content: None,
|
||||
});
|
||||
|
||||
let updated_task: Task = reqwest::Client::new()
|
||||
.put(&format!("{}/tasks/{}", &app_address, task.id))
|
||||
.json(&task)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request")
|
||||
.json()
|
||||
.await
|
||||
.expect("Cannot parse JSON result");
|
||||
|
||||
assert_eq!(updated_task.description, "updated task description");
|
||||
assert_eq!(
|
||||
updated_task.contextswitch.as_ref().unwrap(),
|
||||
&ContextswitchData {
|
||||
bookmarks: vec![
|
||||
Bookmark {
|
||||
uri: "https://example.com/path?filter=1".parse::<Uri>().unwrap(),
|
||||
content: None
|
||||
},
|
||||
Bookmark {
|
||||
uri: "https://example.com/path2".parse::<Uri>().unwrap(),
|
||||
content: None
|
||||
}
|
||||
]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// TODO : test incoherent task id
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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
|
||||
}
|
||||
+46
-191
@@ -1,202 +1,57 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use http::uri::Uri;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use uuid::Uuid;
|
||||
use actix_web::{dev::Server, middleware, web, App, HttpResponse, HttpServer};
|
||||
use listenfd::ListenFd;
|
||||
use serde::Deserialize;
|
||||
use std::env;
|
||||
use std::io::Error;
|
||||
use std::net::TcpListener;
|
||||
use tracing_actix_web::TracingLogger;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Recurrence {
|
||||
Daily,
|
||||
Weekly,
|
||||
Monthly,
|
||||
Yearly,
|
||||
pub mod contextswitch;
|
||||
pub mod observability;
|
||||
pub mod taskwarrior;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TaskQuery {
|
||||
filter: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for Recurrence {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", format!("{:?}", self).to_lowercase())
|
||||
}
|
||||
#[tracing::instrument(level = "debug", skip(task_query))]
|
||||
async fn list_tasks(task_query: web::Query<TaskQuery>) -> Result<HttpResponse, Error> {
|
||||
let tasks = contextswitch::export(task_query.filter.split(' ').collect())?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(serde_json::to_string(&tasks)?))
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Pending,
|
||||
Completed,
|
||||
Recurring,
|
||||
Deleted,
|
||||
async fn health_check() -> HttpResponse {
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
||||
|
||||
impl fmt::Display for Status {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", format!("{:?}", self).to_lowercase())
|
||||
}
|
||||
}
|
||||
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())),
|
||||
)
|
||||
.route("/ping", web::get().to(health_check))
|
||||
.route("/tasks", web::get().to(list_tasks))
|
||||
})
|
||||
.keep_alive(60)
|
||||
.shutdown_timeout(60);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
|
||||
pub enum Priority {
|
||||
H,
|
||||
M,
|
||||
L,
|
||||
}
|
||||
let mut listenfd = ListenFd::from_env();
|
||||
|
||||
impl fmt::Display for Priority {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
server = if let Some(fdlistener) = listenfd.take_tcp_listener(0)? {
|
||||
server.listen(fdlistener)?
|
||||
} else {
|
||||
server.listen(listener)?
|
||||
};
|
||||
|
||||
#[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)
|
||||
}
|
||||
Ok(server.run())
|
||||
}
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
extern crate dotenv;
|
||||
extern crate listenfd;
|
||||
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::{run, taskwarrior};
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
use std::net::TcpListener;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let subscriber = get_subscriber("info".into());
|
||||
init_subscriber(subscriber);
|
||||
|
||||
dotenv().ok();
|
||||
|
||||
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");
|
||||
run(listener)?.await
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use tracing::Level;
|
||||
use tracing::{subscriber::set_global_default, Subscriber};
|
||||
use tracing_log::LogTracer;
|
||||
use tracing_subscriber::{filter, fmt, fmt::format, layer::SubscriberExt, EnvFilter, Layer};
|
||||
|
||||
pub fn get_subscriber(env_filter_str: String) -> impl Subscriber + Send + Sync {
|
||||
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)
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use configparser::ini::Ini;
|
||||
use serde::{Deserialize, 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)]
|
||||
pub struct Task {
|
||||
pub uuid: Uuid,
|
||||
pub id: u32,
|
||||
#[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>,
|
||||
}
|
||||
|
||||
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));
|
||||
return taskrc.get("default", "data.location").unwrap_or_else(|| {
|
||||
panic!(
|
||||
"'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", "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);
|
||||
|
||||
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)?;
|
||||
|
||||
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()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub mod test_helper;
|
||||
|
||||
#[tokio::test]
|
||||
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.");
|
||||
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(Some(0), response.content_length());
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
pub mod test_helper;
|
||||
|
||||
use contextswitch_api::taskwarrior;
|
||||
use contextswitch_types::Task;
|
||||
|
||||
#[tokio::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();
|
||||
|
||||
let response: reqwest::Response = client
|
||||
.get(&format!("{}/tasks?filter=ls", &address))
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to execute request.");
|
||||
|
||||
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");
|
||||
|
||||
let cs_metadata = tasks[0].contextswitch.as_ref().unwrap();
|
||||
assert_eq!(cs_metadata.test, 1);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use contextswitch_api::observability::{get_subscriber, init_subscriber};
|
||||
use contextswitch_api::taskwarrior;
|
||||
use mktemp::Temp;
|
||||
use once_cell::sync::Lazy;
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
|
||||
static TRACING: Lazy<()> = Lazy::new(|| {
|
||||
let subscriber = get_subscriber("info".to_string());
|
||||
init_subscriber(subscriber);
|
||||
});
|
||||
|
||||
pub fn spawn_app() -> String {
|
||||
Lazy::force(&TRACING);
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
pub fn setup_tasks() -> String {
|
||||
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;
|
||||
}
|
||||
|
||||
pub fn clear_tasks(task_data_location: String) {
|
||||
fs::remove_dir_all(task_data_location).unwrap();
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
[package]
|
||||
name = "contextswitch-web"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["David Rousselie <david@rousselie.name>"]
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
path = "src/main.rs"
|
||||
name = "contextswitch-web"
|
||||
|
||||
[dependencies]
|
||||
contextswitch = { path = ".." }
|
||||
yew = "0.19"
|
||||
reqwasm = "0.5"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
uikit-rs = { git = "https://github.com/dax/uikit-rs.git" }
|
||||
wasm-bindgen = "0.2.79"
|
||||
@@ -1,12 +0,0 @@
|
||||
extend = "../Makefile.toml"
|
||||
|
||||
[tasks.build-release]
|
||||
install_crate = { crate_name = "trunk", binary = "trunk" }
|
||||
command = "trunk"
|
||||
args = ["build", "--release"]
|
||||
|
||||
[tasks.run]
|
||||
clear = true
|
||||
install_crate = { crate_name = "trunk", binary = "trunk" }
|
||||
command = "trunk"
|
||||
args = ["serve"]
|
||||
Vendored
-1
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Contextswitch</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="css/uikit.min.css" />
|
||||
<script src="js/uikit.min.js"></script>
|
||||
<script src="js/uikit-icons.min.js"></script>
|
||||
<link data-trunk rel="copy-dir" href="css" />
|
||||
<link data-trunk rel="copy-dir" href="js" />
|
||||
</head>
|
||||
</html>
|
||||
@@ -1,3 +0,0 @@
|
||||
export function get_api_base_url() {
|
||||
return "http://localhost:8000/api";
|
||||
}
|
||||
Vendored
-1
File diff suppressed because one or more lines are too long
Vendored
-1
File diff suppressed because one or more lines are too long
@@ -1,2 +0,0 @@
|
||||
pub mod task;
|
||||
pub mod tasks_list;
|
||||
@@ -1,190 +0,0 @@
|
||||
use contextswitch;
|
||||
use uikit_rs as uk;
|
||||
use yew::{classes, function_component, html, Callback, Classes, Html, MouseEvent, Properties};
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TaskProps {
|
||||
pub task: contextswitch::Task,
|
||||
#[prop_or_default]
|
||||
pub selected: bool,
|
||||
#[prop_or_default]
|
||||
pub on_task_select: Callback<Option<contextswitch::Task>>,
|
||||
}
|
||||
|
||||
#[function_component(Task)]
|
||||
pub fn task(
|
||||
TaskProps {
|
||||
task,
|
||||
selected,
|
||||
on_task_select,
|
||||
}: &TaskProps,
|
||||
) -> Html {
|
||||
let toggle_details = {
|
||||
let task = task.clone();
|
||||
let on_task_select = on_task_select.clone();
|
||||
let is_task_selected = *selected;
|
||||
Callback::from(move |_| {
|
||||
on_task_select.emit(if is_task_selected {
|
||||
None
|
||||
} else {
|
||||
Some(task.clone())
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
let text_style = if task.status == contextswitch::Status::Completed {
|
||||
uk::Text::Success
|
||||
} else {
|
||||
uk::Text::Emphasis
|
||||
};
|
||||
let arrow = if *selected {
|
||||
uk::IconType::TriangleDown
|
||||
} else {
|
||||
uk::IconType::TriangleRight
|
||||
};
|
||||
|
||||
let task_status_class: Classes = format!("task-status-{}", task.status).into();
|
||||
let bookmark_count = if let Some(contextswitch) = &task.contextswitch {
|
||||
contextswitch.bookmarks.len()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
html! {
|
||||
<uk::Card size={uk::CardSize::Small}
|
||||
style={uk::CardStyle::Default}
|
||||
hover={true}
|
||||
width={uk::Width::_1_1}
|
||||
class={task_status_class}>
|
||||
<uk::CardBody padding={vec![uk::Padding::RemoveVertical]}
|
||||
margin={vec![uk::Margin::SmallTop, uk::Margin::SmallBottom]}>
|
||||
<uk::Grid gap_size={uk::GridGapSize::Small}
|
||||
vertical_alignement={uk::FlexVerticalAlignement::Middle}>
|
||||
<uk::Icon icon_type={uk::IconType::Check}
|
||||
text_style={vec![text_style]} />
|
||||
<TaskDescription task={task.clone()}
|
||||
onclick={toggle_details.clone()} />
|
||||
<uk::IconNav>
|
||||
<li>
|
||||
<uk::Icon icon_type={uk::IconType::FileEdit} href="#" />
|
||||
</li>
|
||||
<li>
|
||||
<uk::Link href="#" onclick={toggle_details.clone()}>
|
||||
<uk::Icon icon_type={uk::IconType::Bookmark} />
|
||||
<span> {bookmark_count}</span>
|
||||
</uk::Link>
|
||||
</li>
|
||||
</uk::IconNav>
|
||||
<uk::Icon icon_type={arrow} href="#" onclick={toggle_details} />
|
||||
</uk::Grid>
|
||||
{
|
||||
if *selected {
|
||||
html! {
|
||||
<TaskDetails task={task.clone()} />
|
||||
}
|
||||
} else { html! {} }
|
||||
}
|
||||
</uk::CardBody>
|
||||
</uk::Card>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TaskDescriptionProps {
|
||||
pub task: contextswitch::Task,
|
||||
#[prop_or_default]
|
||||
pub onclick: Callback<MouseEvent>,
|
||||
}
|
||||
|
||||
#[function_component(TaskDescription)]
|
||||
pub fn task_description(TaskDescriptionProps { task, onclick }: &TaskDescriptionProps) -> Html {
|
||||
html! {
|
||||
<uk::Flex width={uk::Width::_Expand} onclick={onclick}>
|
||||
<uk::CardTitle text_style={vec![uk::Text::Lighter]}>
|
||||
{task.description.clone()}
|
||||
</uk::CardTitle>
|
||||
</uk::Flex>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TaskDetailsProps {
|
||||
pub task: contextswitch::Task,
|
||||
}
|
||||
|
||||
#[function_component(TaskDetails)]
|
||||
pub fn task_details(TaskDetailsProps { task }: &TaskDetailsProps) -> Html {
|
||||
let priority = task
|
||||
.priority
|
||||
.as_ref()
|
||||
.map(|prio| prio.to_string())
|
||||
.unwrap_or_else(|| "-".to_string());
|
||||
let project = task
|
||||
.project
|
||||
.as_ref()
|
||||
.map(|proj| proj.to_string())
|
||||
.unwrap_or_else(|| "-".to_string());
|
||||
|
||||
html! {
|
||||
<div class={classes!(uk::Margin::Small)}>
|
||||
<uk::Divider margin={vec![uk::Margin::Small]} />
|
||||
{
|
||||
if let Some(contextswitch) = &task.contextswitch {
|
||||
html! {
|
||||
<TaskContextswitch contextswitch={contextswitch.clone()} />
|
||||
}
|
||||
} else { html! {} }
|
||||
}
|
||||
<uk::Grid gap_size={uk::GridGapSize::Small}
|
||||
child_width={uk::ChildWidth::_Expand}>
|
||||
<span class={classes!(uk::Text::Meta)}>
|
||||
{ format!("priority: {}", priority) }
|
||||
</span>
|
||||
<span class={classes!(uk::Text::Meta)}>
|
||||
{ format!("project: {}", project) }
|
||||
</span>
|
||||
</uk::Grid>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TaskContextswitchProps {
|
||||
pub contextswitch: contextswitch::ContextswitchData,
|
||||
}
|
||||
|
||||
#[function_component(TaskContextswitch)]
|
||||
pub fn task_contextswitch(
|
||||
TaskContextswitchProps { contextswitch }: &TaskContextswitchProps,
|
||||
) -> Html {
|
||||
html! {
|
||||
<uk::Grid gap_size={uk::GridGapSize::Small} height_match={true}>
|
||||
{
|
||||
contextswitch.bookmarks.iter().map(|bookmark| {
|
||||
html! {
|
||||
<TaskBookmark bookmark={bookmark.clone()} />
|
||||
}
|
||||
}).collect::<Html>()
|
||||
}
|
||||
<uk::Icon icon_type={uk::IconType::Plus}
|
||||
margin={vec![uk::Margin::Remove]} />
|
||||
</uk::Grid>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TaskBookmarkProps {
|
||||
pub bookmark: contextswitch::Bookmark,
|
||||
}
|
||||
|
||||
#[function_component(TaskBookmark)]
|
||||
pub fn task_bookmark(TaskBookmarkProps { bookmark }: &TaskBookmarkProps) -> Html {
|
||||
html! {
|
||||
<div class={classes!(uk::Width::_1_1, uk::Text::Small, uk::Margin::Remove)}>
|
||||
<uk::Grid gap_size={uk::GridGapSize::Small} vertical_alignement={uk::FlexVerticalAlignement::Middle}>
|
||||
<uk::Icon icon_type={uk::IconType::Bookmark} />
|
||||
<uk::Link href={bookmark.uri.to_string()}>{bookmark.uri.to_string()}</uk::Link>
|
||||
</uk::Grid>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
use crate::components::task;
|
||||
use contextswitch::Task;
|
||||
use yew::prelude::*;
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct TasksListProps {
|
||||
#[prop_or_default]
|
||||
pub tasks: Vec<Task>,
|
||||
#[prop_or_default]
|
||||
pub selected_task: Option<Task>,
|
||||
#[prop_or_default]
|
||||
pub on_task_select: Callback<Option<Task>>,
|
||||
}
|
||||
|
||||
#[function_component(TasksList)]
|
||||
pub fn tasks_list(
|
||||
TasksListProps {
|
||||
tasks,
|
||||
selected_task,
|
||||
on_task_select,
|
||||
}: &TasksListProps,
|
||||
) -> Html {
|
||||
tasks
|
||||
.iter()
|
||||
.map(|task| {
|
||||
let task_is_selected = selected_task
|
||||
.clone()
|
||||
.map(|t| t.id == task.id)
|
||||
.unwrap_or(false);
|
||||
|
||||
html! {
|
||||
<task::Task selected={task_is_selected}
|
||||
on_task_select={on_task_select}
|
||||
task={task.clone()} />
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
use components::tasks_list::TasksList;
|
||||
use contextswitch::Task;
|
||||
use reqwasm::http::Request;
|
||||
use uikit_rs as uk;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use yew::prelude::*;
|
||||
|
||||
mod components;
|
||||
|
||||
#[wasm_bindgen(module = "/js/api.js")]
|
||||
extern "C" {
|
||||
fn get_api_base_url() -> String;
|
||||
}
|
||||
|
||||
#[function_component(App)]
|
||||
pub fn app() -> Html {
|
||||
let tasks = use_state(Vec::new);
|
||||
{
|
||||
let tasks = tasks.clone();
|
||||
use_effect_with_deps(
|
||||
move |_| {
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let fetched_tasks: Vec<Task> =
|
||||
Request::get(&format!("{}/tasks?filter=task", get_api_base_url()))
|
||||
.send()
|
||||
.await
|
||||
.unwrap() // TODO
|
||||
.json()
|
||||
.await
|
||||
.unwrap(); // TODO
|
||||
tasks.set(fetched_tasks);
|
||||
});
|
||||
|| ()
|
||||
},
|
||||
(),
|
||||
);
|
||||
}
|
||||
let selected_task = use_state(|| None);
|
||||
let on_task_select = {
|
||||
let selected_task = selected_task.clone();
|
||||
Callback::from(move |task: Option<Task>| {
|
||||
selected_task.set(task);
|
||||
})
|
||||
};
|
||||
|
||||
html! {
|
||||
<uk::Section style={uk::SectionStyle::Default}>
|
||||
<uk::Container size={uk::ContainerSize::Small}>
|
||||
<uk::Filter target=".status-filter"
|
||||
filter_width={uk::Width::_Expand}
|
||||
filter_component={uk::UIKitComponent::SubNav}
|
||||
filter_class={"uk-subnav-pill"}
|
||||
filters={vec![uk::FilterData { class: "".to_string(), label: "all".to_string() },
|
||||
uk::FilterData { class: ".task-status-pending".to_string(), label: "pending".to_string() },
|
||||
uk::FilterData { class: ".task-status-completed".to_string(), label: "completed".to_string() }]}>
|
||||
<uk::Grid gap_size={uk::GridGapSize::Small}
|
||||
margin={vec![uk::Margin::Default]}
|
||||
height_match={true}
|
||||
class={"status-filter"}>
|
||||
<TasksList tasks={(*tasks).clone()}
|
||||
selected_task={(*selected_task).clone()}
|
||||
on_task_select={on_task_select} />
|
||||
</uk::Grid>
|
||||
</uk::Filter>
|
||||
</uk::Container>
|
||||
</uk::Section>
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
use contextswitch_web::App;
|
||||
|
||||
fn main() {
|
||||
yew::start_app::<App>();
|
||||
}
|
||||
Reference in New Issue
Block a user