diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index a945a565d..000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,3 +0,0 @@ -taskchampion/* @dbr @djmitche -Cargo.toml @dbr @djmitche -Cargo.lock @dbr @djmitche diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 96553404a..c95ba45fa 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -44,22 +44,6 @@ jobs: args: --all-features name: "Clippy Results" - mdbook: - runs-on: ubuntu-latest - name: "Documentation" - - steps: - - uses: actions/checkout@v4 - - - name: Setup mdBook - uses: peaceiris/actions-mdbook@v2 - with: - # if this changes, change it in .github/workflows/publish-docs.yml as well - mdbook-version: '0.4.10' - - - run: mdbook test taskchampion/docs - - run: mdbook build taskchampion/docs - fmt: runs-on: ubuntu-latest name: "Formatting" diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml deleted file mode 100644 index dfa4c54e7..000000000 --- a/.github/workflows/publish-docs.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: docs - -on: - push: - branches: - - develop - -permissions: - contents: write - -jobs: - mdbook-deploy: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - name: Setup mdBook - uses: peaceiris/actions-mdbook@v2 - with: - # if this changes, change it in .github/workflows/checks.yml as well - mdbook-version: '0.4.10' - - - run: mdbook build taskchampion/docs - - - name: Deploy - uses: peaceiris/actions-gh-pages@v4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./taskchampion/docs/book - destination_dir: taskchampion diff --git a/.github/workflows/rust-tests.yml b/.github/workflows/rust-tests.yml deleted file mode 100644 index cf11d390c..000000000 --- a/.github/workflows/rust-tests.yml +++ /dev/null @@ -1,83 +0,0 @@ - -name: tests - rust - -on: - push: - branches: - - develop - pull_request: - types: [opened, reopened, synchronize] - -jobs: - ## Run the `taskchampion` crate's tests with various combinations of features. - features: - strategy: - matrix: - features: - - "" - - "server-sync" - - name: "taskchampion ${{ matrix.features == '' && 'with no features' || format('with features {0}', matrix.features) }}" - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - name: Cache cargo registry - uses: actions/cache@v4 - with: - path: ~/.cargo/registry - key: ubuntu-latest-stable-cargo-registry-${{ hashFiles('**/Cargo.lock') }} - - - name: Cache cargo build - uses: actions/cache@v4 - with: - path: target - key: ubuntu-latest-stable-cargo-build-target-${{ hashFiles('**/Cargo.lock') }} - - - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - override: true - - - name: test - run: cargo test -p taskchampion --no-default-features --features "${{ matrix.features }}" - - ## Run all TaskChampion crate tests, using both the minimum supported rust version - ## and the latest stable Rust. - test: - strategy: - matrix: - rust: - - "1.70.0" # MSRV - - "stable" - os: - - ubuntu-latest - - macOS-latest - - windows-latest - - name: "rust ${{ matrix.rust }} on ${{ matrix.os }}" - runs-on: ${{ matrix.os }} - - steps: - - uses: actions/checkout@v4 - - - name: Cache cargo registry - uses: actions/cache@v4 - with: - path: ~/.cargo/registry - key: ${{ runner.os }}-${{ matrix.rust }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} - - - name: Cache cargo build - uses: actions/cache@v4 - with: - path: target - key: ${{ runner.os }}-${{ matrix.rust }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }} - - - uses: actions-rs/toolchain@v1 - with: - toolchain: "${{ matrix.rust }}" - override: true - - - name: test - run: cargo test diff --git a/Cargo.lock b/Cargo.lock index 8d742b235..11c8e2d7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -124,21 +124,6 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - [[package]] name = "bitflags" version = "1.3.2" @@ -288,27 +273,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "errno" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" -dependencies = [ - "errno-dragonfly", - "libc", - "windows-sys 0.48.0", -] - -[[package]] -name = "errno-dragonfly" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" -dependencies = [ - "cc", - "libc", -] - [[package]] name = "fallible-iterator" version = "0.2.0" @@ -321,15 +285,6 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - [[package]] name = "ffizz-header" version = "0.5.0" @@ -378,21 +333,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "futures" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - [[package]] name = "futures-channel" version = "0.3.25" @@ -400,7 +340,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed" dependencies = [ "futures-core", - "futures-sink", ] [[package]] @@ -409,17 +348,6 @@ version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" -[[package]] -name = "futures-executor" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - [[package]] name = "futures-io" version = "0.3.25" @@ -449,19 +377,12 @@ version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" -[[package]] -name = "futures-timer" -version = "3.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" - [[package]] name = "futures-util" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" dependencies = [ - "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -631,12 +552,6 @@ dependencies = [ "libc", ] -[[package]] -name = "hermit-abi" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" - [[package]] name = "hex" version = "0.4.3" @@ -758,39 +673,6 @@ dependencies = [ "hashbrown 0.11.2", ] -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "integration-tests" -version = "0.4.1" -dependencies = [ - "anyhow", - "cc", - "lazy_static", - "pretty_assertions", - "taskchampion", - "taskchampion-lib", - "tempfile", -] - -[[package]] -name = "io-lifetimes" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" -dependencies = [ - "hermit-abi 0.3.1", - "libc", - "windows-sys 0.48.0", -] - [[package]] name = "ipnet" version = "2.9.0" @@ -847,12 +729,6 @@ version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" -[[package]] -name = "libm" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" - [[package]] name = "libsqlite3-sys" version = "0.26.0" @@ -884,12 +760,6 @@ dependencies = [ "syn 1.0.104", ] -[[package]] -name = "linux-raw-sys" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" - [[package]] name = "lock_api" version = "0.4.7" @@ -988,7 +858,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" dependencies = [ "autocfg", - "libm", ] [[package]] @@ -997,7 +866,7 @@ version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" dependencies = [ - "hermit-abi 0.1.19", + "hermit-abi", "libc", ] @@ -1034,7 +903,7 @@ checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.13", + "redox_syscall", "smallvec", "windows-sys 0.45.0", ] @@ -1091,12 +960,6 @@ version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - [[package]] name = "pretty_assertions" version = "1.4.0" @@ -1116,32 +979,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proptest" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b476131c3c86cb68032fdc5cb6d5a1045e3e42d96b69fa599fd77701e1f5bf" -dependencies = [ - "bit-set", - "bit-vec", - "bitflags 2.0.2", - "lazy_static", - "num-traits", - "rand", - "rand_chacha", - "rand_xorshift", - "regex-syntax", - "rusty-fork", - "tempfile", - "unarray", -] - -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quote" version = "1.0.28" @@ -1151,45 +988,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_xorshift" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" -dependencies = [ - "rand_core", -] - [[package]] name = "redox_syscall" version = "0.2.13" @@ -1199,15 +997,6 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "redox_syscall" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "regex" version = "1.10.2" @@ -1308,32 +1097,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "rstest" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de1bb486a691878cd320c2f0d319ba91eeaa2e894066d8b5f8f117c000e9d962" -dependencies = [ - "futures", - "futures-timer", - "rstest_macros", - "rustc_version", -] - -[[package]] -name = "rstest_macros" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290ca1a1c8ca7edb7c3283bd44dc35dd54fdec6253a3912e201ba1072018fca8" -dependencies = [ - "cfg-if", - "proc-macro2", - "quote", - "rustc_version", - "syn 1.0.104", - "unicode-ident", -] - [[package]] name = "rusqlite" version = "0.29.0" @@ -1354,29 +1117,6 @@ version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver", -] - -[[package]] -name = "rustix" -version = "0.37.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4eb579851244c2c03e7c24f501c3432bed80b8f720af1d6e5b0e0f01555a035" -dependencies = [ - "bitflags 1.3.2", - "errno", - "io-lifetimes", - "libc", - "linux-raw-sys", - "windows-sys 0.48.0", -] - [[package]] name = "rustls" version = "0.21.11" @@ -1414,18 +1154,6 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" -[[package]] -name = "rusty-fork" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f" -dependencies = [ - "fnv", - "quick-error", - "tempfile", - "wait-timeout", -] - [[package]] name = "ryu" version = "1.0.10" @@ -1448,12 +1176,6 @@ dependencies = [ "untrusted 0.7.1", ] -[[package]] -name = "semver" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" - [[package]] name = "serde" version = "1.0.147" @@ -1617,7 +1339,9 @@ dependencies = [ [[package]] name = "taskchampion" -version = "0.4.1" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e9e2d64086cc515f801ba0e1f366e5e029dd47db3c499a9e173a60b62145410" dependencies = [ "anyhow", "byteorder", @@ -1625,16 +1349,12 @@ dependencies = [ "flate2", "google-cloud-storage", "log", - "pretty_assertions", - "proptest", "ring 0.17.3", - "rstest", "rusqlite", "serde", "serde_json", "strum", "strum_macros", - "tempfile", "thiserror", "tokio", "ureq", @@ -1653,20 +1373,6 @@ dependencies = [ "taskchampion", ] -[[package]] -name = "tempfile" -version = "3.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" -dependencies = [ - "autocfg", - "cfg-if", - "fastrand", - "redox_syscall 0.3.5", - "rustix", - "windows-sys 0.48.0", -] - [[package]] name = "thiserror" version = "1.0.37" @@ -1842,12 +1548,6 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - [[package]] name = "unicase" version = "2.7.0" @@ -1945,15 +1645,6 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" -[[package]] -name = "wait-timeout" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" -dependencies = [ - "libc", -] - [[package]] name = "want" version = "0.3.1" diff --git a/Cargo.toml b/Cargo.toml index efe0c179d..3d6494992 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,17 +1,12 @@ [workspace] members = [ - "taskchampion/taskchampion", - "taskchampion/lib", - "taskchampion/integration-tests", - "taskchampion/xtask", + "src/tc/lib", + "xtask", ] resolver = "2" -# src/tc/rust is just part of the TW build and not a public crate -exclude = [ "src/tc/rust" ] - # All Rust dependencies are defined here, and then referenced by the # Cargo.toml's in the members with `foo.workspace = true`. [workspace.dependencies] @@ -40,3 +35,4 @@ thiserror = "1.0" ureq = { version = "^2.9.0", features = ["tls"] } uuid = { version = "^1.8.0", features = ["serde", "v4"] } url = { version = "2" } +taskchampion = "0.5" diff --git a/doc/devel/README.md b/doc/devel/README.md index 7a09621b5..4f55544e3 100644 --- a/doc/devel/README.md +++ b/doc/devel/README.md @@ -11,10 +11,6 @@ For all other documenation, see https://taskwarrior.org. As of the 3.0 release, Taskwarrior uses TaskChampion to manage task data. Find documentation of TaskChampion here: - * [TaskChampion README](../../taskchampion) - * [TaskChampion CONTRIBUTING guide](../../taskchampion/CONTRIBUTING.md) - * [TaskChampion Book](../../taskchampion/docs/src/SUMMARY.md) + * [TaskChampion Repository](https://github.com/GothenburgBitFactory/taskchampion/) + * [TaskChampion Book](https://gothenburgbitfactory.github.io/taskchampion/) * [TaskChampion API Documentation](https://docs.rs/taskchampion) - -TaskChampion will [become its own -project](https://github.com/GothenburgBitFactory/taskwarrior/issues/3209) soon. diff --git a/doc/devel/contrib/development.md b/doc/devel/contrib/development.md index ff6ff5d98..4a29f14ea 100644 --- a/doc/devel/contrib/development.md +++ b/doc/devel/contrib/development.md @@ -1,12 +1,5 @@ # Developing Taskwarrior -The following describes the process for developing Taskwarrior. If you are only -changing TaskChampion (Rust code), you can simply treat it like any other Rust -project: modify the source under `taskchampion/` and use `cargo test` to run -the TaskChampion tests. - -See the [TaskChampion CONTRIBUTING guide](../../../taskchampion/CONTRIBUTING.md) for more. - ## Satisfy the Requirements: * CMake 3.0 or later diff --git a/doc/devel/contrib/releasing.md b/doc/devel/contrib/releasing.md index 15fd1292a..da002ca9f 100644 --- a/doc/devel/contrib/releasing.md +++ b/doc/devel/contrib/releasing.md @@ -11,7 +11,6 @@ To release Taskwarrior, follow this process: - On `develop` after that PR merges, create a release tarball: - `git clone . release-tarball` - `cd release-tarball/` - - edit `Cargo.toml` to contain only `taskchampion` and `taskchampion-lib` in `members` (see https://github.com/GothenburgBitFactory/taskwarrior/issues/3294). - `cmake -S. -Bbuild` - `make -Cbuild package_source` - copy build/task-*.tar.gz elsewhere and delete the `release-tarball` dir diff --git a/doc/devel/contrib/rust-and-c++.md b/doc/devel/contrib/rust-and-c++.md index e0244424d..5317985e3 100644 --- a/doc/devel/contrib/rust-and-c++.md +++ b/doc/devel/contrib/rust-and-c++.md @@ -1,42 +1,21 @@ # Rust and C++ -Taskwarrior has historically been a C++ project, but as part of an [ongoing effort to replace its storage backend](https://github.com/GothenburgBitFactory/taskwarrior/issues/2770) it now includes a Rust library called TaskChampion. -To develop Taskwarrior, you will need both a [C++ compiler and tools](./development.md), and a [Rust toolchain](https://www.rust-lang.org/tools/install). -However, most tasks will only require you to be familiar with one of the two languages. +Taskwarrior has historically been a C++ project, but as of taskwarrior-3.0.0, the storage backend is now provided by a Rust library called TaskChampion. ## TaskChampion TaskChampion implements storage and access to "replicas" containing a user's tasks. It defines an abstract model for this data, and also provides a simple Rust API for manipulating replicas. It also defines a method of synchronizing replicas and provides an implementation of that method in the form of a sync server. -TaskChampion provides a C interface via the `taskchampion-lib` crate. +TaskChampion provides a C interface via the `taskchampion-lib` crate, at `src/tc/lib`. Other applications, besides Taskwarrior, can use TaskChampion to manage tasks. -Applications written in Rust can use the `taskchampion` crate, while those in other languages may use the `taskchampion-lib` crate. Taskwarrior is just one application using the TaskChampion interface. -You can build TaskChampion locally by simply running `cargo build` in the root of this repository. -The implementation, including more documentation, is in the [`rust`](../../rust) subdirectory. - ## Taskwarrior's use of TaskChampion Taskwarrior's interface to TaskChampion has a few layers: -* The skeletal Rust crate in [`src/tc/rust`](../../src/tc/rust) brings the symbols from `taskchampion-lib` under CMake's management. - The corresponding header file is included from [`taskchampion/lib`](../../taskchampion/lib). - All of these symbols are placed in the C++ namespace, `tc::ffi`. -* C++ wrappers for the types from `taskchampion-lib` are defined in [`src/tc`](../../src/tc), ensuring memory safety (with `unique_ptr`) and adding methods corresponding to the Rust API's methods. +* A Rust library, `takschampion-lib`, that presents `extern "C"` functions for use from C++, essentially defining a C interface to TaskChampion. +* C++ wrappers for the types from `taskchampion-lib`, defined in [`src/tc`](../../src/tc), ensuring memory safety (with `unique_ptr`) and adding methods corresponding to the Rust API's methods. The wrapper types are in the C++ namespace, `tc`. - -## WARNING About Dependency Tracking - -CMake cannot detect changes to Rust files in under the `taskchampion/` directory. -Running `make` after these files are changed will not incorporate the changes into the resulting executables. -To force re-compilation of the Rust dependencies: - -``` -rm -rf src/tc/rust/x86_64-unknown-linux-gnu/debug/libtc_rust.a -make -``` - -You may need to adjust the `x86_64-unknown-linux-gnu` part of that command depending on what system you are using for development. diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9b095c45e..1c269770b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -2,10 +2,10 @@ cmake_minimum_required (VERSION 3.22) include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/src/tc + ${CMAKE_SOURCE_DIR}/src/tc/lib ${CMAKE_SOURCE_DIR}/src/commands ${CMAKE_SOURCE_DIR}/src/columns ${CMAKE_SOURCE_DIR}/src/libshared/src - ${CMAKE_SOURCE_DIR}/taskchampion/lib ${TASK_INCLUDE_DIRS}) add_library (task STATIC CLI2.cpp CLI2.h diff --git a/src/columns/CMakeLists.txt b/src/columns/CMakeLists.txt index f667aac33..ced88cb77 100644 --- a/src/columns/CMakeLists.txt +++ b/src/columns/CMakeLists.txt @@ -2,10 +2,10 @@ cmake_minimum_required (VERSION 3.22) include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/src/tc + ${CMAKE_SOURCE_DIR}/src/tc/lib ${CMAKE_SOURCE_DIR}/src/commands ${CMAKE_SOURCE_DIR}/src/columns ${CMAKE_SOURCE_DIR}/src/libshared/src - ${CMAKE_SOURCE_DIR}/taskchampion/lib ${TASK_INCLUDE_DIRS}) set (columns_SRCS Column.cpp Column.h diff --git a/src/commands/CMakeLists.txt b/src/commands/CMakeLists.txt index c71718d22..16b8025af 100644 --- a/src/commands/CMakeLists.txt +++ b/src/commands/CMakeLists.txt @@ -2,10 +2,10 @@ cmake_minimum_required (VERSION 3.22) include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/src/tc + ${CMAKE_SOURCE_DIR}/src/tc/lib ${CMAKE_SOURCE_DIR}/src/commands ${CMAKE_SOURCE_DIR}/src/columns ${CMAKE_SOURCE_DIR}/src/libshared/src - ${CMAKE_SOURCE_DIR}/taskchampion/lib ${TASK_INCLUDE_DIRS}) set (commands_SRCS Command.cpp Command.h diff --git a/src/tc/CMakeLists.txt b/src/tc/CMakeLists.txt index 165af059c..883367e63 100644 --- a/src/tc/CMakeLists.txt +++ b/src/tc/CMakeLists.txt @@ -8,15 +8,18 @@ corrosion_import_crate( LOCKED CRATES "taskchampion-lib") +# TODO(#3425): figure out how to create taskchampion.h + include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/src/tc + ${CMAKE_SOURCE_DIR}/src/tc/lib ${CMAKE_SOURCE_DIR}/src/libshared/src - ${CMAKE_SOURCE_DIR}/taskchampion/lib ${TASK_INCLUDE_DIRS}) set (tc_SRCS ffi.h + lib/taskchampion.h util.cpp util.h Replica.cpp Replica.h Server.cpp Server.h diff --git a/taskchampion/lib/Cargo.toml b/src/tc/lib/Cargo.toml similarity index 84% rename from taskchampion/lib/Cargo.toml rename to src/tc/lib/Cargo.toml index e9257da28..ecfb1e931 100644 --- a/taskchampion/lib/Cargo.toml +++ b/src/tc/lib/Cargo.toml @@ -2,6 +2,7 @@ name = "taskchampion-lib" version = "0.1.0" edition = "2021" +publish = false [lib] crate-type = ["staticlib", "rlib"] @@ -10,8 +11,7 @@ crate-type = ["staticlib", "rlib"] libc.workspace = true anyhow.workspace = true ffizz-header.workspace = true - -taskchampion = { path = "../taskchampion" } +taskchampion.workspace = true [dev-dependencies] pretty_assertions.workspace = true diff --git a/taskchampion/lib/Makefile b/src/tc/lib/Makefile similarity index 100% rename from taskchampion/lib/Makefile rename to src/tc/lib/Makefile diff --git a/taskchampion/lib/src/annotation.rs b/src/tc/lib/src/annotation.rs similarity index 100% rename from taskchampion/lib/src/annotation.rs rename to src/tc/lib/src/annotation.rs diff --git a/taskchampion/lib/src/atomic.rs b/src/tc/lib/src/atomic.rs similarity index 100% rename from taskchampion/lib/src/atomic.rs rename to src/tc/lib/src/atomic.rs diff --git a/taskchampion/lib/src/kv.rs b/src/tc/lib/src/kv.rs similarity index 100% rename from taskchampion/lib/src/kv.rs rename to src/tc/lib/src/kv.rs diff --git a/taskchampion/lib/src/lib.rs b/src/tc/lib/src/lib.rs similarity index 100% rename from taskchampion/lib/src/lib.rs rename to src/tc/lib/src/lib.rs diff --git a/taskchampion/lib/src/replica.rs b/src/tc/lib/src/replica.rs similarity index 100% rename from taskchampion/lib/src/replica.rs rename to src/tc/lib/src/replica.rs diff --git a/taskchampion/lib/src/result.rs b/src/tc/lib/src/result.rs similarity index 100% rename from taskchampion/lib/src/result.rs rename to src/tc/lib/src/result.rs diff --git a/taskchampion/lib/src/server.rs b/src/tc/lib/src/server.rs similarity index 100% rename from taskchampion/lib/src/server.rs rename to src/tc/lib/src/server.rs diff --git a/taskchampion/lib/src/status.rs b/src/tc/lib/src/status.rs similarity index 100% rename from taskchampion/lib/src/status.rs rename to src/tc/lib/src/status.rs diff --git a/taskchampion/lib/src/string.rs b/src/tc/lib/src/string.rs similarity index 100% rename from taskchampion/lib/src/string.rs rename to src/tc/lib/src/string.rs diff --git a/taskchampion/lib/src/task.rs b/src/tc/lib/src/task.rs similarity index 100% rename from taskchampion/lib/src/task.rs rename to src/tc/lib/src/task.rs diff --git a/taskchampion/lib/src/traits.rs b/src/tc/lib/src/traits.rs similarity index 100% rename from taskchampion/lib/src/traits.rs rename to src/tc/lib/src/traits.rs diff --git a/taskchampion/lib/src/uda.rs b/src/tc/lib/src/uda.rs similarity index 100% rename from taskchampion/lib/src/uda.rs rename to src/tc/lib/src/uda.rs diff --git a/taskchampion/lib/src/util.rs b/src/tc/lib/src/util.rs similarity index 100% rename from taskchampion/lib/src/util.rs rename to src/tc/lib/src/util.rs diff --git a/taskchampion/lib/src/uuid.rs b/src/tc/lib/src/uuid.rs similarity index 100% rename from taskchampion/lib/src/uuid.rs rename to src/tc/lib/src/uuid.rs diff --git a/taskchampion/lib/src/workingset.rs b/src/tc/lib/src/workingset.rs similarity index 100% rename from taskchampion/lib/src/workingset.rs rename to src/tc/lib/src/workingset.rs diff --git a/taskchampion/lib/taskchampion.h b/src/tc/lib/taskchampion.h similarity index 100% rename from taskchampion/lib/taskchampion.h rename to src/tc/lib/taskchampion.h diff --git a/taskchampion/.changelogs/.gitignore b/taskchampion/.changelogs/.gitignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/taskchampion/.changelogs/2021-10-03-server-storage.md b/taskchampion/.changelogs/2021-10-03-server-storage.md deleted file mode 100644 index 7834601d5..000000000 --- a/taskchampion/.changelogs/2021-10-03-server-storage.md +++ /dev/null @@ -1,2 +0,0 @@ -- The SQLite server storage schema has changed incompatibly, in order to add support for snapshots. - As this is not currently ready for production usage, no migration path is provided except deleting the existing database. diff --git a/taskchampion/.changelogs/2021-10-11-issue23-client.md b/taskchampion/.changelogs/2021-10-11-issue23-client.md deleted file mode 100644 index 91a6b0f9e..000000000 --- a/taskchampion/.changelogs/2021-10-11-issue23-client.md +++ /dev/null @@ -1,2 +0,0 @@ -- The `avoid_snapshots` configuration value, if set, will cause the replica to - avoid creating snapshots unless required. diff --git a/taskchampion/.changelogs/2021-10-16-issue299.md b/taskchampion/.changelogs/2021-10-16-issue299.md deleted file mode 100644 index a74af24c5..000000000 --- a/taskchampion/.changelogs/2021-10-16-issue299.md +++ /dev/null @@ -1 +0,0 @@ -- The encryption format used for synchronization has changed incompatibly diff --git a/taskchampion/.changelogs/2021-10-25-issue23-integration.md b/taskchampion/.changelogs/2021-10-25-issue23-integration.md deleted file mode 100644 index d10a4d0ec..000000000 --- a/taskchampion/.changelogs/2021-10-25-issue23-integration.md +++ /dev/null @@ -1 +0,0 @@ -- The details of how task start/stop is represented have changed. Any existing tasks will all be treated as inactive (stopped). diff --git a/taskchampion/.gitignore b/taskchampion/.gitignore deleted file mode 100644 index 72429aeef..000000000 --- a/taskchampion/.gitignore +++ /dev/null @@ -1 +0,0 @@ -**/*.rs.bk diff --git a/taskchampion/CHANGELOG.md b/taskchampion/CHANGELOG.md deleted file mode 100644 index 91a692b5a..000000000 --- a/taskchampion/CHANGELOG.md +++ /dev/null @@ -1,26 +0,0 @@ -# Changelog - -## [Unreleased] - -Note: unreleased change log entries are kept in `.changelogs/` directory in repo root, and can be added with `./script/changelog.py add "Added thing for reason" - -## 0.4.1 - 2021-09-24 -- Fix for the build process to include the serde feature "derive". 0.4.0 could not be published to crates.io due to this bug. - -## 0.4.0 - 2021-09-25 -- Breaking: Removed the KV based storage backend in client and server, and replaced with SQLite ([Issue #131](https://github.com/taskchampion/taskchampion/issues/131), [PR #206](https://github.com/taskchampion/taskchampion/pull/206)) - -## 0.3.0 - 2021-01-11 -- Flexible named reports -- Updates to the TaskChampion crate API -- Usability improvements - -## 0.2.0 - 2020-11-30 - -This release is the first "MVP" version of this tool. It can do basic task operations, and supports a synchronization. Major missing features are captured in issues, but briefly: - - better command-line API, similar to TaskWarrior - authentication of the replica / server protocol - encryption of replica data before transmission to the server - lots of task features (tags, annotations, dependencies, ..) - lots of CLI features (filtering, modifying, ..) diff --git a/taskchampion/CODE_OF_CONDUCT.md b/taskchampion/CODE_OF_CONDUCT.md deleted file mode 100644 index 807def586..000000000 --- a/taskchampion/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,76 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at dustin@cs.uchicago.edu. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq diff --git a/taskchampion/CONTRIBUTING.md b/taskchampion/CONTRIBUTING.md deleted file mode 100644 index 7b44aad75..000000000 --- a/taskchampion/CONTRIBUTING.md +++ /dev/null @@ -1,62 +0,0 @@ -# Welcome - -This application is still in a pre-release state. -That means it's very open to contributions, and we'd love to have your help! - -It also means that things are changing quickly, and lots of stuff is planned that's not quite done yet. -If you would like to work on TaskChampion, please contact the developers (via the issue tracker) before spending a lot of time working on a pull request. -Doing so may save you some wasted time and frustration! - -A good starting point might be one of the issues tagged with ["good first issue"][first]. - -[first]: https://github.com/taskchampion/taskchampion/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 - -# Other Ways To Help - -The best way to help this project to grow is to help spread awareness of it. -Tell your friends, post to social media, blog about it -- whatever works best! - -Other ideas; - * Improve the documentation where it's unclear or lacking some information - * Build and maintain tools that integrate with TaskChampion - -# Development Guide - -TaskChampion is a typical Rust application. -To work on TaskChampion, you'll need to [install the latest version of Rust](https://www.rust-lang.org/tools/install). - -## Running Tests - -It's always a good idea to make sure tests run before you start hacking on a project. -Run `cargo test` from the top-level of this repository to run the tests. - -## Read the Source - -Aside from that, start reading the docs and the source to learn more! -The book documentation explains lots of the concepts in the design of TaskChampion. -It is linked from the README. - -There are three important crates in this repository. -You may be able to limit the scope of what you need to understand to just one crate. - * `taskchampion` is the core functionality of the application, implemented as a library - * `taskchampion-lib` implements a C API for `taskchampion`, used by Taskwarrior - * `integration-tests` contains some tests for integrations between multiple crates. - -You can generate the documentation for the `taskchampion` crate with `cargo doc --release --open -p taskchampion`. - -## Making a Pull Request - -We expect contributors to follow the [GitHub Flow](https://guides.github.com/introduction/flow/). -Aside from that, we have no particular requirements on pull requests. -Make your patch, double-check that it's complete (tests? docs? documentation comments?), and make a new pull request. - -Any non-trivial change (particularly those that change the behaviour of the application, or change the API) should be noted in the projects changelog. -In order to manage this, changelog entries are stored as text files in the `.changelog/` directory at the repository root. - -To add a new changelog entry, you can simply run `python3 ./script/changelog.py add "Fixed thingo to increase zorbloxification [Issue #2](http://example.com)` - -This creates a file named `./changelogs/yyyy-mm-dd-branchname.md` (timestamp, current git branch) which contains a markdown snippet. - -If you don't have a Python 3 intepreter installed, you can simply create this file manually. It should contain a list item like `- Fixed thingo [...]` - -Periodically (probably just before release), these changelog entries are concatenated combined together and added into the `CHANGELOG.md` file. diff --git a/taskchampion/LICENSE b/taskchampion/LICENSE deleted file mode 100644 index f0c9756e1..000000000 --- a/taskchampion/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Dustin J. Mitchell - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/taskchampion/POLICY.md b/taskchampion/POLICY.md deleted file mode 100644 index 3d84cbb82..000000000 --- a/taskchampion/POLICY.md +++ /dev/null @@ -1,45 +0,0 @@ -# Compatibility & deprecation - -Until TaskChampion reaches [v1.0.0](https://github.com/taskchampion/taskchampion/milestone/7), nothing is set in stone. That being said, we aim for the following: - -1. Major versions represent significant change and may be incompatible with previous major release. -2. Minor versions are always backwards compatible and might add some new functionality. -3. Patch versions should not introduce any new functionality and do what name implies — fix bugs. - -As there are no major releases yet, we do not support any older versions. Users are encouraged to use the latest release. - -## ABI policy - -1. We target stable `rustc`. -2. TaskChampion will never upgrade any storage to a non-compatible version without explicit user's request. - -## API policy - -1. Deprecated features return a warning at least 1 minor version prior to being removed. - - Example: - - > If support of `--bar` is to be dropped in v2.0.0, we shall announce it in v1.9.0 at latest. - -2. We aim to issue a notice of newly added functionality when appropriate. - - Example: - - > "NOTICE: Since v1.1.0 you can use `--foo` in conjunction with `--bar`. Foobar!" - -3. TaskChampion always uses UTF-8. - -## Command-line interface - -Considered to be part of the API policy. - -## CLI exit codes - -- `0` - No errors, normal exit. -- `1` - Generic error. -- `2` - Never used to avoid conflicts with Bash. -- `3` - Command-line Syntax Error. - -# Security - -See [SECURITY.md](./SECURITY.md). diff --git a/taskchampion/README.md b/taskchampion/README.md deleted file mode 100644 index ed7cfa77c..000000000 --- a/taskchampion/README.md +++ /dev/null @@ -1,50 +0,0 @@ -TaskChampion ------------- - -TaskChampion implements the task storage and synchronization behind Taskwarrior. -It includes an implementation with Rust and C APIs, allowing any application to maintain and manipulate its own replica. -It also includes a specification for tasks and how they are synchronized, inviting alternative implementations of replicas or task servers. - -See the [documentation](https://gothenburgbitfactory.github.io/taskwarrior/taskchampion/) for more! - -NOTE: Taskwarrior is currently in the midst of a change to use TaskChampion as its storage. -Until that is complete, the information here may be out-of-date. - -## Structure - -There are four crates here: - - * [taskchampion](./taskchampion) - the core of the tool - * [taskchampion-lib](./lib) - glue code to use _taskchampion_ from C - * [integration-tests](./integration-tests) (private) - integration tests covering _taskchampion_ and _taskchampion-lib_. - * [xtask](./xtask) (private) - implementation of the `cargo xtask codegen` command - -## Code Generation - -The _taskchampion_lib_ crate uses a bit of code generation to create the `lib/taskchampion.h` header file. -To regenerate this file, run `cargo xtask codegen`. - -## Rust API - -The Rust API, as defined in [the docs](https://docs.rs/taskchampion/latest/taskchampion/), supports simple creation and manipulation of replicas and the tasks they contain. - -The Rust API follows semantic versioning. -As this is still in the `0.x` phase, so breaking changes may occur but will be indicated with a change to the minor version. - -## C API - -The `taskchampion-lib` crate generates libraries suitable for use from C (or any C-compatible language). -It is a "normal" Cargo crate that happens to export a number of `extern "C"` symbols, and also contains a `taskchampion.h` defining those symbols. - -*WARNING: the C API is not yet stable!* - -It is your responsibility to link this into a form usable in your own build process. -For example, in a typical CMake C++ project, CMakeRust can do this for you. -In many cases, this is as simple as a rust crate with `src/lib.rs` containing - -```rust -pub use taskchampion_lib::*; -``` - -Arrange to use the header file, `lib/taskchampion.h`, by copying it or adding its directory to your include search path. -[Future work](https://github.com/GothenburgBitFactory/taskwarrior/issues/2870) will provide better automation for this process. diff --git a/taskchampion/RELEASING.md b/taskchampion/RELEASING.md deleted file mode 100644 index 78650fe0a..000000000 --- a/taskchampion/RELEASING.md +++ /dev/null @@ -1,16 +0,0 @@ -# Release process - -1. Ensure the changelog is updated with everything from the `.changelogs` directory. `python3 ./scripts/changelog.py build` will output a Markdown snippet to include in `CHANGELOG.md` then `rm .changelog/*.txt` -1. Run `git pull upstream main` -1. Run `cargo test` -1. Run `cargo clean && cargo clippy` -1. Run `mdbook test docs` -1. Update `version` in `*/Cargo.toml`. All versions should match. -1. Run `cargo build --release` -1. Commit the changes (Cargo.lock will change too) with comment `vX.Y.Z`. -1. Run `git tag vX.Y.Z` -1. Run `git push upstream` -1. Run `git push --tags upstream` -1. Run `(cd taskchampion; cargo publish)` (note that the other crates do not get published) -1. Navigate to the tag in the GitHub releases UI and create a release with general comments about the changes in the release -1. Upload `./target/release/task` and `./target/release/task-sync-server` to the release diff --git a/taskchampion/SECURITY.md b/taskchampion/SECURITY.md deleted file mode 100644 index 9d8d975d9..000000000 --- a/taskchampion/SECURITY.md +++ /dev/null @@ -1,11 +0,0 @@ -# Security - -To report a vulnerability, please contact [dustin@cs.uchicago.edu](dustin@cs.uchicago.edu), you may use GPG public-key `D8097934A92E4B4210368102FF8B7AC6154E3226` which is available [here](https://keybase.io/djmitche/pgp_keys.asc?fingerprint=d8097934a92e4b4210368102ff8b7ac6154e3226). Initial response is expected within ~48h. - -We kindly ask to follow the responsible disclosure model and refrain from sharing information until: -1. Vulnerabilities are patched in TaskChampion + 60 days to coordinate with distributions. -2. 90 days since the vulnerability is disclosed to us. - -We recognise the legitimacy of public interest and accept that security researchers can publish information after 90-days deadline unilaterally. - -We will assist with obtaining CVE and acknowledge the vulnerabilites reported. diff --git a/taskchampion/docs/.gitignore b/taskchampion/docs/.gitignore deleted file mode 100644 index d2479eb14..000000000 --- a/taskchampion/docs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -book -tmp diff --git a/taskchampion/docs/README.md b/taskchampion/docs/README.md deleted file mode 100644 index 7aaa35c16..000000000 --- a/taskchampion/docs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This is an [mdbook](https://rust-lang.github.io/mdBook/index.html) book. -Minor modifications can be made without installing the mdbook tool, as the content is simple Markdown. -Changes are verified on pull requests. diff --git a/taskchampion/docs/assets/cgi/LICENSE.md b/taskchampion/docs/assets/cgi/LICENSE.md deleted file mode 100644 index 1d4dbe059..000000000 --- a/taskchampion/docs/assets/cgi/LICENSE.md +++ /dev/null @@ -1,2 +0,0 @@ -Copyright (C) Andrew Savchenko - All Rights Reserved -All files within this folder are proprietary and reserved for the use by TaskChampion project. diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_1024.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_1024.png deleted file mode 100755 index d4a4a9e13..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_1024.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_128.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_128.png deleted file mode 100755 index c6f6ccf87..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_128.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_16.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_16.png deleted file mode 100755 index 225b311de..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_16.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_256.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_256.png deleted file mode 100755 index 9717c8d70..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_256.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_32.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_32.png deleted file mode 100755 index 2832f0b3a..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_32.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_512.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_512.png deleted file mode 100755 index 986236490..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_512.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_64.png b/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_64.png deleted file mode 100755 index 1c831acce..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_rounded/icon_rounded_64.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_1024.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_1024.png deleted file mode 100755 index 275f3b206..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_1024.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_128.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_128.png deleted file mode 100755 index 2600bae3b..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_128.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_16.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_16.png deleted file mode 100755 index e11979d52..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_16.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_256.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_256.png deleted file mode 100755 index 25cf7f694..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_256.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_32.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_32.png deleted file mode 100755 index 24e9a6097..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_32.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_512.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_512.png deleted file mode 100755 index da117347a..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_512.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/icon_square/icon_square_64.png b/taskchampion/docs/assets/cgi/icon_square/icon_square_64.png deleted file mode 100755 index d9d63e823..000000000 Binary files a/taskchampion/docs/assets/cgi/icon_square/icon_square_64.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_1024.png b/taskchampion/docs/assets/cgi/logo/logo_1024.png deleted file mode 100755 index 8f2cf7724..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_1024.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_128.png b/taskchampion/docs/assets/cgi/logo/logo_128.png deleted file mode 100755 index c32d2abe4..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_128.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_16.png b/taskchampion/docs/assets/cgi/logo/logo_16.png deleted file mode 100755 index 867dda789..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_16.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_256.png b/taskchampion/docs/assets/cgi/logo/logo_256.png deleted file mode 100755 index a01735a0d..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_256.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_32.png b/taskchampion/docs/assets/cgi/logo/logo_32.png deleted file mode 100755 index b180de372..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_32.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_512.png b/taskchampion/docs/assets/cgi/logo/logo_512.png deleted file mode 100755 index 2a2fb1502..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_512.png and /dev/null differ diff --git a/taskchampion/docs/assets/cgi/logo/logo_64.png b/taskchampion/docs/assets/cgi/logo/logo_64.png deleted file mode 100755 index 47e028add..000000000 Binary files a/taskchampion/docs/assets/cgi/logo/logo_64.png and /dev/null differ diff --git a/taskchampion/docs/book.toml b/taskchampion/docs/book.toml deleted file mode 100644 index 7e2fa9820..000000000 --- a/taskchampion/docs/book.toml +++ /dev/null @@ -1,9 +0,0 @@ -[book] -authors = ["Dustin J. Mitchell"] -language = "en" -multilingual = false -src = "src" -title = "TaskChampion" - -[output.html] -default-theme = "ayu" diff --git a/taskchampion/docs/src/SUMMARY.md b/taskchampion/docs/src/SUMMARY.md deleted file mode 100644 index b5bc3c6e5..000000000 --- a/taskchampion/docs/src/SUMMARY.md +++ /dev/null @@ -1,17 +0,0 @@ -# Summary - -- [Installation](./installation.md) - * [Running the Sync Server](./running-sync-server.md) -- [Internal Details](./internals.md) - * [Data Model](./data-model.md) - * [Replica Storage](./storage.md) - * [Task Database](./taskdb.md) - * [Tasks](./tasks.md) - * [Synchronization and the Sync Server](./sync.md) - * [Synchronization Model](./sync-model.md) - * [Snapshots](./snapshots.md) - * [Server-Replica Protocol](./sync-protocol.md) - * [Encryption](./encryption.md) - * [HTTP Implementation](./http.md) - * [Object-Store Implementation](./object-store.md) - * [Planned Functionality](./plans.md) diff --git a/taskchampion/docs/src/data-model.md b/taskchampion/docs/src/data-model.md deleted file mode 100644 index 2a43df62b..000000000 --- a/taskchampion/docs/src/data-model.md +++ /dev/null @@ -1,5 +0,0 @@ -# Data Model - -A client manages a single offline instance of a single user's task list, called a replica. -This section covers the structure of that data. -Note that this data model is visible only on the client; the server does not have access to client data. diff --git a/taskchampion/docs/src/encryption.md b/taskchampion/docs/src/encryption.md deleted file mode 100644 index 8a1e57a8f..000000000 --- a/taskchampion/docs/src/encryption.md +++ /dev/null @@ -1,38 +0,0 @@ -# Encryption - -The client configuration includes an encryption secret of arbitrary length. -This section describes how that information is used to encrypt and decrypt data sent to the server (versions and snapshots). - -Encryption is not used for local (on-disk) sync, but is used for all cases where data is sent from the local host. - -## Key Derivation - -The client derives the 32-byte encryption key from the configured encryption secret using PBKDF2 with HMAC-SHA256 and 600,000 iterations. -The salt value depends on the implementation of the protocol, as described in subsequent chapters. - -## Encryption - -The client uses [AEAD](https://commondatastorage.googleapis.com/chromium-boringssl-docs/aead.h.html), with algorithm CHACHA20_POLY1305. -The client should generate a random nonce, noting that AEAD is _not secure_ if a nonce is used repeatedly for the same key. - -AEAD supports additional authenticated data (AAD) which must be provided for both open and seal operations. -In this protocol, the AAD is always 17 bytes of the form: - * `app_id` (byte) - always 1 - * `version_id` (16 bytes) - 16-byte form of the version ID associated with this data - * for versions (AddVersion, GetChildVersion), the _parent_ version_id - * for snapshots (AddSnapshot, GetSnapshot), the snapshot version_id - -The `app_id` field is for future expansion to handle other, non-task data using this protocol. -Including it in the AAD ensures that such data cannot be confused with task data. - -Although the AEAD specification distinguishes ciphertext and tags, for purposes of this specification they are considered concatenated into a single bytestring as in BoringSSL's `EVP_AEAD_CTX_seal`. - -## Representation - -The final byte-stream is comprised of the following structure: - -* `version` (byte) - format version (always 1) -* `nonce` (12 bytes) - encryption nonce -* `ciphertext` (remaining bytes) - ciphertext from sealing operation - -The `version` field identifies this data format, and future formats will have a value other than 1 in this position. diff --git a/taskchampion/docs/src/http.md b/taskchampion/docs/src/http.md deleted file mode 100644 index 90b93753d..000000000 --- a/taskchampion/docs/src/http.md +++ /dev/null @@ -1,65 +0,0 @@ -# HTTP Representation - -The transactions in the sync protocol are realized for an HTTP server at `` using the HTTP requests and responses described here. -The `origin` *should* be an HTTPS endpoint on general principle, but nothing in the functonality or security of the protocol depends on connection encryption. - -The replica identifies itself to the server using a `client_id` in the form of a UUID. -This value is passed with every request in the `X-Client-Id` header, in its dashed-hex format. - -The salt used in key derivation is the 16-byte client ID. - -## AddVersion - -The request is a `POST` to `/v1/client/add-version/`. -The request body contains the history segment, optionally encoded using any encoding supported by actix-web. -The content-type must be `application/vnd.taskchampion.history-segment`. - -The success response is a 200 OK with an empty body. -The new version ID appears in the `X-Version-Id` header. -If included, a snapshot request appears in the `X-Snapshot-Request` header with value `urgency=low` or `urgency=high`. - -On conflict, the response is a 409 CONFLICT with an empty body. -The expected parent version ID appears in the `X-Parent-Version-Id` header. - -Other error responses (4xx or 5xx) may be returned and should be treated appropriately to their meanings in the HTTP specification. - -## GetChildVersion - -The request is a `GET` to `/v1/client/get-child-version/`. - -The response is determined as described above. -The _not-found_ response is 404 NOT FOUND. -The _gone_ response is 410 GONE. -Neither has a response body. - -On success, the response is a 200 OK. -The version's history segment is returned in the response body, with content-type `application/vnd.taskchampion.history-segment`. -The version ID appears in the `X-Version-Id` header. -The response body may be encoded, in accordance with any `Accept-Encoding` header in the request. - -On failure, a client should treat a 404 NOT FOUND as indicating that it is up-to-date. -Clients should treat a 410 GONE as a synchronization error. -If the client has pending changes to send to the server, based on a now-removed version, then those changes cannot be reconciled and will be lost. -The client should, optionally after consulting the user, download and apply the latest snapshot. - -## AddSnapshot - -The request is a `POST` to `/v1/client/add-snapshot/`. -The request body contains the snapshot data, optionally encoded using any encoding supported by actix-web. -The content-type must be `application/vnd.taskchampion.snapshot`. - -If the version is invalid, as described above, the response should be 400 BAD REQUEST. -The server response should be 200 OK on success. - -## GetSnapshot - -The request is a `GET` to `/v1/client/snapshot`. - -The response is a 200 OK. -The snapshot is returned in the response body, with content-type `application/vnd.taskchampion.snapshot`. -The version ID appears in the `X-Version-Id` header. -The response body may be encoded, in accordance with any `Accept-Encoding` header in the request. - -After downloading and decrypting a snapshot, a client must replace its entire local task database with the content of the snapshot. -Any local operations that had not yet been synchronized must be discarded. -After the snapshot is applied, the client should begin the synchronization process again, starting from the snapshot version. diff --git a/taskchampion/docs/src/images/name_timestamp.png b/taskchampion/docs/src/images/name_timestamp.png deleted file mode 100644 index d829039b7..000000000 Binary files a/taskchampion/docs/src/images/name_timestamp.png and /dev/null differ diff --git a/taskchampion/docs/src/installation.md b/taskchampion/docs/src/installation.md deleted file mode 100644 index a597a11da..000000000 --- a/taskchampion/docs/src/installation.md +++ /dev/null @@ -1,3 +0,0 @@ -# Installation - -As this is currently in development, installation is by cloning the repository and running "cargo build". diff --git a/taskchampion/docs/src/internals.md b/taskchampion/docs/src/internals.md deleted file mode 100644 index 7cc36ac29..000000000 --- a/taskchampion/docs/src/internals.md +++ /dev/null @@ -1,5 +0,0 @@ -# Internal Details - -The following sections get into the details of how TaskChampion works. -None of this information is necessary to use TaskChampion, but might be helpful in understanding its behavior. -Developers of TaskChampion and of tools that integrate with TaskChampion should be familiar with this information. diff --git a/taskchampion/docs/src/object-store.md b/taskchampion/docs/src/object-store.md deleted file mode 100644 index af6054ad3..000000000 --- a/taskchampion/docs/src/object-store.md +++ /dev/null @@ -1,9 +0,0 @@ -# Object Store Representation - -TaskChampion also supports use of a generic key-value store to synchronize replicas. - -In this case, the salt used in key derivation is a random 16-byte value, stored -in the object store and retrieved as needed. - -The details of the mapping from this protocol to keys and values are private to the implementation. -Other applications should not access the key-value store directly. diff --git a/taskchampion/docs/src/plans.md b/taskchampion/docs/src/plans.md deleted file mode 100644 index 4ee20c5d0..000000000 --- a/taskchampion/docs/src/plans.md +++ /dev/null @@ -1,35 +0,0 @@ -# Planned Functionality - -This section is a bit of a to-do list for additional functionality to add to the synchronzation system. -Each feature has some discussion of how it might be implemented. - -## Snapshots - -As designed, storage required on the server would grow with time, as would the time required for new clients to update to the latest version. -As an optimization, the server also stores "snapshots" containing a full copy of the task database at a given version. -Based on configurable heuristics, it may delete older operations and snapshots, as long as enough data remains for active clients to synchronize and for new clients to initialize. - -Since snapshots must be computed by clients, the server may "request" a snapshot when providing the latest version to a client. -This request comes with a number indicating how much it 'wants" the snapshot. -Clients which can easily generate and transmit a snapshot should be generous to the server, while clients with more limited resources can wait until the server's requests are more desperate. -The intent is, where possible, to request snapshots created on well-connected desktop clients over mobile and low-power clients. - -## Encryption and Signing - -From the server's perspective, all data except for version numbers are opaque binary blobs. -Clients encrypt and sign these blobs using a symmetric key known only to the clients. -This secures the data at-rest on the server. -Note that privacy is not complete, as the server still has some information about users, including source and frequency of synchronization transactions and size of those transactions. - -## Backups - -In this design, the server is little more than an authenticated storage for encrypted blobs provided by the client. -To allow for failure or data loss on the server, clients are expected to cache these blobs locally for a short time (a week), along with a server-provided HMAC signature. -When data loss is detected -- such as when a client expects the server to have a version N or higher, and the server only has N-1, the client can send those blobs to the server. -The server can validate the HMAC and, if successful, add the blobs to its datastore. - -## Expiration - -Deleted tasks remain in the task database, and are simply hidden in most views. -All tasks have an expiration time after which they may be flushed, preventing unbounded increase in task database size. -However, purging of a task does not satisfy the necessary OT guarantees, so some further formal design work is required before this is implemented. diff --git a/taskchampion/docs/src/running-sync-server.md b/taskchampion/docs/src/running-sync-server.md deleted file mode 100644 index e8b8c56ce..000000000 --- a/taskchampion/docs/src/running-sync-server.md +++ /dev/null @@ -1,11 +0,0 @@ -# Running the Sync Server - -> NOTE: TaskChampion is still in development and not yet feature-complete. -> The server is functional, but lacks any administrative features. - -Run `taskchampion-sync-server` to start the sync server. -Use `--port` to specify the port it should listen on, and `--data-dir` to specify the directory which it should store its data. -It only serves HTTP; the expectation is that a frontend proxy will be used for HTTPS support. - -The server has optional parameters `--snapshot-days` and `--snapshot-version`, giving the target number of days and versions, respectively, between snapshots of the client state. -The default values for these parameters are generally adequate. diff --git a/taskchampion/docs/src/snapshots.md b/taskchampion/docs/src/snapshots.md deleted file mode 100644 index 1ca134f34..000000000 --- a/taskchampion/docs/src/snapshots.md +++ /dev/null @@ -1,39 +0,0 @@ -# Snapshots - -The basic synchronization model described in the previous page has a few shortcomings: - * servers must store an ever-increasing quantity of versions - * a new replica must download all versions since the beginning (the nil UUID) in order to derive the current state - -Snapshots allow TaskChampion to avoid both of these issues. -A snapshot is a copy of the task database at a specific version. -It is created by a replica, encrypted, and stored on the server. -A new replica can simply download a recent snapshot and apply any additional versions synchronized since that snapshot was made. -Servers can delete and reclaim space used by older versions, as long as newer snapshots are available. - -## Snapshot Heuristics - -A server implementation must answer a few questions: - * How often should snapshots be made? - * When can versions be deleted? - * When can snapshots be deleted? - -A critical invariant is that at least one snapshot must exist for any database that does not have a child of the nil version. -This ensures that a new replica can always derive the latest state. - -Aside from that invariant, the server implementation can vary in its answers to these questions, with the following considerations: - -Snapshots should be made frequently enough that a new replica can initialize quickly. - -Existing replicas will fail to synchronize if they request a child version that has been deleted. -This failure can cause data loss if the replica had local changes. -It's conceivable that replicas may not sync for weeks or months if, for example, they are located on a home computer while the user is on holiday. - -## Requesting New Snapshots - -The server requests snapshots from replicas, indicating an urgency for the request. -Some replicas, such as those running on PCs or servers, can produce a snapshot even at low urgency. -Other replicas, in more restricted environments such as mobile devices, will only produce a snapshot at high urgency. -This saves resources in these restricted environments. - -A snapshot must be made on a replica with no unsynchronized operations. -As such, it only makes sense to request a snapshot in response to a successful AddVersion request. diff --git a/taskchampion/docs/src/storage.md b/taskchampion/docs/src/storage.md deleted file mode 100644 index f733f4f98..000000000 --- a/taskchampion/docs/src/storage.md +++ /dev/null @@ -1,83 +0,0 @@ -# Replica Storage - -Each replica has a storage backend. -The interface for this backend is given in `crate::taskstorage::Storage` and `StorageTxn`. - -The storage is transaction-protected, with the expectation of a serializable isolation level. -The storage contains the following information: - -- `tasks`: a set of tasks, indexed by UUID -- `base_version`: the number of the last version sync'd from the server (a single integer) -- `operations`: all operations performed since base_version -- `working_set`: a mapping from integer -> UUID, used to keep stable small-integer indexes into the tasks for users' convenience. This data is not synchronized with the server and does not affect any consistency guarantees. - -## Tasks - -The tasks are stored as an un-ordered collection, keyed by task UUID. -Each task in the database has represented by a key-value map. -See [Tasks](./tasks.md) for details on the content of that map. - -## Operations - -Every change to the task database is captured as an operation. -In other words, operations act as deltas between database states. -Operations are crucial to synchronization of replicas, described in [Synchronization Model](./sync-model.md). - -Operations are entirely managed by the replica, and some combinations of operations are described as "invalid" here. -A replica must not create invalid operations, but should be resilient to receiving invalid operations during a synchronization operation. - -Each operation has one of the forms - - * `Create(uuid)` - * `Delete(uuid, oldTask)` - * `Update(uuid, property, oldValue, newValue, timestamp)` - * `UndoPoint()` - -The Create form creates a new task. -It is invalid to create a task that already exists. - -Similarly, the Delete form deletes an existing task. -It is invalid to delete a task that does not exist. -The `oldTask` property contains the task data from before it was deleted. - -The Update form updates the given property of the given task, where the property and values are strings. -The `oldValue` gives the old value of the property (or None to create a new property), while `newValue` gives the new value (or None to delete a property). -It is invalid to update a task that does not exist. -The timestamp on updates serves as additional metadata and is used to resolve conflicts. - -### Application - -Each operation can be "applied" to a task database in a natural way: - - * Applying `Create` creates a new, empty task in the task database. - * Applying `Delete` deletes a task, including all of its properties, from the task database. - * Applying `Update` modifies the properties of a task. - * Applying `UndoPoint` does nothing. - -### Undo - -Each operation also contains enough information to reverse its application: - - * Undoing `Create` deletes a task. - * Undoing `Delete` creates a task, including all of the properties in `oldTask`. - * Undoing `Update` modifies the properties of a task, reverting to `oldValue`. - * Undoing `UndoPoint` does nothing. - -The `UndoPoint` operation serves as a marker of points in the operation sequence to which the user might wish to undo. -For example, creation of a new task with several properities involves several operations, but is a single step from the user's perspective. -An "undo" command reverses operations, removing them from the operations sequence, until it reaches an `UndoPoint` operation. - -### Synchronizing Operations - -After operations are synchronized to the server, they can no longer be undone. -As such, the [synchronization model](./sync-model.md) uses simpler operations. -Replica operations are converted to sync operations as follows: - - * `Create(uuid)` -> `Create(uuid)` (no change) - * `Delete(uuid, oldTask)` -> `Delete(uuid)` - * `Update(uuid, property, oldValue, newValue, timestamp)` -> `Update(uuid, property, newValue, timestamp)` - * `UndoPoint()` -> Ø (dropped from operation sequence) - -Once a sequence of operations has been synchronized, there is no need to store those operations on the replica. -The current implementation deletes operations at that time. -An alternative approach is to keep operations for existing tasks, and provide access to those operations as a "history" of modifications to the task. diff --git a/taskchampion/docs/src/sync-model.md b/taskchampion/docs/src/sync-model.md deleted file mode 100644 index f03626efb..000000000 --- a/taskchampion/docs/src/sync-model.md +++ /dev/null @@ -1,141 +0,0 @@ -# Synchronization Model - -The [task database](./taskdb.md) also implements synchronization. -Synchronization occurs between disconnected replicas, mediated by a server. -The replicas never communicate directly with one another. -The server does not have access to the task data; it sees only opaque blobs of data with a small amount of metadata. - -The synchronization process is a critical part of the task database's functionality, and it cannot function efficiently without occasional synchronization operations - -## Operational Transforms - -Synchronization is based on [operational transformation](https://en.wikipedia.org/wiki/Operational_transformation). -This section will assume some familiarity with the concept. - -## State and Operations - -At a given time, the set of tasks in a replica's storage is the essential "state" of that replica. -All modifications to that state occur via operations, as defined in [Replica Storage](./storage.md). -We can draw a network, or graph, with the nodes representing states and the edges representing operations. -For example: - -```text - o -- State: {abc-d123: 'get groceries', priority L} - | - | -- Operation: set abc-d123 priority to H - | - o -- State: {abc-d123: 'get groceries', priority H} -``` - -For those familiar with distributed version control systems, a state is analogous to a revision, while an operation is analogous to a commit. - -Fundamentally, synchronization involves all replicas agreeing on a single, linear sequence of operations and the state that those operations create. -Since the replicas are not connected, each may have additional operations that have been applied locally, but which have not yet been agreed on. -The synchronization process uses operational transformation to "linearize" those operations. - -This process is analogous (vaguely) to rebasing a sequence of Git commits. -Critically, though, operations cannot merge; in effect, the only option is rebasing. -Furthermore, once an operation has been sent to the server it cannot be changed; in effect, the server does not permit "force push". - -### Sync Operations - -The [Replica Storage](./storage.md) model contains additional information in its operations that is not included in operations synchronized to other replicas. -In this document, we will be discussing "sync operations" of the form - - * `Create(uuid)` - * `Delete(uuid)` - * `Update(uuid, property, value, timestamp)` - - -### Versions - -Occasionally, database states are given a name (that takes the form of a UUID). -The system as a whole (all replicas) constructs a branch-free sequence of versions and the operations that separate each version from the next. -The version with the nil UUID is implicitly the empty database. - -The server stores the operations to change a state from a "parent" version to a "child" version, and provides that information as needed to replicas. -Replicas use this information to update their local task databases, and to generate new versions to send to the server. - -Replicas generate a new version to transmit local changes to the server. -The changes are represented as a sequence of operations with the state resulting from the final operation corresponding to the version. -In order to keep the versions in a single sequence, the server will only accept a proposed version from a replica if its parent version matches the latest version on the server. - -In the non-conflict case (such as with a single replica), then, a replica's synchronization process involves gathering up the operations it has accumulated since its last synchronization; bundling those operations into a version; and sending that version to the server. - -### Replica Invariant - -The replica's [storage](./storage.md) contains the current state in `tasks`, the as-yet un-synchronized operations in `operations`, and the last version at which synchronization occurred in `base_version`. - -The replica's un-synchronized operations are already reflected in its local `tasks`, so the following invariant holds: - -> Applying `operations` to the set of tasks at `base_version` gives a set of tasks identical -> to `tasks`. - -### Transformation - -When the latest version on the server contains operations that are not present in the replica, then the states have diverged. -For example: - -```text - o -- version N - w|\a - o o - x| \b - o o - y| \c - o o -- replica's local state - z| - o -- version N+1 -``` - -(diagram notation: `o` designates a state, lower-case letters designate operations, and versions are presented as if they were numbered sequentially) - -In this situation, the replica must "rebase" the local operations onto the latest version from the server and try again. -This process is performed using operational transformation (OT). -The result of this transformation is a sequence of operations based on the latest version, and a sequence of operations the replica can apply to its local task database to reach the same state -Continuing the example above, the resulting operations are shown with `'`: - -```text - o -- version N - w|\a - o o - x| \b - o o - y| \c - o o -- replica's intermediate local state - z| |w' - o-N+1 o - a'\ |x' - o o - b'\ |y' - o o - c'\|z' - o -- version N+2 -``` - -The replica applies w' through z' locally, and sends a' through c' to the server as the operations to generate version N+2. -Either path through this graph, a-b-c-w'-x'-y'-z' or a'-b'-c'-w-x-y-z, must generate *precisely* the same final state at version N+2. -Careful selection of the operations and the transformation function ensure this. - -See the comments in the source code for the details of how this transformation process is implemented. - -## Synchronization Process - -To perform a synchronization, the replica first requests the child version of `base_version` from the server (GetChildVersion). -It applies that version to its local `tasks`, rebases its local `operations` as described above, and updates `base_version`. -The replica repeats this process until the server indicates no additional child versions exist. -If there are no un-synchronized local operations, the process is complete. - -Otherwise, the replica creates a new version containing its local operations, giving its `base_version` as the parent version, and transmits that to the server (AddVersion). -In most cases, this will succeed, but if another replica has created a new version in the interim, then the new version will conflict with that other replica's new version and the server will respond with the new expected parent version. -In this case, the process repeats. -If the server indicates a conflict twice with the same expected base version, that is an indication that the replica has diverged (something serious has gone wrong). - -## Servers - -A replica depends on periodic synchronization for performant operation. -Without synchronization, its list of pending operations would grow indefinitely, and tasks could never be expired. -So all replicas, even "singleton" replicas which do not replicate task data with any other replica, must synchronize periodically. - -TaskChampion provides a `LocalServer` for this purpose. -It implements the `get_child_version` and `add_version` operations as described, storing data on-disk locally. diff --git a/taskchampion/docs/src/sync-protocol.md b/taskchampion/docs/src/sync-protocol.md deleted file mode 100644 index 98caf24e3..000000000 --- a/taskchampion/docs/src/sync-protocol.md +++ /dev/null @@ -1,115 +0,0 @@ -# Server-Replica Protocol - -The server-replica protocol is defined abstractly in terms of request/response transactions. - -The protocol builds on the model presented in the previous chapters, and in particular on the synchronization process. - -## Clients - -From the protocol's perspective, replicas accessing the same task history are indistinguishable, so this protocol uses the term "client" to refer generically to all replicas replicating a single task history. - -## Server - -A server implements the requests and responses described below. -Where the logic is implemented depends on the specific implementation of the protocol. - -For each client, the server is responsible for storing the task history, in the form of a branch-free sequence of versions. -It also stores the latest snapshot, if any exists. -From the server's perspective, snapshots and versions are opaque byte sequences. - -## Version Invariant - -The following invariant must always hold: - -> All versions are linked by parent-child relationships to form a single chain. -> That is, each version must have no more than one parent and one child, and no more than one version may have zero parents or zero children. - -## Data Formats - -Task data sent to the server is encrypted by the client, using the scheme described in the "Encryption" chapter. - -### Version - -The decrypted form of a version is a JSON array containing operations in the order they should be applied. -Each operation has the form `{TYPE: DATA}`, for example: - - * `[{"Create":{"uuid":"56e0be07-c61f-494c-a54c-bdcfdd52d2a7"}}]` - * `[{"Delete":{"uuid":"56e0be07-c61f-494c-a54c-bdcfdd52d2a7"}}]` - * `[{"Update":{"uuid":"56e0be07-c61f-494c-a54c-bdcfdd52d2a7","property":"prop","value":"v","timestamp":"2021-10-11T12:47:07.188090948Z"}}]` - * `[{"Update":{"uuid":"56e0be07-c61f-494c-a54c-bdcfdd52d2a7","property":"prop","value":null,"timestamp":"2021-10-11T12:47:07.188090948Z"}}]` (to delete a property) - -Timestamps are in RFC3339 format with a `Z` suffix. - -### Snapshot - -The decrypted form of a snapshot is a JSON object mapping task IDs to task properties. -For example (pretty-printed for clarity): - -```json -{ - "56e0be07-c61f-494c-a54c-bdcfdd52d2a7": { - "description": "a task", - "priority": "H" - }, - "4b7ed904-f7b0-4293-8a10-ad452422c7b3": { - "description": "another task" - } -} -``` - -## Transactions - -All interactions between the client and server are defined in terms of request/response transactions, as described here. - -### AddVersion - -The AddVersion transaction requests that the server add a new version to the client's task history. -The request contains the following; - - * parent version ID, and - * encrypted version data. - -The server determines whether the new version is acceptable, atomically with respect to other requests for the same client. -If it has no versions for the client, it accepts the version. -If it already has one or more versions for the client, then it accepts the version only if the given parent version has no children, thereby maintaining the version invariant. - -If the version is accepted, the server generates a new version ID for it. -The version is added to the chain of versions for the client, and the new version ID is returned in the response to the client. -The response may also include a request for a snapshot, with associated urgency. - -If the version is not accepted, the server makes no changes, but responds to the client with a conflict indication containing the ID of the version which has no children. -The client may then "rebase" its operations and try again. -Note that if a client receives two conflict responses with the same parent version ID, it is an indication that the client's version history has diverged from that on the server. - -### GetChildVersion - -The GetChildVersion transaction is a read-only request for a version. -The request consists of a parent version ID. -The server searches its set of versions for a version with the given parent ID. -If found, it returns the version's - - * version ID, - * parent version ID (matching that in the request), and - * encrypted version data. - -If not found, it returns an indication that no such version exists. - -### AddSnapshot - -The AddSnapshot transaction requests that the server store a new snapshot, generated by the client. -The request contains the following: - - * version ID at which the snapshot was made, and - * encrypted snapshot data. - -The server may validate that the snapshot is for an existing version and is newer than any existing snapshot. -It may also validate that the snapshot is for a "recent" version (e.g., one of the last 5 versions). -If a snapshot already exists for the given version, the server may keep or discard the new snapshot but should return a success indication to the client. - -The server response is empty. - -### GetSnapshot - -The GetSnapshot transaction requests that the server provide the latest snapshot. -The response contains the snapshot version ID and the snapshot data, if those exist. - diff --git a/taskchampion/docs/src/sync.md b/taskchampion/docs/src/sync.md deleted file mode 100644 index fed75d17f..000000000 --- a/taskchampion/docs/src/sync.md +++ /dev/null @@ -1,7 +0,0 @@ -# Synchronization and the Sync Server - -This section covers *synchronization* of *replicas* containing the same set of tasks. -A replica is can perform all operations locally without connecting to a sync server, then share those operations with other replicas when it connects. -Sync is a critical feature of TaskChampion, allowing users to consult and update the same task list on multiple devices, without requiring constant connection. - -This is a complex topic, and the section is broken into several chapters, beginning at the lower levels of the implementation and working up. diff --git a/taskchampion/docs/src/taskdb.md b/taskchampion/docs/src/taskdb.md deleted file mode 100644 index b70e9bf3c..000000000 --- a/taskchampion/docs/src/taskdb.md +++ /dev/null @@ -1,32 +0,0 @@ -# Task Database - -The task database is a layer of abstraction above the replica storage layer, responsible for maintaining some important invariants. -While the storage is pluggable, there is only one implementation of the task database. - -## Reading Data - -The task database provides read access to the data in the replica's storage through a variety of methods on the struct. -Each read operation is executed in a transaction, so data may not be consistent between read operations. -In practice, this is not an issue for TaskChampion's purposes. - -## Working Set - -The task database maintains the working set. -The working set maps small integers to current tasks, for easy reference by command-line users. -This is done in such a way that the task numbers remain stable until the working set is rebuilt, at which point gaps in the numbering, such as for completed tasks, are removed by shifting all higher-numbered tasks downward. - -The working set is not replicated, and is not considered a part of any consistency guarantees in the task database. - -## Modifying Data - -Modifications to the data set are made by applying operations. -Operations are described in [Replica Storage](./storage.md). - -Each operation is added to the list of operations in the storage, and simultaneously applied to the tasks in that storage. -Operations are checked for validity as they are applied. - -## Deletion and Expiration - -Deletion of a task merely changes the task's status to "deleted", leaving it in the Task database. -Actual removal of tasks from the task database takes place as part of _expiration_, triggered by the user as part of a garbage-collection process. -Expiration removes tasks with a `modified` property more than 180 days in the past, by creating a `Delete(uuid)` operation. diff --git a/taskchampion/docs/src/tasks.md b/taskchampion/docs/src/tasks.md deleted file mode 100644 index bac90cc9d..000000000 --- a/taskchampion/docs/src/tasks.md +++ /dev/null @@ -1,58 +0,0 @@ -# Tasks - -Tasks are stored internally as a key/value map with string keys and values. -All fields are optional: the `Create` operation creates an empty task. -Display layers should apply appropriate defaults where necessary. - -## Atomicity - -The synchronization process does not support read-modify-write operations. -For example, suppose tags are updated by reading a list of tags, adding a tag, and writing the result back. -This would be captured as an `Update` operation containing the amended list of tags. -Suppose two such `Update` operations are made in different replicas and must be reconciled: - * `Update("d394be59-60e6-499e-b7e7-ca0142648409", "tags", "oldtag,newtag1", "2020-11-23T14:21:22Z")` - * `Update("d394be59-60e6-499e-b7e7-ca0142648409", "tags", "oldtag,newtag2", "2020-11-23T15:08:57Z")` - -The result of this reconciliation will be `oldtag,newtag2`, while the user almost certainly intended `oldtag,newtag1,newtag2`. - -The key names given below avoid this issue, allowing user updates such as adding a tag or deleting a dependency to be represented in a single `Update` operation. - -## Validity - -_Any_ key/value map is a valid task. -Consumers of task data must make a best effort to interpret any map, even if it contains apparently contradictory information. -For example, a task with status "completed" but no "end" key present should be interpreted as completed at an unknown time. - -## Representations - -Integers are stored in decimal notation. - -Timestamps are stored as UNIX epoch timestamps, in the form of an integer. - -## Keys - -The following keys, and key formats, are defined: - -* `status` - one of `P` for a pending task (the default), `C` for completed, `D` for deleted, or `R` for recurring -* `description` - the one-line summary of the task -* `modified` - the time of the last modification of this task -* `start` - the most recent time at which this task was started (a task with no `start` key is not active) -* `end` - if present, the time at which this task was completed or deleted (note that this key may not agree with `status`: it may be present for a pending task, or absent for a deleted or completed task) -* `tag_` - indicates this task has tag `` (value is ignored) -* `wait` - indicates the time before which this task should be hidden, as it is not actionable -* `entry` - the time at which the task was created -* `annotation_` - value is an annotation created at the given time; for example, `annotation_1693329505`. -* `dep_` - indicates this task depends on another task identified by ``; the value is ignored; for example, `dep_8c4fed9c-c0d2-40c2-936d-36fc44e084a0` - -Note that while TaskChampion recognizes "recurring" as a status, it does not implement recurrence directly. - -### UDAs - -Any unrecognized keys are treated as "user-defined attributes" (UDAs). -These attributes can be used to store additional data associated with a task. -For example, applications that synchronize tasks with other systems such as calendars or team planning services might store unique identifiers for those systems as UDAs. -The application defining a UDA defines the format of the value. - -UDAs _should_ have a namespaced structure of the form `.`, where `` identifies the application defining the UDA. -For example, a service named "DevSync" synchronizing tasks from GitHub might use UDAs like `devsync.github.issue-id`. -Note that many existing UDAs for Taskwarrior integrations do not follow this pattern; these are referred to as legacy UDAs. diff --git a/taskchampion/integration-tests/.gitignore b/taskchampion/integration-tests/.gitignore deleted file mode 100644 index 140a35ffe..000000000 --- a/taskchampion/integration-tests/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -test-db -test-sync-server diff --git a/taskchampion/integration-tests/Cargo.toml b/taskchampion/integration-tests/Cargo.toml deleted file mode 100644 index 217961394..000000000 --- a/taskchampion/integration-tests/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "integration-tests" -version = "0.4.1" -authors = ["Dustin J. Mitchell "] -edition = "2021" -publish = false -build = "build.rs" - -[dependencies] -taskchampion = { path = "../taskchampion" } -taskchampion-lib = { path = "../lib" } - -[dev-dependencies] -anyhow.workspace = true -tempfile.workspace = true -pretty_assertions.workspace = true -lazy_static.workspace = true - -[build-dependencies] -cc.workspace = true diff --git a/taskchampion/integration-tests/README.md b/taskchampion/integration-tests/README.md deleted file mode 100644 index 34a308aa5..000000000 --- a/taskchampion/integration-tests/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Integration Tests for TaskChampion - -## "Regular" Tests - -Some of the tests in `tests/` are just regular integration tests. -Nothing exciting to see. - -## Bindings Tests - -The bindings tests are a bit more interesting, since they are written in C. -They are composed of a collection of "suites", each in one C file in `integration-tests/src/bindings_tests/`. -Each suite contains a number of tests (using [Unity](http://www.throwtheswitch.org/unity)) and an exported function named after the suite that returns an exit status (1 = failure). - -The build script (`integration-tests/build.rs`) builds these files into a library that is linked with the `integration_tests` library crate. -This crate contains a `bindings_tests` module with a pub function for each suite. - -Finally, the `integration-tests/tests/bindings.rs` test file calls each of those functions in a separate test case. - -### Adding Tests - -To add a test, select a suite and add a new test-case function. -Add a `RUN_TEST` invocation for your new function to the `.._tests` function at the bottom. -Keep the `RUN_TEST`s in the same order as the functions they call. - -### Adding Suites - -To add a suite, - -1. Add a new C file in `integration-tests/src/bindings_tests/`, based off of one of the others. -1. Add a the suite name to `suites` in `integration-tests/build.rs`. diff --git a/taskchampion/integration-tests/build.rs b/taskchampion/integration-tests/build.rs deleted file mode 100644 index dd10a997c..000000000 --- a/taskchampion/integration-tests/build.rs +++ /dev/null @@ -1,51 +0,0 @@ -use std::env; -use std::fs; -use std::path::Path; - -/// Build the Unity-based C test suite in `src/bindings_tests`, linking the result with this -/// package's library crate. -fn build_bindings_tests(suites: &[&'static str]) { - let mut build = cc::Build::new(); - build.include("../lib"); // include path for taskchampion.h - build.include("src/bindings_tests/unity"); - build.define("UNITY_OUTPUT_CHAR", "test_output"); - build.define( - "UNITY_OUTPUT_CHAR_HEADER_DECLARATION", - "test_output(char c)", - ); - - let mut files = vec![ - "src/bindings_tests/test.c".into(), - "src/bindings_tests/unity/unity.c".into(), - ]; - for suite in suites { - files.push(format!("src/bindings_tests/{}.c", suite)); - } - for file in files { - build.file(&file); - println!("cargo:rerun-if-changed={}", file); - } - println!("cargo:rerun-if-changed=../lib/taskchampion.h"); - - build.compile("bindings-tests"); -} - -/// Make `bindings_test_suites.rs` listing all of the test suites, for use in building the -/// bindings-test binary. -fn make_suite_file(suites: &[&'static str]) { - let out_dir = env::var_os("OUT_DIR").unwrap(); - let dest_path = Path::new(&out_dir).join("bindings_test_suites.rs"); - let mut content = String::new(); - for suite in suites { - content.push_str(format!("suite!({}_tests);\n", suite).as_ref()); - } - fs::write(dest_path, content).unwrap(); -} - -fn main() { - println!("cargo:rerun-if-changed=build.rs"); - - let suites = &["uuid", "string", "task", "replica"]; - build_bindings_tests(suites); - make_suite_file(suites); -} diff --git a/taskchampion/integration-tests/src/bindings_tests/mod.rs b/taskchampion/integration-tests/src/bindings_tests/mod.rs deleted file mode 100644 index 327ca83fe..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::fs; - -extern "C" { - // set up to send test output to TEST-OUTPUT - fn setup_output(); - // close the output file - fn finish_output(); -} - -// Each suite is represented by a _tests C function in .c. -// All of these C files are built into a library that is linked to the crate -- but not to test -// crates. So, this macro produces a "glue function" that calls the C function, and that can be -// called from test crates. -macro_rules! suite( - { $s:ident } => { - pub fn $s() -> (i32, String) { - extern "C" { - fn $s() -> i32; - } - unsafe { setup_output() }; - let res = unsafe { $s() }; - unsafe { finish_output() }; - let output = fs::read_to_string("TEST-OUTPUT") - .unwrap_or_else(|e| format!("could not open TEST-OUTPUT: {}", e)); - (res, output) - } - }; -); - -include!(concat!(env!("OUT_DIR"), "/bindings_test_suites.rs")); diff --git a/taskchampion/integration-tests/src/bindings_tests/replica.c b/taskchampion/integration-tests/src/bindings_tests/replica.c deleted file mode 100644 index 0126791ff..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/replica.c +++ /dev/null @@ -1,330 +0,0 @@ -#include -#include -#include -#include "taskchampion.h" -#include "unity.h" - -// creating an in-memory replica does not crash -static void test_replica_creation(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NOT_NULL(rep); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - tc_replica_free(rep); -} - -// creating an on-disk replica does not crash -static void test_replica_creation_disk(void) { - TCReplica *rep = tc_replica_new_on_disk(tc_string_borrow("test-db"), true, NULL); - TEST_ASSERT_NOT_NULL(rep); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - tc_replica_free(rep); -} - -// undo on an empty in-memory TCReplica does nothing -static void test_replica_undo_empty(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - int undone; - TCReplicaOpList undo_ops = tc_replica_get_undo_ops(rep); - int rv = tc_replica_commit_undo_ops(rep, undo_ops, &undone); - TEST_ASSERT_EQUAL(TC_RESULT_OK, rv); - TEST_ASSERT_EQUAL(0, undone); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - tc_replica_free(rep); -} - -// adding an undo point succeeds -static void test_replica_add_undo_point(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_replica_add_undo_point(rep, true)); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - tc_replica_free(rep); -} - -// working set operations succeed -static void test_replica_working_set(void) { - TCWorkingSet *ws; - TCTask *task1, *task2, *task3; - TCUuid uuid, uuid1, uuid2, uuid3; - - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_replica_rebuild_working_set(rep, true)); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - ws = tc_replica_working_set(rep); - TEST_ASSERT_EQUAL(0, tc_working_set_len(ws)); - tc_working_set_free(ws); - - task1 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("task1")); - TEST_ASSERT_NOT_NULL(task1); - uuid1 = tc_task_get_uuid(task1); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_replica_rebuild_working_set(rep, true)); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - task2 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("task2")); - TEST_ASSERT_NOT_NULL(task2); - uuid2 = tc_task_get_uuid(task2); - - task3 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("task3")); - TEST_ASSERT_NOT_NULL(task3); - uuid3 = tc_task_get_uuid(task3); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_replica_rebuild_working_set(rep, false)); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - // finish task2 to leave a "hole" - tc_task_to_mut(task2, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_done(task2)); - tc_task_to_immut(task2); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_replica_rebuild_working_set(rep, false)); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - tc_task_free(task1); - tc_task_free(task2); - tc_task_free(task3); - - // working set should now be - // 0 -> None - // 1 -> uuid1 - // 2 -> None - // 3 -> uuid3 - ws = tc_replica_working_set(rep); - TEST_ASSERT_EQUAL(2, tc_working_set_len(ws)); - TEST_ASSERT_EQUAL(3, tc_working_set_largest_index(ws)); - - TEST_ASSERT_FALSE(tc_working_set_by_index(ws, 0, &uuid)); - TEST_ASSERT_TRUE(tc_working_set_by_index(ws, 1, &uuid)); - TEST_ASSERT_EQUAL_MEMORY(uuid1.bytes, uuid.bytes, sizeof(uuid)); - TEST_ASSERT_FALSE(tc_working_set_by_index(ws, 2, &uuid)); - TEST_ASSERT_TRUE(tc_working_set_by_index(ws, 3, &uuid)); - TEST_ASSERT_EQUAL_MEMORY(uuid3.bytes, uuid.bytes, sizeof(uuid)); - - TEST_ASSERT_EQUAL(1, tc_working_set_by_uuid(ws, uuid1)); - TEST_ASSERT_EQUAL(0, tc_working_set_by_uuid(ws, uuid2)); - TEST_ASSERT_EQUAL(3, tc_working_set_by_uuid(ws, uuid3)); - - tc_working_set_free(ws); - - TEST_ASSERT_EQUAL(18, tc_replica_num_local_operations(rep)); - - tc_replica_free(rep); -} - -// When tc_replica_commit_undo_ops is passed NULL for undone_out, it still succeeds -static void test_replica_undo_empty_null_undone_out(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - TCReplicaOpList undo_ops = tc_replica_get_undo_ops(rep); - int rv = tc_replica_commit_undo_ops(rep, undo_ops, NULL); - TEST_ASSERT_EQUAL(TC_RESULT_OK, rv); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - tc_replica_free(rep); -} - -// creating a task succeeds and the resulting task looks good -static void test_replica_task_creation(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TCUuid uuid = tc_task_get_uuid(task); - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - TCString desc = tc_task_get_description(task); - TEST_ASSERT_NOT_NULL(desc.ptr); - TEST_ASSERT_EQUAL_STRING("my task", tc_string_content(&desc)); - tc_string_free(&desc); - - tc_task_free(task); - - // get the task again and verify it - task = tc_replica_get_task(rep, uuid); - TEST_ASSERT_NOT_NULL(task); - TEST_ASSERT_EQUAL_MEMORY(uuid.bytes, tc_task_get_uuid(task).bytes, sizeof(uuid.bytes)); - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - tc_task_free(task); - - tc_replica_free(rep); -} - -static void test_replica_sync_local(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - mkdir("test-sync-server", 0755); // ignore error, if dir already exists - - TCString err; - TCServer *server = tc_server_new_local(tc_string_borrow("test-sync-server"), &err); - TEST_ASSERT_NOT_NULL(server); - TEST_ASSERT_NULL(err.ptr); - - int rv = tc_replica_sync(rep, server, false); - TEST_ASSERT_EQUAL(TC_RESULT_OK, rv); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - tc_server_free(server); - tc_replica_free(rep); - - // test error handling - server = tc_server_new_local(tc_string_borrow("/no/such/directory"), &err); - TEST_ASSERT_NULL(server); - TEST_ASSERT_NOT_NULL(err.ptr); - tc_string_free(&err); -} - -static void test_replica_remote_server(void) { - TCString err; - TCServer *server = tc_server_new_sync( - tc_string_borrow("http://tc.freecinc.com"), - tc_uuid_new_v4(), - tc_string_borrow("\xf0\x28\x8c\x28"), // NOTE: not utf-8 - &err); - TEST_ASSERT_NOT_NULL(server); - TEST_ASSERT_NULL(err.ptr); - - // can't actually do anything with this server! - - tc_server_free(server); -} - -// a replica with tasks in it returns an appropriate list of tasks and list of uuids -static void test_replica_all_tasks(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task1 = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("task1")); - TEST_ASSERT_NOT_NULL(task1); - TCUuid uuid1 = tc_task_get_uuid(task1); - tc_task_free(task1); - - TCTask *task2 = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("task2")); - TEST_ASSERT_NOT_NULL(task2); - TCUuid uuid2 = tc_task_get_uuid(task2); - tc_task_free(task2); - - { - TCTaskList tasks = tc_replica_all_tasks(rep); - TEST_ASSERT_NOT_NULL(tasks.items); - TEST_ASSERT_EQUAL(2, tasks.len); - - bool seen1, seen2 = false; - for (size_t i = 0; i < tasks.len; i++) { - TCTask *task = tasks.items[i]; - TCString descr = tc_task_get_description(task); - if (0 == strcmp(tc_string_content(&descr), "task1")) { - seen1 = true; - } else if (0 == strcmp(tc_string_content(&descr), "task2")) { - seen2 = true; - } - tc_string_free(&descr); - } - TEST_ASSERT_TRUE(seen1); - TEST_ASSERT_TRUE(seen2); - - tc_task_list_free(&tasks); - TEST_ASSERT_NULL(tasks.items); - } - - { - TCUuidList uuids = tc_replica_all_task_uuids(rep); - TEST_ASSERT_NOT_NULL(uuids.items); - TEST_ASSERT_EQUAL(2, uuids.len); - - bool seen1, seen2 = false; - for (size_t i = 0; i < uuids.len; i++) { - TCUuid uuid = uuids.items[i]; - if (0 == memcmp(&uuid1, &uuid, sizeof(TCUuid))) { - seen1 = true; - } else if (0 == memcmp(&uuid2, &uuid, sizeof(TCUuid))) { - seen2 = true; - } - } - TEST_ASSERT_TRUE(seen1); - TEST_ASSERT_TRUE(seen2); - - tc_uuid_list_free(&uuids); - TEST_ASSERT_NULL(uuids.items); - } - - tc_replica_free(rep); -} - -// importing a task succeeds and the resulting task looks good -static void test_replica_task_import(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCUuid uuid; - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_uuid_from_str(tc_string_borrow("23cb25e0-5d1a-4932-8131-594ac6d3a843"), &uuid)); - TCTask *task = tc_replica_import_task_with_uuid(rep, uuid); - TEST_ASSERT_NOT_NULL(task); - - TEST_ASSERT_EQUAL_MEMORY(uuid.bytes, tc_task_get_uuid(task).bytes, sizeof(uuid.bytes)); - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - TCString desc = tc_task_get_description(task); - TEST_ASSERT_NOT_NULL(desc.ptr); - TEST_ASSERT_EQUAL_STRING("", tc_string_content(&desc)); // default value - tc_string_free(&desc); - - tc_task_free(task); - - // get the task again and verify it - task = tc_replica_get_task(rep, uuid); - TEST_ASSERT_NOT_NULL(task); - TEST_ASSERT_EQUAL_MEMORY(uuid.bytes, tc_task_get_uuid(task).bytes, sizeof(uuid.bytes)); - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// importing a task succeeds and the resulting task looks good -static void test_replica_get_task_not_found(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCUuid uuid; - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_uuid_from_str(tc_string_borrow("23cb25e0-5d1a-4932-8131-594ac6d3a843"), &uuid)); - TCTask *task = tc_replica_get_task(rep, uuid); - TEST_ASSERT_NULL(task); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - tc_replica_free(rep); -} - -int replica_tests(void) { - UNITY_BEGIN(); - // each test case above should be named here, in order. - RUN_TEST(test_replica_creation); - RUN_TEST(test_replica_creation_disk); - RUN_TEST(test_replica_undo_empty); - RUN_TEST(test_replica_add_undo_point); - RUN_TEST(test_replica_working_set); - RUN_TEST(test_replica_undo_empty_null_undone_out); - RUN_TEST(test_replica_task_creation); - RUN_TEST(test_replica_sync_local); - RUN_TEST(test_replica_remote_server); - RUN_TEST(test_replica_all_tasks); - RUN_TEST(test_replica_task_import); - RUN_TEST(test_replica_get_task_not_found); - return UNITY_END(); -} diff --git a/taskchampion/integration-tests/src/bindings_tests/string.c b/taskchampion/integration-tests/src/bindings_tests/string.c deleted file mode 100644 index 2bd2749c0..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/string.c +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include "unity.h" -#include "taskchampion.h" - -// creating strings does not crash -static void test_string_creation(void) { - TCString s = tc_string_borrow("abcdef"); - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// creating cloned strings does not crash -static void test_string_cloning(void) { - char *abcdef = strdup("abcdef"); - TCString s = tc_string_clone(abcdef); - TEST_ASSERT_NOT_NULL(s.ptr); - free(abcdef); - - TEST_ASSERT_EQUAL_STRING("abcdef", tc_string_content(&s)); - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// creating cloned strings with invalid utf-8 does not crash -// ..but content is NULL and content_and_len returns the value -static void test_string_cloning_invalid_utf8(void) { - TCString s = tc_string_clone("\xf0\x28\x8c\x28"); - TEST_ASSERT_NOT_NULL(s.ptr); - - // NOTE: this is not one of the cases where invalid UTF-8 results in NULL, - // but that may change. - - size_t len; - const char *buf = tc_string_content_with_len(&s, &len); - TEST_ASSERT_NOT_NULL(buf); - TEST_ASSERT_EQUAL(4, len); - TEST_ASSERT_EQUAL_MEMORY("\xf0\x28\x8c\x28", buf, len); - - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// borrowed strings echo back their content -static void test_string_borrowed_strings_echo(void) { - TCString s = tc_string_borrow("abcdef"); - TEST_ASSERT_NOT_NULL(s.ptr); - - TEST_ASSERT_EQUAL_STRING("abcdef", tc_string_content(&s)); - - size_t len; - const char *buf = tc_string_content_with_len(&s, &len); - TEST_ASSERT_NOT_NULL(buf); - TEST_ASSERT_EQUAL(6, len); - TEST_ASSERT_EQUAL_MEMORY("abcdef", buf, len); - - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// cloned strings echo back their content -static void test_string_cloned_strings_echo(void) { - char *orig = strdup("abcdef"); - TCString s = tc_string_clone(orig); - TEST_ASSERT_NOT_NULL(s.ptr); - free(orig); - - TEST_ASSERT_EQUAL_STRING("abcdef", tc_string_content(&s)); - - size_t len; - const char *buf = tc_string_content_with_len(&s, &len); - TEST_ASSERT_NOT_NULL(buf); - TEST_ASSERT_EQUAL(6, len); - TEST_ASSERT_EQUAL_MEMORY("abcdef", buf, len); - - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// tc_clone_with_len can have NULs, and tc_string_content returns NULL for -// strings containing embedded NULs -static void test_string_content_null_for_embedded_nuls(void) { - TCString s = tc_string_clone_with_len("ab\0de", 5); - TEST_ASSERT_NOT_NULL(s.ptr); - - TEST_ASSERT_NULL(tc_string_content(&s)); - - size_t len; - const char *buf = tc_string_content_with_len(&s, &len); - TEST_ASSERT_NOT_NULL(buf); - TEST_ASSERT_EQUAL(5, len); - TEST_ASSERT_EQUAL_MEMORY("ab\0de", buf, len); - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -// tc_string_clone_with_len will accept invalid utf-8, but then tc_string_content -// returns NULL. -static void test_string_clone_with_len_invalid_utf8(void) { - TCString s = tc_string_clone_with_len("\xf0\x28\x8c\x28", 4); - TEST_ASSERT_NOT_NULL(s.ptr); - - TEST_ASSERT_NULL(tc_string_content(&s)); - - size_t len; - const char *buf = tc_string_content_with_len(&s, &len); - TEST_ASSERT_NOT_NULL(buf); - TEST_ASSERT_EQUAL(4, len); - TEST_ASSERT_EQUAL_MEMORY("\xf0\x28\x8c\x28", buf, len); - tc_string_free(&s); - TEST_ASSERT_NULL(s.ptr); -} - -int string_tests(void) { - UNITY_BEGIN(); - // each test case above should be named here, in order. - RUN_TEST(test_string_creation); - RUN_TEST(test_string_cloning); - RUN_TEST(test_string_cloning_invalid_utf8); - RUN_TEST(test_string_borrowed_strings_echo); - RUN_TEST(test_string_cloned_strings_echo); - RUN_TEST(test_string_content_null_for_embedded_nuls); - RUN_TEST(test_string_clone_with_len_invalid_utf8); - return UNITY_END(); -} diff --git a/taskchampion/integration-tests/src/bindings_tests/task.c b/taskchampion/integration-tests/src/bindings_tests/task.c deleted file mode 100644 index 828775468..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/task.c +++ /dev/null @@ -1,717 +0,0 @@ -#include -#include -#include "unity.h" -#include "taskchampion.h" - -// creating a task succeeds and the resulting task looks good -static void test_task_creation(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - TCString desc = tc_task_get_description(task); - TEST_ASSERT_NOT_NULL(desc.ptr); - TEST_ASSERT_EQUAL_STRING("my task", tc_string_content(&desc)); - tc_string_free(&desc); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// freeing a mutable task works, marking it immutable -static void test_task_free_mutable_task(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - TCUuid uuid = tc_task_get_uuid(task); - - tc_task_to_mut(task, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_status(task, TC_STATUS_DELETED)); - TEST_ASSERT_EQUAL(TC_STATUS_DELETED, tc_task_get_status(task)); - - tc_task_free(task); // implicitly converts to immut - - task = tc_replica_get_task(rep, uuid); - TEST_ASSERT_NOT_NULL(task); - TEST_ASSERT_EQUAL(TC_STATUS_DELETED, tc_task_get_status(task)); - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating status on a task works -static void test_task_get_set_status(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - - tc_task_to_mut(task, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_status(task, TC_STATUS_DELETED)); - TEST_ASSERT_EQUAL(TC_STATUS_DELETED, tc_task_get_status(task)); // while mut - tc_task_to_immut(task); - TEST_ASSERT_EQUAL(TC_STATUS_DELETED, tc_task_get_status(task)); // while immut - - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating description on a task works -static void test_task_get_set_description(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TCString desc; - - tc_task_to_mut(task, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_description(task, tc_string_borrow("updated"))); - - desc = tc_task_get_description(task); - TEST_ASSERT_NOT_NULL(desc.ptr); - TEST_ASSERT_EQUAL_STRING("updated", tc_string_content(&desc)); - tc_string_free(&desc); - - tc_task_to_immut(task); - - desc = tc_task_get_description(task); - TEST_ASSERT_NOT_NULL(desc.ptr); - TEST_ASSERT_EQUAL_STRING("updated", tc_string_content(&desc)); - tc_string_free(&desc); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating arbitrary attributes on a task works -static void test_task_get_set_attribute(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TCString foo; - - foo = tc_task_get_value(task, tc_string_borrow("foo")); - TEST_ASSERT_NULL(foo.ptr); - - tc_task_to_mut(task, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_value(task, - tc_string_borrow("foo"), - tc_string_borrow("updated"))); - - foo = tc_task_get_value(task, tc_string_borrow("foo")); - TEST_ASSERT_NOT_NULL(foo.ptr); - TEST_ASSERT_EQUAL_STRING("updated", tc_string_content(&foo)); - tc_string_free(&foo); - - tc_task_to_immut(task); - - foo = tc_task_get_value(task, tc_string_borrow("foo")); - TEST_ASSERT_NOT_NULL(foo.ptr); - TEST_ASSERT_EQUAL_STRING("updated", tc_string_content(&foo)); - tc_string_free(&foo); - - TCString null = { .ptr = NULL }; - - tc_task_to_mut(task, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_value(task, - tc_string_borrow("foo"), - null)); - - foo = tc_task_get_value(task, tc_string_borrow("foo")); - TEST_ASSERT_NULL(foo.ptr); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating entry on a task works -static void test_task_get_set_entry(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - // creation of a task sets entry to current time - TEST_ASSERT_NOT_EQUAL(0, tc_task_get_entry(task)); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_entry(task, 1643679997)); - TEST_ASSERT_EQUAL(1643679997, tc_task_get_entry(task)); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_entry(task, 0)); - TEST_ASSERT_EQUAL(0, tc_task_get_entry(task)); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating wait on a task works -static void test_task_get_set_wait_and_is_waiting(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - // wait is not set on creation - TEST_ASSERT_EQUAL(0, tc_task_get_wait(task)); - TEST_ASSERT_FALSE(tc_task_is_waiting(task)); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_wait(task, 3643679997)); // 2085 - TEST_ASSERT_EQUAL(3643679997, tc_task_get_wait(task)); - TEST_ASSERT_TRUE(tc_task_is_waiting(task)); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_wait(task, 643679997)); // THE PAST! - TEST_ASSERT_EQUAL(643679997, tc_task_get_wait(task)); - TEST_ASSERT_FALSE(tc_task_is_waiting(task)); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_wait(task, 0)); - TEST_ASSERT_EQUAL(0, tc_task_get_wait(task)); - TEST_ASSERT_FALSE(tc_task_is_waiting(task)); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// updating modified on a task works -static void test_task_get_set_modified(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - // creation of a task sets modified to current time - TEST_ASSERT_NOT_EQUAL(0, tc_task_get_modified(task)); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_modified(task, 1643679997)); - TEST_ASSERT_EQUAL(1643679997, tc_task_get_modified(task)); - - // zero is not allowed - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_task_set_modified(task, 0)); - - tc_task_free(task); - - tc_replica_free(rep); -} - -// starting and stopping a task works, as seen by tc_task_is_active -static void test_task_start_stop_is_active(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TEST_ASSERT_FALSE(tc_task_is_active(task)); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_FALSE(tc_task_is_active(task)); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_start(task)); - TEST_ASSERT_TRUE(tc_task_is_active(task)); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_stop(task)); - TEST_ASSERT_FALSE(tc_task_is_active(task)); - - tc_task_free(task); - tc_replica_free(rep); -} - -// tc_task_done and delete work and set the status -static void test_task_done_and_delete(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_STATUS_PENDING, tc_task_get_status(task)); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_done(task)); - TEST_ASSERT_EQUAL(TC_STATUS_COMPLETED, tc_task_get_status(task)); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_delete(task)); - TEST_ASSERT_EQUAL(TC_STATUS_DELETED, tc_task_get_status(task)); - - tc_task_free(task); - tc_replica_free(rep); -} - -// adding and removing tags to a task works, and invalid tags are rejected -static void test_task_add_remove_has_tag(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_FALSE(tc_task_has_tag(task, tc_string_borrow("next"))); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_tag(task, tc_string_borrow("next"))); - TEST_ASSERT_NULL(tc_task_error(task).ptr); - - TEST_ASSERT_TRUE(tc_task_has_tag(task, tc_string_borrow("next"))); - - // invalid - synthetic tag - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_task_add_tag(task, tc_string_borrow("PENDING"))); - TCString err = tc_task_error(task); - TEST_ASSERT_NOT_NULL(err.ptr); - tc_string_free(&err); - - // invald - not a valid tag string - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_task_add_tag(task, tc_string_borrow("my tag"))); - err = tc_task_error(task); - TEST_ASSERT_NOT_NULL(err.ptr); - tc_string_free(&err); - - // invald - not utf-8 - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_task_add_tag(task, tc_string_borrow("\xf0\x28\x8c\x28"))); - err = tc_task_error(task); - TEST_ASSERT_NOT_NULL(err.ptr); - tc_string_free(&err); - - TEST_ASSERT_TRUE(tc_task_has_tag(task, tc_string_borrow("next"))); - - // remove the tag - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_remove_tag(task, tc_string_borrow("next"))); - TEST_ASSERT_NULL(tc_task_error(task).ptr); - - TEST_ASSERT_FALSE(tc_task_has_tag(task, tc_string_borrow("next"))); - - tc_task_free(task); - tc_replica_free(rep); -} - -// get_tags returns the list of tags -static void test_task_get_tags(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_tag(task, tc_string_borrow("next"))); - - TCStringList tags = tc_task_get_tags(task); - - int found_pending = false, found_next = false; - for (size_t i = 0; i < tags.len; i++) { - if (strcmp("PENDING", tc_string_content(&tags.items[i])) == 0) { - found_pending = true; - } - if (strcmp("next", tc_string_content(&tags.items[i])) == 0) { - found_next = true; - } - } - TEST_ASSERT_TRUE(found_pending); - TEST_ASSERT_TRUE(found_next); - - tc_string_list_free(&tags); - TEST_ASSERT_NULL(tags.items); - - tc_task_free(task); - tc_replica_free(rep); -} - -// annotation manipulation (add, remove, list, free) -static void test_task_annotations(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - TCAnnotationList anns = tc_task_get_annotations(task); - TEST_ASSERT_EQUAL(0, anns.len); - TEST_ASSERT_NOT_NULL(anns.items); - tc_annotation_list_free(&anns); - - tc_task_to_mut(task, rep); - - TCAnnotation ann; - - ann.entry = 1644623411; - ann.description = tc_string_borrow("ann1"); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_annotation(task, &ann)); - TEST_ASSERT_NULL(ann.description.ptr); - - ann.entry = 1644623422; - ann.description = tc_string_borrow("ann2"); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_annotation(task, &ann)); - TEST_ASSERT_NULL(ann.description.ptr); - - anns = tc_task_get_annotations(task); - - int found1 = false, found2 = false; - for (size_t i = 0; i < anns.len; i++) { - if (0 == strcmp("ann1", tc_string_content(&anns.items[i].description))) { - TEST_ASSERT_EQUAL(anns.items[i].entry, 1644623411); - found1 = true; - } - if (0 == strcmp("ann2", tc_string_content(&anns.items[i].description))) { - TEST_ASSERT_EQUAL(anns.items[i].entry, 1644623422); - found2 = true; - } - } - TEST_ASSERT_TRUE(found1); - TEST_ASSERT_TRUE(found2); - - tc_annotation_list_free(&anns); - TEST_ASSERT_NULL(anns.items); - - tc_task_free(task); - tc_replica_free(rep); -} - -// UDA manipulation (add, remove, list, free) -static void test_task_udas(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task( - rep, - TC_STATUS_PENDING, - tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - tc_task_to_mut(task, rep); - - TCString value; - TCUdaList udas; - - TEST_ASSERT_NULL(tc_task_get_uda(task, tc_string_borrow("ns"), tc_string_borrow("u1")).ptr); - TEST_ASSERT_NULL(tc_task_get_legacy_uda(task, tc_string_borrow("leg1")).ptr); - - udas = tc_task_get_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(0, udas.len); - tc_uda_list_free(&udas); - - udas = tc_task_get_legacy_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(0, udas.len); - tc_uda_list_free(&udas); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_set_uda(task, - tc_string_borrow("ns"), - tc_string_borrow("u1"), - tc_string_borrow("vvv"))); - - value = tc_task_get_uda(task, tc_string_borrow("ns"), tc_string_borrow("u1")); - TEST_ASSERT_NOT_NULL(value.ptr); - TEST_ASSERT_EQUAL_STRING("vvv", tc_string_content(&value)); - tc_string_free(&value); - TEST_ASSERT_NULL(tc_task_get_legacy_uda(task, tc_string_borrow("leg1")).ptr); - - udas = tc_task_get_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(1, udas.len); - TEST_ASSERT_EQUAL_STRING("ns", tc_string_content(&udas.items[0].ns)); - TEST_ASSERT_EQUAL_STRING("u1", tc_string_content(&udas.items[0].key)); - TEST_ASSERT_EQUAL_STRING("vvv", tc_string_content(&udas.items[0].value)); - tc_uda_list_free(&udas); - - udas = tc_task_get_legacy_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(1, udas.len); - TEST_ASSERT_NULL(udas.items[0].ns.ptr); - TEST_ASSERT_EQUAL_STRING("ns.u1", tc_string_content(&udas.items[0].key)); - TEST_ASSERT_EQUAL_STRING("vvv", tc_string_content(&udas.items[0].value)); - tc_uda_list_free(&udas); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_set_legacy_uda(task, - tc_string_borrow("leg1"), - tc_string_borrow("legv"))); - - value = tc_task_get_uda(task, tc_string_borrow("ns"), tc_string_borrow("u1")); - TEST_ASSERT_NOT_NULL(value.ptr); - TEST_ASSERT_EQUAL_STRING("vvv", tc_string_content(&value)); - tc_string_free(&value); - - value = tc_task_get_legacy_uda(task, tc_string_borrow("leg1")); - TEST_ASSERT_NOT_NULL(value.ptr); - TEST_ASSERT_EQUAL_STRING("legv", tc_string_content(&value)); - tc_string_free(&value); - - udas = tc_task_get_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(2, udas.len); - tc_uda_list_free(&udas); - - udas = tc_task_get_legacy_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(2, udas.len); - tc_uda_list_free(&udas); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_remove_uda(task, - tc_string_borrow("ns"), - tc_string_borrow("u1"))); - - TEST_ASSERT_NULL(tc_task_get_uda(task, tc_string_borrow("ns"), tc_string_borrow("u1")).ptr); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_remove_uda(task, - tc_string_borrow("ns"), - tc_string_borrow("u1"))); - - udas = tc_task_get_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(1, udas.len); - TEST_ASSERT_EQUAL_STRING("", tc_string_content(&udas.items[0].ns)); - TEST_ASSERT_EQUAL_STRING("leg1", tc_string_content(&udas.items[0].key)); - TEST_ASSERT_EQUAL_STRING("legv", tc_string_content(&udas.items[0].value)); - tc_uda_list_free(&udas); - - udas = tc_task_get_legacy_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(1, udas.len); - TEST_ASSERT_NULL(udas.items[0].ns.ptr); - TEST_ASSERT_EQUAL_STRING("leg1", tc_string_content(&udas.items[0].key)); - TEST_ASSERT_EQUAL_STRING("legv", tc_string_content(&udas.items[0].value)); - tc_uda_list_free(&udas); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_remove_legacy_uda(task, - tc_string_borrow("leg1"))); - - TEST_ASSERT_NULL(tc_task_get_legacy_uda(task, tc_string_borrow("leg1")).ptr); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_remove_legacy_uda(task, - tc_string_borrow("leg1"))); - - udas = tc_task_get_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(0, udas.len); - tc_uda_list_free(&udas); - - udas = tc_task_get_legacy_udas(task); - TEST_ASSERT_NOT_NULL(udas.items); - TEST_ASSERT_EQUAL(0, udas.len); - tc_uda_list_free(&udas); - - tc_task_free(task); - tc_replica_free(rep); -} - -// dependency manipulation -static void test_task_dependencies(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task1 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("task 1")); - TEST_ASSERT_NOT_NULL(task1); - TCTask *task2 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("task 2")); - TEST_ASSERT_NOT_NULL(task2); - - TCUuidList deps; - - deps = tc_task_get_dependencies(task1); - TEST_ASSERT_EQUAL(0, deps.len); - tc_uuid_list_free(&deps); - - tc_task_to_mut(task1, rep); - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_add_dependency(task1, tc_task_get_uuid(task2))); - - deps = tc_task_get_dependencies(task1); - TEST_ASSERT_EQUAL(1, deps.len); - TEST_ASSERT_EQUAL_MEMORY(tc_task_get_uuid(task2).bytes, deps.items[0].bytes, 16); - tc_uuid_list_free(&deps); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, - tc_task_remove_dependency(task1, tc_task_get_uuid(task2))); - - deps = tc_task_get_dependencies(task1); - TEST_ASSERT_EQUAL(0, deps.len); - tc_uuid_list_free(&deps); - - tc_task_free(task1); - tc_task_free(task2); - tc_replica_free(rep); -} - -static void tckvlist_assert_key(TCKVList *list, char *key, char *value) { - TEST_ASSERT_NOT_NULL(list); - for (size_t i = 0; i < list->len; i++) { - if (0 == strcmp(tc_string_content(&list->items[i].key), key)) { - TEST_ASSERT_EQUAL_STRING(value, tc_string_content(&list->items[i].value)); - return; - } - } - TEST_FAIL_MESSAGE("key not found"); -} - -// get_tags returns the list of tags -static void test_task_taskmap(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("my task")); - TEST_ASSERT_NOT_NULL(task); - - tc_task_to_mut(task, rep); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_tag(task, tc_string_borrow("next"))); - - TCAnnotation ann; - ann.entry = 1644623411; - ann.description = tc_string_borrow("ann1"); - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_add_annotation(task, &ann)); - - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_task_set_wait(task, 3643679997)); // 2085 - - TCKVList taskmap = tc_task_get_taskmap(task); - tckvlist_assert_key(&taskmap, "annotation_1644623411", "ann1"); - tckvlist_assert_key(&taskmap, "tag_next", ""); - tckvlist_assert_key(&taskmap, "status", "pending"); - tckvlist_assert_key(&taskmap, "description", "my task"); - tc_kv_list_free(&taskmap); - - tc_task_free(task); - tc_replica_free(rep); -} - -// taking from a task list behaves correctly -static void test_task_list_take(void) { - TCReplica *rep = tc_replica_new_in_memory(); - TEST_ASSERT_NULL(tc_replica_error(rep).ptr); - - TCTask *task1 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("t")); - TEST_ASSERT_NOT_NULL(task1); - - TCTask *task2 = tc_replica_new_task(rep, TC_STATUS_PENDING, tc_string_borrow("t")); - TEST_ASSERT_NOT_NULL(task2); - tc_task_free(task2); - - TCString desc; - TCTaskList tasks = tc_replica_all_tasks(rep); - TEST_ASSERT_NOT_NULL(tasks.items); - TEST_ASSERT_EQUAL(2, tasks.len); - - task1 = tc_task_list_take(&tasks, 5); // out of bounds - TEST_ASSERT_NULL(task1); - - task1 = tc_task_list_take(&tasks, 0); - TEST_ASSERT_NOT_NULL(task1); - desc = tc_task_get_description(task1); - TEST_ASSERT_EQUAL_STRING("t", tc_string_content(&desc)); - tc_string_free(&desc); - - task2 = tc_task_list_take(&tasks, 1); - TEST_ASSERT_NOT_NULL(task2); - desc = tc_task_get_description(task2); - TEST_ASSERT_EQUAL_STRING("t", tc_string_content(&desc)); - tc_string_free(&desc); - - tc_task_free(task1); - tc_task_free(task2); - - task1 = tc_task_list_take(&tasks, 0); // already taken - TEST_ASSERT_NULL(task1); - - task1 = tc_task_list_take(&tasks, 5); // out of bounds - TEST_ASSERT_NULL(task1); - - tc_task_list_free(&tasks); - TEST_ASSERT_NULL(tasks.items); - - tc_replica_free(rep); -} - -int task_tests(void) { - UNITY_BEGIN(); - // each test case above should be named here, in order. - RUN_TEST(test_task_creation); - RUN_TEST(test_task_free_mutable_task); - RUN_TEST(test_task_get_set_status); - RUN_TEST(test_task_get_set_description); - RUN_TEST(test_task_get_set_attribute); - RUN_TEST(test_task_get_set_entry); - RUN_TEST(test_task_get_set_modified); - RUN_TEST(test_task_get_set_wait_and_is_waiting); - RUN_TEST(test_task_start_stop_is_active); - RUN_TEST(test_task_done_and_delete); - RUN_TEST(test_task_add_remove_has_tag); - RUN_TEST(test_task_get_tags); - RUN_TEST(test_task_annotations); - RUN_TEST(test_task_udas); - RUN_TEST(test_task_dependencies); - RUN_TEST(test_task_taskmap); - RUN_TEST(test_task_list_take); - return UNITY_END(); -} diff --git a/taskchampion/integration-tests/src/bindings_tests/test.c b/taskchampion/integration-tests/src/bindings_tests/test.c deleted file mode 100644 index 5afa236ca..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/test.c +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include "unity.h" - -// these functions are shared between all test "suites" -// and cannot be customized per-suite. -void setUp(void) { } -void tearDown(void) { } - -static FILE *output = NULL; - -// Set up for test_output, writing output to "TEST-OUTPUT" in the -// current directory. The Rust test harness reads this file to get -// the output and display it only on failure. This is called by -// the Rust test harness -void setup_output(void) { - output = fopen("TEST-OUTPUT", "w"); -} - -// Close the output file. Called by the Rust test harness. -void finish_output(void) { - fclose(output); - output = NULL; -} - -// this replaces UNITY_OUTPUT_CHAR, and writes output to -// TEST-OUTPUT in the current directory; the Rust test harness -// will read this data if the test fails. -void test_output(char c) { - fputc(c, output); -} diff --git a/taskchampion/integration-tests/src/bindings_tests/unity/LICENSE.txt b/taskchampion/integration-tests/src/bindings_tests/unity/LICENSE.txt deleted file mode 100644 index b9a329dde..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/unity/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/taskchampion/integration-tests/src/bindings_tests/unity/README.md b/taskchampion/integration-tests/src/bindings_tests/unity/README.md deleted file mode 100644 index 6f755ced0..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/unity/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Unity - -This directory contains the src from https://github.com/ThrowTheSwitch/Unity, revision 8ba01386008196a92ef4fdbdb0b00f2434c79563. diff --git a/taskchampion/integration-tests/src/bindings_tests/unity/unity.c b/taskchampion/integration-tests/src/bindings_tests/unity/unity.c deleted file mode 100644 index b88024875..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/unity/unity.c +++ /dev/null @@ -1,2119 +0,0 @@ -/* ========================================================================= - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -============================================================================ */ - -#include "unity.h" -#include - -#ifdef AVR -#include -#else -#define PROGMEM -#endif - -/* If omitted from header, declare overrideable prototypes here so they're ready for use */ -#ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION -void UNITY_OUTPUT_CHAR(int); -#endif - -/* Helpful macros for us to use here in Assert functions */ -#define UNITY_FAIL_AND_BAIL do { Unity.CurrentTestFailed = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } while (0) -#define UNITY_IGNORE_AND_BAIL do { Unity.CurrentTestIgnored = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } while (0) -#define RETURN_IF_FAIL_OR_IGNORE do { if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) { TEST_ABORT(); } } while (0) - -struct UNITY_STORAGE_T Unity; - -#ifdef UNITY_OUTPUT_COLOR -const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m"; -const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m"; -const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m"; -const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; -#else -const char PROGMEM UnityStrOk[] = "OK"; -const char PROGMEM UnityStrPass[] = "PASS"; -const char PROGMEM UnityStrFail[] = "FAIL"; -const char PROGMEM UnityStrIgnore[] = "IGNORE"; -#endif -static const char PROGMEM UnityStrNull[] = "NULL"; -static const char PROGMEM UnityStrSpacer[] = ". "; -static const char PROGMEM UnityStrExpected[] = " Expected "; -static const char PROGMEM UnityStrWas[] = " Was "; -static const char PROGMEM UnityStrGt[] = " to be greater than "; -static const char PROGMEM UnityStrLt[] = " to be less than "; -static const char PROGMEM UnityStrOrEqual[] = "or equal to "; -static const char PROGMEM UnityStrNotEqual[] = " to be not equal to "; -static const char PROGMEM UnityStrElement[] = " Element "; -static const char PROGMEM UnityStrByte[] = " Byte "; -static const char PROGMEM UnityStrMemory[] = " Memory Mismatch."; -static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta "; -static const char PROGMEM UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; -static const char PROGMEM UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; -static const char PROGMEM UnityStrNullPointerForActual[] = " Actual pointer was NULL"; -#ifndef UNITY_EXCLUDE_FLOAT -static const char PROGMEM UnityStrNot[] = "Not "; -static const char PROGMEM UnityStrInf[] = "Infinity"; -static const char PROGMEM UnityStrNegInf[] = "Negative Infinity"; -static const char PROGMEM UnityStrNaN[] = "NaN"; -static const char PROGMEM UnityStrDet[] = "Determinate"; -static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; -#endif -const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled"; -const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled"; -const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled"; -const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled"; -static const char PROGMEM UnityStrBreaker[] = "-----------------------"; -static const char PROGMEM UnityStrResultsTests[] = " Tests "; -static const char PROGMEM UnityStrResultsFailures[] = " Failures "; -static const char PROGMEM UnityStrResultsIgnored[] = " Ignored "; -#ifndef UNITY_EXCLUDE_DETAILS -static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; -static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; -#endif -/*----------------------------------------------- - * Pretty Printers & Test Result Output Handlers - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -/* Local helper function to print characters. */ -static void UnityPrintChar(const char* pch) -{ - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } -} - -/*-----------------------------------------------*/ -/* Local helper function to print ANSI escape strings e.g. "\033[42m". */ -#ifdef UNITY_OUTPUT_COLOR -static UNITY_UINT UnityPrintAnsiEscapeString(const char* string) -{ - const char* pch = string; - UNITY_UINT count = 0; - - while (*pch && (*pch != 'm')) - { - UNITY_OUTPUT_CHAR(*pch); - pch++; - count++; - } - UNITY_OUTPUT_CHAR('m'); - count++; - - return count; -} -#endif - -/*-----------------------------------------------*/ -void UnityPrint(const char* string) -{ - const char* pch = string; - - if (pch != NULL) - { - while (*pch) - { -#ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } -#endif - UnityPrintChar(pch); - pch++; - } - } -} -/*-----------------------------------------------*/ -void UnityPrintLen(const char* string, const UNITY_UINT32 length) -{ - const char* pch = string; - - if (pch != NULL) - { - while (*pch && ((UNITY_UINT32)(pch - string) < length)) - { - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } - pch++; - } - } -} - -/*-----------------------------------------------*/ -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style) -{ - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (style == UNITY_DISPLAY_STYLE_CHAR) - { - /* printable characters plus CR & LF are printed */ - UNITY_OUTPUT_CHAR('\''); - if ((number <= 126) && (number >= 32)) - { - UNITY_OUTPUT_CHAR((int)number); - } - /* write escaped carriage returns */ - else if (number == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (number == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 2); - } - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrintNumber(number); - } - } - else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT) - { - UnityPrintNumberUnsigned((UNITY_UINT)number); - } - else - { - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, (char)((style & 0xF) * 2)); - } -} - -/*-----------------------------------------------*/ -void UnityPrintNumber(const UNITY_INT number_to_print) -{ - UNITY_UINT number = (UNITY_UINT)number_to_print; - - if (number_to_print < 0) - { - /* A negative number, including MIN negative */ - UNITY_OUTPUT_CHAR('-'); - number = (~number) + 1; - } - UnityPrintNumberUnsigned(number); -} - -/*----------------------------------------------- - * basically do an itoa using as little ram as possible */ -void UnityPrintNumberUnsigned(const UNITY_UINT number) -{ - UNITY_UINT divisor = 1; - - /* figure out initial divisor */ - while (number / divisor > 9) - { - divisor *= 10; - } - - /* now mod and print, then divide divisor */ - do - { - UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10))); - divisor /= 10; - } while (divisor > 0); -} - -/*-----------------------------------------------*/ -void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print) -{ - int nibble; - char nibbles = nibbles_to_print; - - if ((unsigned)nibbles > UNITY_MAX_NIBBLES) - { - nibbles = UNITY_MAX_NIBBLES; - } - - while (nibbles > 0) - { - nibbles--; - nibble = (int)(number >> (nibbles * 4)) & 0x0F; - if (nibble <= 9) - { - UNITY_OUTPUT_CHAR((char)('0' + nibble)); - } - else - { - UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble)); - } - } -} - -/*-----------------------------------------------*/ -void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) -{ - UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1); - UNITY_INT32 i; - - for (i = 0; i < UNITY_INT_WIDTH; i++) - { - if (current_bit & mask) - { - if (current_bit & number) - { - UNITY_OUTPUT_CHAR('1'); - } - else - { - UNITY_OUTPUT_CHAR('0'); - } - } - else - { - UNITY_OUTPUT_CHAR('X'); - } - current_bit = current_bit >> 1; - } -} - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -/* - * This function prints a floating-point value in a format similar to - * printf("%.7g") on a single-precision machine or printf("%.9g") on a - * double-precision machine. The 7th digit won't always be totally correct - * in single-precision operation (for that level of accuracy, a more - * complicated algorithm would be needed). - */ -void UnityPrintFloat(const UNITY_DOUBLE input_number) -{ -#ifdef UNITY_INCLUDE_DOUBLE - static const int sig_digits = 9; - static const UNITY_INT32 min_scaled = 100000000; - static const UNITY_INT32 max_scaled = 1000000000; -#else - static const int sig_digits = 7; - static const UNITY_INT32 min_scaled = 1000000; - static const UNITY_INT32 max_scaled = 10000000; -#endif - - UNITY_DOUBLE number = input_number; - - /* print minus sign (does not handle negative zero) */ - if (number < 0.0f) - { - UNITY_OUTPUT_CHAR('-'); - number = -number; - } - - /* handle zero, NaN, and +/- infinity */ - if (number == 0.0f) - { - UnityPrint("0"); - } - else if (isnan(number)) - { - UnityPrint("nan"); - } - else if (isinf(number)) - { - UnityPrint("inf"); - } - else - { - UNITY_INT32 n_int = 0; - UNITY_INT32 n; - int exponent = 0; - int decimals; - int digits; - char buf[16] = {0}; - - /* - * Scale up or down by powers of 10. To minimize rounding error, - * start with a factor/divisor of 10^10, which is the largest - * power of 10 that can be represented exactly. Finally, compute - * (exactly) the remaining power of 10 and perform one more - * multiplication or division. - */ - if (number < 1.0f) - { - UNITY_DOUBLE factor = 1.0f; - - while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; } - while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; } - - number *= factor; - } - else if (number > (UNITY_DOUBLE)max_scaled) - { - UNITY_DOUBLE divisor = 1.0f; - - while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { number /= 1e10f; exponent += 10; } - while (number / divisor > (UNITY_DOUBLE)max_scaled) { divisor *= 10.0f; exponent++; } - - number /= divisor; - } - else - { - /* - * In this range, we can split off the integer part before - * doing any multiplications. This reduces rounding error by - * freeing up significant bits in the fractional part. - */ - UNITY_DOUBLE factor = 1.0f; - n_int = (UNITY_INT32)number; - number -= (UNITY_DOUBLE)n_int; - - while (n_int < min_scaled) { n_int *= 10; factor *= 10.0f; exponent--; } - - number *= factor; - } - - /* round to nearest integer */ - n = ((UNITY_INT32)(number + number) + 1) / 2; - -#ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO - /* round to even if exactly between two integers */ - if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) - n--; -#endif - - n += n_int; - - if (n >= max_scaled) - { - n = min_scaled; - exponent++; - } - - /* determine where to place decimal point */ - decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) ? (-exponent) : (sig_digits - 1); - exponent += decimals; - - /* truncate trailing zeroes after decimal point */ - while ((decimals > 0) && ((n % 10) == 0)) - { - n /= 10; - decimals--; - } - - /* build up buffer in reverse order */ - digits = 0; - while ((n != 0) || (digits <= decimals)) - { - buf[digits++] = (char)('0' + n % 10); - n /= 10; - } - - /* print out buffer (backwards) */ - while (digits > 0) - { - if (digits == decimals) - { - UNITY_OUTPUT_CHAR('.'); - } - UNITY_OUTPUT_CHAR(buf[--digits]); - } - - /* print exponent if needed */ - if (exponent != 0) - { - UNITY_OUTPUT_CHAR('e'); - - if (exponent < 0) - { - UNITY_OUTPUT_CHAR('-'); - exponent = -exponent; - } - else - { - UNITY_OUTPUT_CHAR('+'); - } - - digits = 0; - while ((exponent != 0) || (digits < 2)) - { - buf[digits++] = (char)('0' + exponent % 10); - exponent /= 10; - } - while (digits > 0) - { - UNITY_OUTPUT_CHAR(buf[--digits]); - } - } - } -} -#endif /* ! UNITY_EXCLUDE_FLOAT_PRINT */ - -/*-----------------------------------------------*/ -static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) -{ -#ifdef UNITY_OUTPUT_FOR_ECLIPSE - UNITY_OUTPUT_CHAR('('); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(')'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#else -#ifdef UNITY_OUTPUT_FOR_IAR_WORKBENCH - UnityPrint("'); - UnityPrint(Unity.CurrentTestName); - UnityPrint(" "); -#else -#ifdef UNITY_OUTPUT_FOR_QT_CREATOR - UnityPrint("file://"); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#else - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(':'); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#endif -#endif -#endif -} - -/*-----------------------------------------------*/ -static void UnityTestResultsFailBegin(const UNITY_LINE_TYPE line) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - UNITY_OUTPUT_CHAR(':'); -} - -/*-----------------------------------------------*/ -void UnityConcludeTest(void) -{ - if (Unity.CurrentTestIgnored) - { - Unity.TestIgnores++; - } - else if (!Unity.CurrentTestFailed) - { - UnityTestResultsBegin(Unity.TestFile, Unity.CurrentTestLineNumber); - UnityPrint(UnityStrPass); - } - else - { - Unity.TestFailures++; - } - - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - UNITY_PRINT_EXEC_TIME(); - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); -} - -/*-----------------------------------------------*/ -static void UnityAddMsgIfSpecified(const char* msg) -{ - if (msg) - { - UnityPrint(UnityStrSpacer); - -#ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); -#endif -#ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } -#endif - UnityPrint(msg); - } -} - -/*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStrings(const char* expected, const char* actual) -{ - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(expected); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(actual); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } -} - -/*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStringsLen(const char* expected, - const char* actual, - const UNITY_UINT32 length) -{ - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(expected, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(actual, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } -} - -/*----------------------------------------------- - * Assertion & Control Helpers - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_LINE_TYPE lineNumber, - const char* msg) -{ - /* Both are NULL or same pointer */ - if (expected == actual) { return 0; } - - /* print and return true if just expected is NULL */ - if (expected == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForExpected); - UnityAddMsgIfSpecified(msg); - return 1; - } - - /* print and return true if just actual is NULL */ - if (actual == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForActual); - UnityAddMsgIfSpecified(msg); - return 1; - } - - return 0; /* return false if neither is NULL */ -} - -/*----------------------------------------------- - * Assertion Functions - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if ((mask & expected) != (mask & actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected); - UnityPrint(UnityStrWas); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if (expected != actual) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - int failed = 0; - RETURN_IF_FAIL_OR_IGNORE; - - if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { return; } - if ((threshold == actual)) { failed = 1; } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - else /* UINT or HEX */ - { - if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - - if (failed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(actual, style); - if (compare & UNITY_GREATER_THAN) { UnityPrint(UnityStrGt); } - if (compare & UNITY_SMALLER_THAN) { UnityPrint(UnityStrLt); } - if (compare & UNITY_EQUAL_TO) { UnityPrint(UnityStrOrEqual); } - if (compare == UNITY_NOT_EQUAL) { UnityPrint(UnityStrNotEqual); } - UnityPrintNumberByStyle(threshold, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#define UnityPrintPointlessAndBail() \ -do { \ - UnityTestResultsFailBegin(lineNumber); \ - UnityPrint(UnityStrPointless); \ - UnityAddMsgIfSpecified(msg); \ - UNITY_FAIL_AND_BAIL; \ -} while (0) - -/*-----------------------------------------------*/ -void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; - -#ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; -#endif - - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if (expect_val != actual_val) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } -} - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_FLOAT -/* Wrap this define in a function with variable types as float or double */ -#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \ - if (isinf(expected) && isinf(actual) && (((expected) < 0) == ((actual) < 0))) return 1; \ - if (UNITY_NAN_CHECK) return 1; \ - (diff) = (actual) - (expected); \ - if ((diff) < 0) (diff) = -(diff); \ - if ((delta) < 0) (delta) = -(delta); \ - return !(isnan(diff) || isinf(diff) || ((diff) > (delta))) - /* This first part of this condition will catch any NaN or Infinite values */ -#ifndef UNITY_NAN_NOT_EQUAL_NAN - #define UNITY_NAN_CHECK isnan(expected) && isnan(actual) -#else - #define UNITY_NAN_CHECK 0 -#endif - -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - do { \ - UnityPrint(UnityStrExpected); \ - UnityPrintFloat(expected); \ - UnityPrint(UnityStrWas); \ - UnityPrintFloat(actual); \ - } while (0) -#else - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - UnityPrint(UnityStrDelta) -#endif /* UNITY_EXCLUDE_FLOAT_PRINT */ - -/*-----------------------------------------------*/ -static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual) -{ - UNITY_FLOAT diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)*ptr_expected, (UNITY_DOUBLE)*ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } -} - -/*-----------------------------------------------*/ -void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - - if (!UnityFloatsWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) -{ - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: /* including UNITY_FLOAT_INVALID_TRAIT */ - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat((UNITY_DOUBLE)actual); -#else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); -#endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#endif /* not UNITY_EXCLUDE_FLOAT */ - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_DOUBLE -static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_DOUBLE actual) -{ - UNITY_DOUBLE diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, *ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } -} - -/*-----------------------------------------------*/ -void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if (!UnityDoublesWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) -{ - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: /* including UNITY_FLOAT_INVALID_TRAIT */ - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat(actual); -#else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); -#endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#endif /* not UNITY_EXCLUDE_DOUBLE */ - -/*-----------------------------------------------*/ -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual > expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - else - { - if ((UNITY_UINT)actual > (UNITY_UINT)expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; - -#ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; -#endif - - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual_val > expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - else - { - if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; expected[i] || actual[i]; i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStrings(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; (i < length) && (expected[i] || actual[i]); i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStringsLen(expected, actual, length); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 i = 0; - UNITY_UINT32 j = 0; - const char* expd = NULL; - const char* act = NULL; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if no elements, it's an error */ - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if ((const void*)expected == (const void*)actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - if (flags != UNITY_ARRAY_TO_ARRAY) - { - expd = (const char*)expected; - } - - do - { - act = actual[j]; - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expd = ((const char* const*)expected)[j]; - } - - /* if both pointers not null compare the strings */ - if (expd && act) - { - for (i = 0; expd[i] || act[i]; i++) - { - if (expd[i] != act[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expd != act) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(j); - } - UnityPrintExpectedAndActualStrings(expd, act); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - } while (++j < num_elements); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_act = (UNITY_PTR_ATTRIBUTE const unsigned char*)actual; - UNITY_UINT32 elements = num_elements; - UNITY_UINT32 bytes; - - RETURN_IF_FAIL_OR_IGNORE; - - if ((elements == 0) || (length == 0)) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - bytes = length; - while (bytes--) - { - if (*ptr_exp != *ptr_act) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrMemory); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - } - UnityPrint(UnityStrByte); - UnityPrintNumberUnsigned(length - bytes - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(*ptr_exp, UNITY_DISPLAY_STYLE_HEX8); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(*ptr_act, UNITY_DISPLAY_STYLE_HEX8); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - ptr_exp++; - ptr_act++; - } - if (flags == UNITY_ARRAY_TO_VAL) - { - ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - } - } -} - -/*-----------------------------------------------*/ - -static union -{ - UNITY_INT8 i8; - UNITY_INT16 i16; - UNITY_INT32 i32; -#ifdef UNITY_SUPPORT_64 - UNITY_INT64 i64; -#endif -#ifndef UNITY_EXCLUDE_FLOAT - float f; -#endif -#ifndef UNITY_EXCLUDE_DOUBLE - double d; -#endif -} UnityQuickCompare; - -UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size) -{ - switch(size) - { - case 1: - UnityQuickCompare.i8 = (UNITY_INT8)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); - - case 2: - UnityQuickCompare.i16 = (UNITY_INT16)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); - -#ifdef UNITY_SUPPORT_64 - case 8: - UnityQuickCompare.i64 = (UNITY_INT64)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); -#endif - - default: /* 4 bytes */ - UnityQuickCompare.i32 = (UNITY_INT32)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); - } -} - -#ifndef UNITY_EXCLUDE_FLOAT -/*-----------------------------------------------*/ -UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) -{ - UnityQuickCompare.f = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f); -} -#endif - -#ifndef UNITY_EXCLUDE_DOUBLE -/*-----------------------------------------------*/ -UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) -{ - UnityQuickCompare.d = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d); -} -#endif - -/*----------------------------------------------- - * printf helper function - *-----------------------------------------------*/ -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -static void UnityPrintFVA(const char* format, va_list va) -{ - const char* pch = format; - if (pch != NULL) - { - while (*pch) - { - /* format identification character */ - if (*pch == '%') - { - pch++; - - if (pch != NULL) - { - switch (*pch) - { - case 'd': - case 'i': - { - const int number = va_arg(va, int); - UnityPrintNumber((UNITY_INT)number); - break; - } -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - case 'f': - case 'g': - { - const double number = va_arg(va, double); - UnityPrintFloat((UNITY_DOUBLE)number); - break; - } -#endif - case 'u': - { - const unsigned int number = va_arg(va, unsigned int); - UnityPrintNumberUnsigned((UNITY_UINT)number); - break; - } - case 'b': - { - const unsigned int number = va_arg(va, unsigned int); - const UNITY_UINT mask = (UNITY_UINT)0 - (UNITY_UINT)1; - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('b'); - UnityPrintMask(mask, (UNITY_UINT)number); - break; - } - case 'x': - case 'X': - case 'p': - { - const unsigned int number = va_arg(va, unsigned int); - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 8); - break; - } - case 'c': - { - const int ch = va_arg(va, int); - UnityPrintChar((const char *)&ch); - break; - } - case 's': - { - const char * string = va_arg(va, const char *); - UnityPrint(string); - break; - } - case '%': - { - UnityPrintChar(pch); - break; - } - default: - { - /* print the unknown format character */ - UNITY_OUTPUT_CHAR('%'); - UnityPrintChar(pch); - break; - } - } - } - } -#ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - else if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } -#endif - else if (*pch == '\n') - { - UNITY_PRINT_EOL(); - } - else - { - UnityPrintChar(pch); - } - - pch++; - } - } -} - -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if(format != NULL) - { - UnityPrint(": "); - va_list va; - va_start(va, format); - UnityPrintFVA(format, va); - va_end(va); - } - UNITY_PRINT_EOL(); -} -#endif /* ! UNITY_INCLUDE_PRINT_FORMATTED */ - - -/*----------------------------------------------- - * Control Functions - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -void UnityFail(const char* msg, const UNITY_LINE_TYPE line) -{ - RETURN_IF_FAIL_OR_IGNORE; - - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - -#ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); -#endif -#ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } -#endif - if (msg[0] != ' ') - { - UNITY_OUTPUT_CHAR(' '); - } - UnityPrint(msg); - } - - UNITY_FAIL_AND_BAIL; -} - -/*-----------------------------------------------*/ -void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line) -{ - RETURN_IF_FAIL_OR_IGNORE; - - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrIgnore); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_IGNORE_AND_BAIL; -} - -/*-----------------------------------------------*/ -void UnityMessage(const char* msg, const UNITY_LINE_TYPE line) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_PRINT_EOL(); -} - -/*-----------------------------------------------*/ -/* If we have not defined our own test runner, then include our default test runner to make life easier */ -#ifndef UNITY_SKIP_DEFAULT_RUNNER -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) -{ - Unity.CurrentTestName = FuncName; - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; - Unity.NumberOfTests++; - UNITY_CLR_DETAILS(); - UNITY_EXEC_TIME_START(); - if (TEST_PROTECT()) - { - setUp(); - Func(); - } - if (TEST_PROTECT()) - { - tearDown(); - } - UNITY_EXEC_TIME_STOP(); - UnityConcludeTest(); -} -#endif - -/*-----------------------------------------------*/ -void UnitySetTestFile(const char* filename) -{ - Unity.TestFile = filename; -} - -/*-----------------------------------------------*/ -void UnityBegin(const char* filename) -{ - Unity.TestFile = filename; - Unity.CurrentTestName = NULL; - Unity.CurrentTestLineNumber = 0; - Unity.NumberOfTests = 0; - Unity.TestFailures = 0; - Unity.TestIgnores = 0; - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - - UNITY_CLR_DETAILS(); - UNITY_OUTPUT_START(); -} - -/*-----------------------------------------------*/ -int UnityEnd(void) -{ - UNITY_PRINT_EOL(); - UnityPrint(UnityStrBreaker); - UNITY_PRINT_EOL(); - UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests)); - UnityPrint(UnityStrResultsTests); - UnityPrintNumber((UNITY_INT)(Unity.TestFailures)); - UnityPrint(UnityStrResultsFailures); - UnityPrintNumber((UNITY_INT)(Unity.TestIgnores)); - UnityPrint(UnityStrResultsIgnored); - UNITY_PRINT_EOL(); - if (Unity.TestFailures == 0U) - { - UnityPrint(UnityStrOk); - } - else - { - UnityPrint(UnityStrFail); -#ifdef UNITY_DIFFERENTIATE_FINAL_FAIL - UNITY_OUTPUT_CHAR('E'); UNITY_OUTPUT_CHAR('D'); -#endif - } - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); - UNITY_OUTPUT_COMPLETE(); - return (int)(Unity.TestFailures); -} - -/*----------------------------------------------- - * Command Line Argument Support - *-----------------------------------------------*/ -#ifdef UNITY_USE_COMMAND_LINE_ARGS - -char* UnityOptionIncludeNamed = NULL; -char* UnityOptionExcludeNamed = NULL; -int UnityVerbosity = 1; - -/*-----------------------------------------------*/ -int UnityParseOptions(int argc, char** argv) -{ - int i; - UnityOptionIncludeNamed = NULL; - UnityOptionExcludeNamed = NULL; - - for (i = 1; i < argc; i++) - { - if (argv[i][0] == '-') - { - switch (argv[i][1]) - { - case 'l': /* list tests */ - return -1; - case 'n': /* include tests with name including this string */ - case 'f': /* an alias for -n */ - if (argv[i][2] == '=') - { - UnityOptionIncludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionIncludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Include Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - case 'q': /* quiet */ - UnityVerbosity = 0; - break; - case 'v': /* verbose */ - UnityVerbosity = 2; - break; - case 'x': /* exclude tests with name including this string */ - if (argv[i][2] == '=') - { - UnityOptionExcludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionExcludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Exclude Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - default: - UnityPrint("ERROR: Unknown Option "); - UNITY_OUTPUT_CHAR(argv[i][1]); - UNITY_PRINT_EOL(); - return 1; - } - } - } - - return 0; -} - -/*-----------------------------------------------*/ -int IsStringInBiggerString(const char* longstring, const char* shortstring) -{ - const char* lptr = longstring; - const char* sptr = shortstring; - const char* lnext = lptr; - - if (*sptr == '*') - { - return 1; - } - - while (*lptr) - { - lnext = lptr + 1; - - /* If they current bytes match, go on to the next bytes */ - while (*lptr && *sptr && (*lptr == *sptr)) - { - lptr++; - sptr++; - - /* We're done if we match the entire string or up to a wildcard */ - if (*sptr == '*') - return 1; - if (*sptr == ',') - return 1; - if (*sptr == '"') - return 1; - if (*sptr == '\'') - return 1; - if (*sptr == ':') - return 2; - if (*sptr == 0) - return 1; - } - - /* Otherwise we start in the long pointer 1 character further and try again */ - lptr = lnext; - sptr = shortstring; - } - - return 0; -} - -/*-----------------------------------------------*/ -int UnityStringArgumentMatches(const char* str) -{ - int retval; - const char* ptr1; - const char* ptr2; - const char* ptrf; - - /* Go through the options and get the substrings for matching one at a time */ - ptr1 = str; - while (ptr1[0] != 0) - { - if ((ptr1[0] == '"') || (ptr1[0] == '\'')) - { - ptr1++; - } - - /* look for the start of the next partial */ - ptr2 = ptr1; - ptrf = 0; - do - { - ptr2++; - if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')) - { - ptrf = &ptr2[1]; - } - } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')); - - while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ','))) - { - ptr2++; - } - - /* done if complete filename match */ - retval = IsStringInBiggerString(Unity.TestFile, ptr1); - if (retval == 1) - { - return retval; - } - - /* done if testname match after filename partial match */ - if ((retval == 2) && (ptrf != 0)) - { - if (IsStringInBiggerString(Unity.CurrentTestName, ptrf)) - { - return 1; - } - } - - /* done if complete testname match */ - if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) - { - return 1; - } - - ptr1 = ptr2; - } - - /* we couldn't find a match for any substrings */ - return 0; -} - -/*-----------------------------------------------*/ -int UnityTestMatches(void) -{ - /* Check if this test name matches the included test pattern */ - int retval; - if (UnityOptionIncludeNamed) - { - retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); - } - else - { - retval = 1; - } - - /* Check if this test name matches the excluded test pattern */ - if (UnityOptionExcludeNamed) - { - if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) - { - retval = 0; - } - } - - return retval; -} - -#endif /* UNITY_USE_COMMAND_LINE_ARGS */ -/*-----------------------------------------------*/ diff --git a/taskchampion/integration-tests/src/bindings_tests/unity/unity.h b/taskchampion/integration-tests/src/bindings_tests/unity/unity.h deleted file mode 100644 index 14225a354..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/unity/unity.h +++ /dev/null @@ -1,661 +0,0 @@ -/* ========================================== - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef UNITY_FRAMEWORK_H -#define UNITY_FRAMEWORK_H -#define UNITY - -#define UNITY_VERSION_MAJOR 2 -#define UNITY_VERSION_MINOR 5 -#define UNITY_VERSION_BUILD 4 -#define UNITY_VERSION ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | UNITY_VERSION_BUILD) - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include "unity_internals.h" - -/*------------------------------------------------------- - * Test Setup / Teardown - *-------------------------------------------------------*/ - -/* These functions are intended to be called before and after each test. - * If using unity directly, these will need to be provided for each test - * executable built. If you are using the test runner generator and/or - * Ceedling, these are optional. */ -void setUp(void); -void tearDown(void); - -/* These functions are intended to be called at the beginning and end of an - * entire test suite. suiteTearDown() is passed the number of tests that - * failed, and its return value becomes the exit code of main(). If using - * Unity directly, you're in charge of calling these if they are desired. - * If using Ceedling or the test runner generator, these will be called - * automatically if they exist. */ -void suiteSetUp(void); -int suiteTearDown(int num_failures); - -/*------------------------------------------------------- - * Test Reset and Verify - *-------------------------------------------------------*/ - -/* These functions are intended to be called before during tests in order - * to support complex test loops, etc. Both are NOT built into Unity. Instead - * the test runner generator will create them. resetTest will run teardown and - * setup again, verifying any end-of-test needs between. verifyTest will only - * run the verification. */ -void resetTest(void); -void verifyTest(void); - -/*------------------------------------------------------- - * Configuration Options - *------------------------------------------------------- - * All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above. - - * Integers/longs/pointers - * - Unity attempts to automatically discover your integer sizes - * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in - * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in - * - If you cannot use the automatic methods above, you can force Unity by using these options: - * - define UNITY_SUPPORT_64 - * - set UNITY_INT_WIDTH - * - set UNITY_LONG_WIDTH - * - set UNITY_POINTER_WIDTH - - * Floats - * - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons - * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT - * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats - * - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons - * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default) - * - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE - * - define UNITY_DOUBLE_TYPE to specify something other than double - * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors - - * Output - * - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired - * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure - - * Optimization - * - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge - * - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests. - - * Test Cases - * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script - - * Parameterized Tests - * - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing - - * Tests with Arguments - * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity - - *------------------------------------------------------- - * Basic Fail and Ignore - *-------------------------------------------------------*/ - -#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) -#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) -#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) -#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) -#define TEST_MESSAGE(message) UnityMessage((message), __LINE__) -#define TEST_ONLY() -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -#define TEST_PRINTF(message, ...) UnityPrintF(__LINE__, (message), __VA_ARGS__) -#endif - -/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. - * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ -#define TEST_PASS() TEST_ABORT() -#define TEST_PASS_MESSAGE(message) do { UnityMessage((message), __LINE__); TEST_ABORT(); } while (0) - -/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out - * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ -#define TEST_FILE(a) - -/*------------------------------------------------------- - * Test Asserts (simple) - *-------------------------------------------------------*/ - -/* Boolean */ -#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE") -#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE") -#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE") -#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE") -#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL") -#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") -#define TEST_ASSERT_EMPTY(pointer) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, " Expected Empty") -#define TEST_ASSERT_NOT_EMPTY(pointer) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, " Expected Non-Empty") - -/* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR(expected, actual) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(0), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(0), (actual), __LINE__, NULL) - -/* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -/* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -/* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, NULL) - -/* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) - - -/* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL) - -/* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) - -/* Arrays Compared To Single Value */ -#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, NULL) - -/* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) - -/* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) - -/* Shorthand */ -#ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") -#endif -#ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal") -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") -#endif -#ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif - -/*------------------------------------------------------- - * Test Asserts (with additional messages) - *-------------------------------------------------------*/ - -/* Boolean */ -#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) -#define TEST_ASSERT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, (message)) - -/* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message)) - -/* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - - -/* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - -/* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, (message)) - -/* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) - - -/* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message)) - -/* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) - -/* Arrays Compared To Single Value*/ -#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, (message)) - -/* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message)) - -/* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) - -/* Shorthand */ -#ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) -#endif -#ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message) -#endif -#ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif - -/* end of UNITY_FRAMEWORK_H */ -#ifdef __cplusplus -} -#endif -#endif diff --git a/taskchampion/integration-tests/src/bindings_tests/unity/unity_internals.h b/taskchampion/integration-tests/src/bindings_tests/unity/unity_internals.h deleted file mode 100644 index d303e8fe7..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/unity/unity_internals.h +++ /dev/null @@ -1,1053 +0,0 @@ -/* ========================================== - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef UNITY_INTERNALS_H -#define UNITY_INTERNALS_H - -#ifdef UNITY_INCLUDE_CONFIG_H -#include "unity_config.h" -#endif - -#ifndef UNITY_EXCLUDE_SETJMP_H -#include -#endif - -#ifndef UNITY_EXCLUDE_MATH_H -#include -#endif - -#ifndef UNITY_EXCLUDE_STDDEF_H -#include -#endif - -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -#include -#endif - -/* Unity Attempts to Auto-Detect Integer Types - * Attempt 1: UINT_MAX, ULONG_MAX in , or default to 32 bits - * Attempt 2: UINTPTR_MAX in , or default to same size as long - * The user may override any of these derived constants: - * UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */ -#ifndef UNITY_EXCLUDE_STDINT_H -#include -#endif - -#ifndef UNITY_EXCLUDE_LIMITS_H -#include -#endif - -#if defined(__GNUC__) || defined(__clang__) - #define UNITY_FUNCTION_ATTR(a) __attribute__((a)) -#else - #define UNITY_FUNCTION_ATTR(a) /* ignore */ -#endif - -#ifndef UNITY_NORETURN - #if defined(__cplusplus) - #if __cplusplus >= 201103L - #define UNITY_NORETURN [[ noreturn ]] - #endif - #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #include - #define UNITY_NORETURN noreturn - #endif -#endif -#ifndef UNITY_NORETURN - #define UNITY_NORETURN UNITY_FUNCTION_ATTR(noreturn) -#endif - -/*------------------------------------------------------- - * Guess Widths If Not Specified - *-------------------------------------------------------*/ - -/* Determine the size of an int, if not already specified. - * We cannot use sizeof(int), because it is not yet defined - * at this stage in the translation of the C program. - * Also sizeof(int) does return the size in addressable units on all platforms, - * which may not necessarily be the size in bytes. - * Therefore, infer it from UINT_MAX if possible. */ -#ifndef UNITY_INT_WIDTH - #ifdef UINT_MAX - #if (UINT_MAX == 0xFFFF) - #define UNITY_INT_WIDTH (16) - #elif (UINT_MAX == 0xFFFFFFFF) - #define UNITY_INT_WIDTH (32) - #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_INT_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_INT_WIDTH (32) - #endif /* UINT_MAX */ -#endif - -/* Determine the size of a long, if not already specified. */ -#ifndef UNITY_LONG_WIDTH - #ifdef ULONG_MAX - #if (ULONG_MAX == 0xFFFF) - #define UNITY_LONG_WIDTH (16) - #elif (ULONG_MAX == 0xFFFFFFFF) - #define UNITY_LONG_WIDTH (32) - #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_LONG_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_LONG_WIDTH (32) - #endif /* ULONG_MAX */ -#endif - -/* Determine the size of a pointer, if not already specified. */ -#ifndef UNITY_POINTER_WIDTH - #ifdef UINTPTR_MAX - #if (UINTPTR_MAX <= 0xFFFF) - #define UNITY_POINTER_WIDTH (16) - #elif (UINTPTR_MAX <= 0xFFFFFFFF) - #define UNITY_POINTER_WIDTH (32) - #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) - #define UNITY_POINTER_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH - #endif /* UINTPTR_MAX */ -#endif - -/*------------------------------------------------------- - * Int Support (Define types based on detected sizes) - *-------------------------------------------------------*/ - -#if (UNITY_INT_WIDTH == 32) - typedef unsigned char UNITY_UINT8; - typedef unsigned short UNITY_UINT16; - typedef unsigned int UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed short UNITY_INT16; - typedef signed int UNITY_INT32; -#elif (UNITY_INT_WIDTH == 16) - typedef unsigned char UNITY_UINT8; - typedef unsigned int UNITY_UINT16; - typedef unsigned long UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed int UNITY_INT16; - typedef signed long UNITY_INT32; -#else - #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) -#endif - -/*------------------------------------------------------- - * 64-bit Support - *-------------------------------------------------------*/ - -/* Auto-detect 64 Bit Support */ -#ifndef UNITY_SUPPORT_64 - #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 - #define UNITY_SUPPORT_64 - #endif -#endif - -/* 64-Bit Support Dependent Configuration */ -#ifndef UNITY_SUPPORT_64 - /* No 64-bit Support */ - typedef UNITY_UINT32 UNITY_UINT; - typedef UNITY_INT32 UNITY_INT; - #define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */ -#else - /* 64-bit Support */ - #if (UNITY_LONG_WIDTH == 32) - typedef unsigned long long UNITY_UINT64; - typedef signed long long UNITY_INT64; - #elif (UNITY_LONG_WIDTH == 64) - typedef unsigned long UNITY_UINT64; - typedef signed long UNITY_INT64; - #else - #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) - #endif - typedef UNITY_UINT64 UNITY_UINT; - typedef UNITY_INT64 UNITY_INT; - #define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */ -#endif - -/*------------------------------------------------------- - * Pointer Support - *-------------------------------------------------------*/ - -#if (UNITY_POINTER_WIDTH == 32) - #define UNITY_PTR_TO_INT UNITY_INT32 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 -#elif (UNITY_POINTER_WIDTH == 64) - #define UNITY_PTR_TO_INT UNITY_INT64 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 -#elif (UNITY_POINTER_WIDTH == 16) - #define UNITY_PTR_TO_INT UNITY_INT16 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 -#else - #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) -#endif - -#ifndef UNITY_PTR_ATTRIBUTE - #define UNITY_PTR_ATTRIBUTE -#endif - -#ifndef UNITY_INTERNAL_PTR - #define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* -#endif - -/*------------------------------------------------------- - * Float Support - *-------------------------------------------------------*/ - -#ifdef UNITY_EXCLUDE_FLOAT - -/* No Floating Point Support */ -#ifndef UNITY_EXCLUDE_DOUBLE -#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */ -#endif -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -#define UNITY_EXCLUDE_FLOAT_PRINT -#endif - -#else - -/* Floating Point Support */ -#ifndef UNITY_FLOAT_PRECISION -#define UNITY_FLOAT_PRECISION (0.00001f) -#endif -#ifndef UNITY_FLOAT_TYPE -#define UNITY_FLOAT_TYPE float -#endif -typedef UNITY_FLOAT_TYPE UNITY_FLOAT; - -/* isinf & isnan macros should be provided by math.h */ -#ifndef isinf -/* The value of Inf - Inf is NaN */ -#define isinf(n) (isnan((n) - (n)) && !isnan(n)) -#endif - -#ifndef isnan -/* NaN is the only floating point value that does NOT equal itself. - * Therefore if n != n, then it is NaN. */ -#define isnan(n) ((n != n) ? 1 : 0) -#endif - -#endif - -/*------------------------------------------------------- - * Double Float Support - *-------------------------------------------------------*/ - -/* unlike float, we DON'T include by default */ -#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) - - /* No Floating Point Support */ - #ifndef UNITY_EXCLUDE_DOUBLE - #define UNITY_EXCLUDE_DOUBLE - #else - #undef UNITY_INCLUDE_DOUBLE - #endif - - #ifndef UNITY_EXCLUDE_FLOAT - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_FLOAT UNITY_DOUBLE; - /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ - #endif - -#else - - /* Double Floating Point Support */ - #ifndef UNITY_DOUBLE_PRECISION - #define UNITY_DOUBLE_PRECISION (1e-12) - #endif - - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; - -#endif - -/*------------------------------------------------------- - * Output Method: stdout (DEFAULT) - *-------------------------------------------------------*/ -#ifndef UNITY_OUTPUT_CHAR - /* Default to using putchar, which is defined in stdio.h */ - #include - #define UNITY_OUTPUT_CHAR(a) (void)putchar(a) -#else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION - extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; - #endif -#endif - -#ifndef UNITY_OUTPUT_FLUSH - #ifdef UNITY_USE_FLUSH_STDOUT - /* We want to use the stdout flush utility */ - #include - #define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) - #else - /* We've specified nothing, therefore flush should just be ignored */ - #define UNITY_OUTPUT_FLUSH() (void)0 - #endif -#else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION - extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION; - #endif -#endif - -#ifndef UNITY_OUTPUT_FLUSH -#define UNITY_FLUSH_CALL() -#else -#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH() -#endif - -#ifndef UNITY_PRINT_EOL -#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') -#endif - -#ifndef UNITY_OUTPUT_START -#define UNITY_OUTPUT_START() -#endif - -#ifndef UNITY_OUTPUT_COMPLETE -#define UNITY_OUTPUT_COMPLETE() -#endif - -#ifdef UNITY_INCLUDE_EXEC_TIME - #if !defined(UNITY_EXEC_TIME_START) && \ - !defined(UNITY_EXEC_TIME_STOP) && \ - !defined(UNITY_PRINT_EXEC_TIME) && \ - !defined(UNITY_TIME_TYPE) - /* If none any of these macros are defined then try to provide a default implementation */ - - #if defined(UNITY_CLOCK_MS) - /* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */ - #define UNITY_TIME_TYPE UNITY_UINT - #define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() - #define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(_WIN32) - #include - #define UNITY_TIME_TYPE clock_t - #define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(__unix__) || defined(__APPLE__) - #include - #define UNITY_TIME_TYPE struct timespec - #define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \ - execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #endif - #endif -#endif - -#ifndef UNITY_EXEC_TIME_START -#define UNITY_EXEC_TIME_START() do { /* nothing*/ } while (0) -#endif - -#ifndef UNITY_EXEC_TIME_STOP -#define UNITY_EXEC_TIME_STOP() do { /* nothing*/ } while (0) -#endif - -#ifndef UNITY_TIME_TYPE -#define UNITY_TIME_TYPE UNITY_UINT -#endif - -#ifndef UNITY_PRINT_EXEC_TIME -#define UNITY_PRINT_EXEC_TIME() do { /* nothing*/ } while (0) -#endif - -/*------------------------------------------------------- - * Footprint - *-------------------------------------------------------*/ - -#ifndef UNITY_LINE_TYPE -#define UNITY_LINE_TYPE UNITY_UINT -#endif - -#ifndef UNITY_COUNTER_TYPE -#define UNITY_COUNTER_TYPE UNITY_UINT -#endif - -/*------------------------------------------------------- - * Internal Structs Needed - *-------------------------------------------------------*/ - -typedef void (*UnityTestFunction)(void); - -#define UNITY_DISPLAY_RANGE_INT (0x10) -#define UNITY_DISPLAY_RANGE_UINT (0x20) -#define UNITY_DISPLAY_RANGE_HEX (0x40) -#define UNITY_DISPLAY_RANGE_CHAR (0x80) - -typedef enum -{ - UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, -#endif - - UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, -#endif - - UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, -#endif - - UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, - - UNITY_DISPLAY_STYLE_UNKNOWN -} UNITY_DISPLAY_STYLE_T; - -typedef enum -{ - UNITY_WITHIN = 0x0, - UNITY_EQUAL_TO = 0x1, - UNITY_GREATER_THAN = 0x2, - UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, - UNITY_SMALLER_THAN = 0x4, - UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, - UNITY_NOT_EQUAL = 0x0, - UNITY_UNKNOWN -} UNITY_COMPARISON_T; - -#ifndef UNITY_EXCLUDE_FLOAT -typedef enum UNITY_FLOAT_TRAIT -{ - UNITY_FLOAT_IS_NOT_INF = 0, - UNITY_FLOAT_IS_INF, - UNITY_FLOAT_IS_NOT_NEG_INF, - UNITY_FLOAT_IS_NEG_INF, - UNITY_FLOAT_IS_NOT_NAN, - UNITY_FLOAT_IS_NAN, - UNITY_FLOAT_IS_NOT_DET, - UNITY_FLOAT_IS_DET, - UNITY_FLOAT_INVALID_TRAIT -} UNITY_FLOAT_TRAIT_T; -#endif - -typedef enum -{ - UNITY_ARRAY_TO_VAL = 0, - UNITY_ARRAY_TO_ARRAY, - UNITY_ARRAY_UNKNOWN -} UNITY_FLAGS_T; - -struct UNITY_STORAGE_T -{ - const char* TestFile; - const char* CurrentTestName; -#ifndef UNITY_EXCLUDE_DETAILS - const char* CurrentDetail1; - const char* CurrentDetail2; -#endif - UNITY_LINE_TYPE CurrentTestLineNumber; - UNITY_COUNTER_TYPE NumberOfTests; - UNITY_COUNTER_TYPE TestFailures; - UNITY_COUNTER_TYPE TestIgnores; - UNITY_COUNTER_TYPE CurrentTestFailed; - UNITY_COUNTER_TYPE CurrentTestIgnored; -#ifdef UNITY_INCLUDE_EXEC_TIME - UNITY_TIME_TYPE CurrentTestStartTime; - UNITY_TIME_TYPE CurrentTestStopTime; -#endif -#ifndef UNITY_EXCLUDE_SETJMP_H - jmp_buf AbortFrame; -#endif -}; - -extern struct UNITY_STORAGE_T Unity; - -/*------------------------------------------------------- - * Test Suite Management - *-------------------------------------------------------*/ - -void UnityBegin(const char* filename); -int UnityEnd(void); -void UnitySetTestFile(const char* filename); -void UnityConcludeTest(void); - -#ifndef RUN_TEST -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); -#else -#define UNITY_SKIP_DEFAULT_RUNNER -#endif - -/*------------------------------------------------------- - * Details Support - *-------------------------------------------------------*/ - -#ifdef UNITY_EXCLUDE_DETAILS -#define UNITY_CLR_DETAILS() -#define UNITY_SET_DETAIL(d1) -#define UNITY_SET_DETAILS(d1,d2) -#else -#define UNITY_CLR_DETAILS() do { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } while (0) -#define UNITY_SET_DETAIL(d1) do { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = 0; } while (0) -#define UNITY_SET_DETAILS(d1,d2) do { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = (d2); } while (0) - -#ifndef UNITY_DETAIL1_NAME -#define UNITY_DETAIL1_NAME "Function" -#endif - -#ifndef UNITY_DETAIL2_NAME -#define UNITY_DETAIL2_NAME "Argument" -#endif -#endif - -#ifdef UNITY_PRINT_TEST_CONTEXT -void UNITY_PRINT_TEST_CONTEXT(void); -#endif - -/*------------------------------------------------------- - * Test Output - *-------------------------------------------------------*/ - -void UnityPrint(const char* string); - -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...); -#endif - -void UnityPrintLen(const char* string, const UNITY_UINT32 length); -void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); -void UnityPrintNumber(const UNITY_INT number_to_print); -void UnityPrintNumberUnsigned(const UNITY_UINT number); -void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print); - -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -void UnityPrintFloat(const UNITY_DOUBLE input_number); -#endif - -/*------------------------------------------------------- - * Test Assertion Functions - *------------------------------------------------------- - * Use the macros below this section instead of calling - * these directly. The macros have a consistent naming - * convention and will pull in file and line information - * for you. */ - -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -#ifndef UNITY_EXCLUDE_SETJMP_H -UNITY_NORETURN void UnityFail(const char* message, const UNITY_LINE_TYPE line); -UNITY_NORETURN void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); -#else -void UnityFail(const char* message, const UNITY_LINE_TYPE line); -void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); -#endif - -void UnityMessage(const char* message, const UNITY_LINE_TYPE line); - -#ifndef UNITY_EXCLUDE_FLOAT -void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); -#endif - -#ifndef UNITY_EXCLUDE_DOUBLE -void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); -#endif - -/*------------------------------------------------------- - * Helpers - *-------------------------------------------------------*/ - -UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size); -#ifndef UNITY_EXCLUDE_FLOAT -UNITY_INTERNAL_PTR UnityFloatToPtr(const float num); -#endif -#ifndef UNITY_EXCLUDE_DOUBLE -UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); -#endif - -/*------------------------------------------------------- - * Error Strings We Might Need - *-------------------------------------------------------*/ - -extern const char UnityStrOk[]; -extern const char UnityStrPass[]; -extern const char UnityStrFail[]; -extern const char UnityStrIgnore[]; - -extern const char UnityStrErrFloat[]; -extern const char UnityStrErrDouble[]; -extern const char UnityStrErr64[]; -extern const char UnityStrErrShorthand[]; - -/*------------------------------------------------------- - * Test Running Macros - *-------------------------------------------------------*/ - -#ifndef UNITY_EXCLUDE_SETJMP_H -#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0) -#define TEST_ABORT() longjmp(Unity.AbortFrame, 1) -#else -#define TEST_PROTECT() 1 -#define TEST_ABORT() return -#endif - -/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ -#ifndef RUN_TEST -#ifdef __STDC_VERSION__ -#if __STDC_VERSION__ >= 199901L -#define UNITY_SUPPORT_VARIADIC_MACROS -#endif -#endif -#ifdef UNITY_SUPPORT_VARIADIC_MACROS -#define RUN_TEST(...) RUN_TEST_AT_LINE(__VA_ARGS__, __LINE__, throwaway) -#define RUN_TEST_AT_LINE(func, line, ...) UnityDefaultTestRun(func, #func, line) -#endif -#endif - -/* If we can't do the tricky version, we'll just have to require them to always include the line number */ -#ifndef RUN_TEST -#ifdef CMOCK -#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) -#else -#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) -#endif -#endif - -#define TEST_LINE_NUM (Unity.CurrentTestLineNumber) -#define TEST_IS_IGNORED (Unity.CurrentTestIgnored) -#define UNITY_NEW_TEST(a) \ - Unity.CurrentTestName = (a); \ - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ - Unity.NumberOfTests++; - -#ifndef UNITY_BEGIN -#define UNITY_BEGIN() UnityBegin(__FILE__) -#endif - -#ifndef UNITY_END -#define UNITY_END() UnityEnd() -#endif - -#ifndef UNITY_SHORTHAND_AS_INT -#ifndef UNITY_SHORTHAND_AS_MEM -#ifndef UNITY_SHORTHAND_AS_NONE -#ifndef UNITY_SHORTHAND_AS_RAW -#define UNITY_SHORTHAND_AS_OLD -#endif -#endif -#endif -#endif - -/*----------------------------------------------- - * Command Line Argument Support - *-----------------------------------------------*/ - -#ifdef UNITY_USE_COMMAND_LINE_ARGS -int UnityParseOptions(int argc, char** argv); -int UnityTestMatches(void); -#endif - -/*------------------------------------------------------- - * Basic Fail and Ignore - *-------------------------------------------------------*/ - -#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) - -/*------------------------------------------------------- - * Test Asserts - *-------------------------------------------------------*/ - -#define UNITY_TEST_ASSERT(condition, line, message) do { if (condition) { /* nothing*/ } else { UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message)); } } while (0) -#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) == 0), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) != 0), (UNITY_LINE_TYPE)(line), (message)) - -#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) - -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - - -#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) -#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL) - -#ifdef UNITY_SUPPORT_64 -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#else -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#endif - -#ifdef UNITY_EXCLUDE_FLOAT -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#else -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) -#endif - -#ifdef UNITY_EXCLUDE_DOUBLE -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#else -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) -#endif - -/* End of UNITY_INTERNALS_H */ -#endif diff --git a/taskchampion/integration-tests/src/bindings_tests/uuid.c b/taskchampion/integration-tests/src/bindings_tests/uuid.c deleted file mode 100644 index 83b02482d..000000000 --- a/taskchampion/integration-tests/src/bindings_tests/uuid.c +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include "unity.h" -#include "taskchampion.h" - -// creating UUIDs does not crash -static void test_uuid_creation(void) { - tc_uuid_new_v4(); - tc_uuid_nil(); -} - -// converting UUIDs to a buf works -static void test_uuid_to_buf(void) { - TEST_ASSERT_EQUAL(TC_UUID_STRING_BYTES, 36); - - TCUuid u2 = tc_uuid_nil(); - - char u2str[TC_UUID_STRING_BYTES]; - tc_uuid_to_buf(u2, u2str); - TEST_ASSERT_EQUAL_MEMORY("00000000-0000-0000-0000-000000000000", u2str, TC_UUID_STRING_BYTES); -} - -// converting UUIDs to a buf works -static void test_uuid_to_str(void) { - TCUuid u = tc_uuid_nil(); - TCString s = tc_uuid_to_str(u); - TEST_ASSERT_EQUAL_STRING( - "00000000-0000-0000-0000-000000000000", - tc_string_content(&s)); - tc_string_free(&s); -} - -// converting valid UUIDs from string works -static void test_uuid_valid_from_str(void) { - TCUuid u; - char *ustr = "23cb25e0-5d1a-4932-8131-594ac6d3a843"; - TEST_ASSERT_EQUAL(TC_RESULT_OK, tc_uuid_from_str(tc_string_borrow(ustr), &u)); - TEST_ASSERT_EQUAL(0x23, u.bytes[0]); - TEST_ASSERT_EQUAL(0x43, u.bytes[15]); -} - -// converting invalid UUIDs from string fails as expected -static void test_uuid_invalid_string_fails(void) { - TCUuid u; - char *ustr = "not-a-valid-uuid"; - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_uuid_from_str(tc_string_borrow(ustr), &u)); -} - -// converting invalid UTF-8 UUIDs from string fails as expected -static void test_uuid_bad_utf8(void) { - TCUuid u; - char *ustr = "\xf0\x28\x8c\xbc"; - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_uuid_from_str(tc_string_borrow(ustr), &u)); -} - -// converting a string with embedded NUL fails as expected -static void test_uuid_embedded_nul(void) { - TCUuid u; - TEST_ASSERT_EQUAL(TC_RESULT_ERROR, tc_uuid_from_str(tc_string_clone_with_len("ab\0de", 5), &u)); -} - -int uuid_tests(void) { - UNITY_BEGIN(); - // each test case above should be named here, in order. - RUN_TEST(test_uuid_creation); - RUN_TEST(test_uuid_valid_from_str); - RUN_TEST(test_uuid_to_buf); - RUN_TEST(test_uuid_to_str); - RUN_TEST(test_uuid_invalid_string_fails); - RUN_TEST(test_uuid_bad_utf8); - RUN_TEST(test_uuid_embedded_nul); - return UNITY_END(); -} diff --git a/taskchampion/integration-tests/src/lib.rs b/taskchampion/integration-tests/src/lib.rs deleted file mode 100644 index 3d76f3008..000000000 --- a/taskchampion/integration-tests/src/lib.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod bindings_tests; -pub use taskchampion_lib::*; diff --git a/taskchampion/integration-tests/tests/bindings.rs b/taskchampion/integration-tests/tests/bindings.rs deleted file mode 100644 index a121dd721..000000000 --- a/taskchampion/integration-tests/tests/bindings.rs +++ /dev/null @@ -1,31 +0,0 @@ -use lazy_static::lazy_static; -use std::sync::Mutex; -use tempfile::TempDir; - -lazy_static! { - // the C library running the tests is not reentrant, so we use a mutex to ensure that only one - // test runs at a time. - static ref MUTEX: Mutex<()> = Mutex::new(()); -} - -macro_rules! suite( - { $s:ident } => { - #[test] - fn $s() { - let tmp_dir = TempDir::new().expect("TempDir failed"); - let (res, output) = { - let _guard = MUTEX.lock().unwrap(); - // run the tests in the temp dir (NOTE: this must be inside - // the mutex guard!) - std::env::set_current_dir(tmp_dir.as_ref()).unwrap(); - integration_tests::bindings_tests::$s() - }; - println!("{}", output); - if res != 0 { - assert!(false, "test failed"); - } - } - }; -); - -include!(concat!(env!("OUT_DIR"), "/bindings_test_suites.rs")); diff --git a/taskchampion/integration-tests/tests/cross-sync.rs b/taskchampion/integration-tests/tests/cross-sync.rs deleted file mode 100644 index 6cac3c293..000000000 --- a/taskchampion/integration-tests/tests/cross-sync.rs +++ /dev/null @@ -1,66 +0,0 @@ -use pretty_assertions::assert_eq; -use taskchampion::{Replica, ServerConfig, Status, StorageConfig}; -use tempfile::TempDir; - -#[test] -fn cross_sync() -> anyhow::Result<()> { - // set up two replicas, and demonstrate replication between them - let mut rep1 = Replica::new(StorageConfig::InMemory.into_storage()?); - let mut rep2 = Replica::new(StorageConfig::InMemory.into_storage()?); - - let tmp_dir = TempDir::new().expect("TempDir failed"); - let server_config = ServerConfig::Local { - server_dir: tmp_dir.path().to_path_buf(), - }; - let mut server = server_config.into_server()?; - - // add some tasks on rep1 - let t1 = rep1.new_task(Status::Pending, "test 1".into())?; - let t2 = rep1.new_task(Status::Pending, "test 2".into())?; - - // modify t1 - let mut t1 = t1.into_mut(&mut rep1); - t1.start()?; - let t1 = t1.into_immut(); - - rep1.sync(&mut server, false)?; - rep2.sync(&mut server, false)?; - - // those tasks should exist on rep2 now - let t12 = rep2 - .get_task(t1.get_uuid())? - .expect("expected task 1 on rep2"); - let t22 = rep2 - .get_task(t2.get_uuid())? - .expect("expected task 2 on rep2"); - - assert_eq!(t12.get_description(), "test 1"); - assert_eq!(t12.is_active(), true); - assert_eq!(t22.get_description(), "test 2"); - assert_eq!(t22.is_active(), false); - - // make non-conflicting changes on the two replicas - let mut t2 = t2.into_mut(&mut rep1); - t2.set_status(Status::Completed)?; - let t2 = t2.into_immut(); - - let mut t12 = t12.into_mut(&mut rep2); - t12.set_status(Status::Completed)?; - - // sync those changes back and forth - rep1.sync(&mut server, false)?; // rep1 -> server - rep2.sync(&mut server, false)?; // server -> rep2, rep2 -> server - rep1.sync(&mut server, false)?; // server -> rep1 - - let t1 = rep1 - .get_task(t1.get_uuid())? - .expect("expected task 1 on rep1"); - assert_eq!(t1.get_status(), Status::Completed); - - let t22 = rep2 - .get_task(t2.get_uuid())? - .expect("expected task 2 on rep2"); - assert_eq!(t22.get_status(), Status::Completed); - - Ok(()) -} diff --git a/taskchampion/integration-tests/tests/update-and-delete-sync.rs b/taskchampion/integration-tests/tests/update-and-delete-sync.rs deleted file mode 100644 index 91727c7e1..000000000 --- a/taskchampion/integration-tests/tests/update-and-delete-sync.rs +++ /dev/null @@ -1,72 +0,0 @@ -use taskchampion::chrono::{TimeZone, Utc}; -use taskchampion::{Replica, ServerConfig, Status, StorageConfig}; -use tempfile::TempDir; - -#[test] -fn update_and_delete_sync_delete_first() -> anyhow::Result<()> { - update_and_delete_sync(true) -} - -#[test] -fn update_and_delete_sync_update_first() -> anyhow::Result<()> { - update_and_delete_sync(false) -} - -/// Test what happens when an update is sync'd into a repo after a task is deleted. -/// If delete_first, then the deletion is sync'd to the server first; otherwise -/// the update is sync'd first. Either way, the task is gone. -fn update_and_delete_sync(delete_first: bool) -> anyhow::Result<()> { - // set up two replicas, and demonstrate replication between them - let mut rep1 = Replica::new(StorageConfig::InMemory.into_storage()?); - let mut rep2 = Replica::new(StorageConfig::InMemory.into_storage()?); - - let tmp_dir = TempDir::new().expect("TempDir failed"); - let mut server = ServerConfig::Local { - server_dir: tmp_dir.path().to_path_buf(), - } - .into_server()?; - - // add a task on rep1, and sync it to rep2 - let t = rep1.new_task(Status::Pending, "test task".into())?; - let u = t.get_uuid(); - - rep1.sync(&mut server, false)?; - rep2.sync(&mut server, false)?; - - // mark the task as deleted, long in the past, on rep2 - { - let mut t = rep2.get_task(u)?.unwrap().into_mut(&mut rep2); - t.delete()?; - t.set_modified(Utc.ymd(1980, 1, 1).and_hms(0, 0, 0))?; - } - - // sync it back to rep1 - rep2.sync(&mut server, false)?; - rep1.sync(&mut server, false)?; - - // expire the task on rep1 and check that it is gone locally - rep1.expire_tasks()?; - assert!(rep1.get_task(u)?.is_none()); - - // modify the task on rep2 - { - let mut t = rep2.get_task(u)?.unwrap().into_mut(&mut rep2); - t.set_description("modified".to_string())?; - } - - // sync back and forth - if delete_first { - rep1.sync(&mut server, false)?; - } - rep2.sync(&mut server, false)?; - rep1.sync(&mut server, false)?; - if !delete_first { - rep2.sync(&mut server, false)?; - } - - // check that the task is gone on both replicas - assert!(rep1.get_task(u)?.is_none()); - assert!(rep2.get_task(u)?.is_none()); - - Ok(()) -} diff --git a/taskchampion/scripts/changelog.py b/taskchampion/scripts/changelog.py deleted file mode 100755 index 0eac4fa35..000000000 --- a/taskchampion/scripts/changelog.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python3 -import os -import argparse -import datetime -import subprocess -from typing import List - -def ymd(): - return datetime.datetime.now().strftime("%Y-%m-%d") - -def git_current_branch() -> str : - out = subprocess.check_output(["git", "branch", "--show-current"]) - return out.strip().decode("utf-8") - -def get_dir() -> str: - here = os.path.dirname(os.path.abspath(__file__)) - return os.path.join( - here, - "../.changelogs") - -def get_changefiles() -> List[str]: - changedir = get_dir() - changefiles = [] - for f in os.listdir(changedir): - if f.endswith(".md") and not f.startswith("."): - changefiles.append(os.path.join(changedir, f)) - - return changefiles - -def cmd_add(args): - text = args.text.strip() - if not text.startswith("- "): - text = "- %s" % text - - timestamp = ymd() - branchname = git_current_branch() - fname = os.path.join(get_dir(), "%s-%s.md" % (timestamp, branchname)) - with open(fname, "a") as f: - f.write(text) - f.write("\n") - -def cmd_build(args): - print("## x.y.z - %s" % (ymd())) - for e in get_changefiles(): - print(open(e).read().strip()) - -def main() -> None: - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(title='Sub commands', dest='command') - subparsers.required = True - - parser_add = subparsers.add_parser('add') - parser_add.add_argument("text") - parser_add.set_defaults(func=cmd_add) - - parser_build = subparsers.add_parser('build') - parser_build.set_defaults(func=cmd_build) - - args = parser.parse_args() - args.func(args) - - -if __name__ == "__main__": - main() diff --git a/taskchampion/taskchampion/Cargo.toml b/taskchampion/taskchampion/Cargo.toml deleted file mode 100644 index 7ff582dd7..000000000 --- a/taskchampion/taskchampion/Cargo.toml +++ /dev/null @@ -1,58 +0,0 @@ -[package] -name = "taskchampion" -version = "0.4.1" -authors = ["Dustin J. Mitchell "] -description = "Personal task-tracking" -homepage = "https://gothenburgbitfactory.github.io/taskwarrior/taskchampion/" -documentation = "https://docs.rs/crate/taskchampion" -repository = "https://github.com/GothenburgBitFactory/taskwarrior" -readme = "../README.md" -license = "MIT" -edition = "2021" -rust-version = "1.70.0" - -[features] -default = ["server-sync", "server-gcp"] - -# Support for sync to a server -server-sync = ["encryption", "dep:ureq", "dep:url"] -# Support for sync to GCP -server-gcp = ["cloud", "encryption", "dep:google-cloud-storage", "dep:tokio"] -# (private) Support for sync protocol encryption -encryption = ["dep:ring"] -# (private) Generic support for cloud sync -cloud = [] - -[package.metadata.docs.rs] -all-features = true - -[dependencies] -uuid.workspace = true -serde.workspace = true -serde_json.workspace = true -chrono.workspace = true -anyhow.workspace = true -thiserror.workspace = true -ureq.workspace = true -log.workspace = true -rusqlite.workspace = true -strum.workspace = true -strum_macros.workspace = true -flate2.workspace = true -byteorder.workspace = true -ring.workspace = true -google-cloud-storage.workspace = true -tokio.workspace = true -url.workspace = true - -google-cloud-storage.optional = true -tokio.optional = true -ureq.optional = true -url.optional = true -ring.optional = true - -[dev-dependencies] -proptest.workspace = true -tempfile.workspace = true -rstest.workspace = true -pretty_assertions.workspace = true diff --git a/taskchampion/taskchampion/src/depmap.rs b/taskchampion/taskchampion/src/depmap.rs deleted file mode 100644 index fe4d5df6f..000000000 --- a/taskchampion/taskchampion/src/depmap.rs +++ /dev/null @@ -1,81 +0,0 @@ -use uuid::Uuid; - -/// DependencyMap stores information on task dependencies between pending tasks. -/// -/// This information requires a scan of the working set to generate, so it is -/// typically calculated once and re-used. -#[derive(Debug, PartialEq, Eq)] -pub struct DependencyMap { - /// Edges of the dependency graph. If (a, b) is in this array, then task a depends on tsak b. - edges: Vec<(Uuid, Uuid)>, -} - -impl DependencyMap { - /// Create a new, empty DependencyMap. - pub(super) fn new() -> Self { - Self { edges: Vec::new() } - } - - /// Add a dependency of a on b. - pub(super) fn add_dependency(&mut self, a: Uuid, b: Uuid) { - self.edges.push((a, b)); - } - - /// Return an iterator of Uuids on which task `deps_of` depends. This is equivalent to - /// `task.get_dependencies()`. - pub fn dependencies(&self, dep_of: Uuid) -> impl Iterator + '_ { - self.edges - .iter() - .filter_map(move |(a, b)| if a == &dep_of { Some(*b) } else { None }) - } - - /// Return an iterator of Uuids of tasks that depend on `dep_on` - /// `task.get_dependencies()`. - pub fn dependents(&self, dep_on: Uuid) -> impl Iterator + '_ { - self.edges - .iter() - .filter_map(move |(a, b)| if b == &dep_on { Some(*a) } else { None }) - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - use std::collections::HashSet; - - #[test] - fn dependencies() { - let t = Uuid::new_v4(); - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - let mut dm = DependencyMap::new(); - - dm.add_dependency(t, uuid1); - dm.add_dependency(t, uuid2); - dm.add_dependency(Uuid::new_v4(), t); - dm.add_dependency(Uuid::new_v4(), uuid1); - dm.add_dependency(uuid2, Uuid::new_v4()); - - assert_eq!( - dm.dependencies(t).collect::>(), - set![uuid1, uuid2] - ); - } - - #[test] - fn dependents() { - let t = Uuid::new_v4(); - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - let mut dm = DependencyMap::new(); - - dm.add_dependency(uuid1, t); - dm.add_dependency(uuid2, t); - dm.add_dependency(t, Uuid::new_v4()); - dm.add_dependency(Uuid::new_v4(), uuid1); - dm.add_dependency(uuid2, Uuid::new_v4()); - - assert_eq!(dm.dependents(t).collect::>(), set![uuid1, uuid2]); - } -} diff --git a/taskchampion/taskchampion/src/errors.rs b/taskchampion/taskchampion/src/errors.rs deleted file mode 100644 index 031c6ce93..000000000 --- a/taskchampion/taskchampion/src/errors.rs +++ /dev/null @@ -1,48 +0,0 @@ -use std::io; -use thiserror::Error; - -#[derive(Debug, Error)] -#[non_exhaustive] -/// Errors returned from taskchampion operations -pub enum Error { - /// A server-related error - #[error("Server Error: {0}")] - Server(String), - /// A task-database-related error - #[error("Task Database Error: {0}")] - Database(String), - /// An error specifically indicating that the local replica cannot - /// be synchronized with the sever, due to being out of date or some - /// other irrecoverable error. - #[error("Local replica is out of sync with the server")] - OutOfSync, - /// A usage error - #[error("Usage Error: {0}")] - Usage(String), - /// A general error. - #[error(transparent)] - Other(#[from] anyhow::Error), -} - -/// Convert private and third party errors into Error::Other. -macro_rules! other_error { - ( $error:ty ) => { - impl From<$error> for Error { - fn from(err: $error) -> Self { - Self::Other(err.into()) - } - } - }; -} -#[cfg(feature = "server-sync")] -other_error!(ureq::Error); -other_error!(io::Error); -other_error!(serde_json::Error); -other_error!(rusqlite::Error); -other_error!(crate::storage::sqlite::SqliteError); -#[cfg(feature = "server-gcp")] -other_error!(google_cloud_storage::http::Error); -#[cfg(feature = "server-gcp")] -other_error!(google_cloud_storage::client::google_cloud_auth::error::Error); - -pub type Result = std::result::Result; diff --git a/taskchampion/taskchampion/src/lib.rs b/taskchampion/taskchampion/src/lib.rs deleted file mode 100644 index c9408586f..000000000 --- a/taskchampion/taskchampion/src/lib.rs +++ /dev/null @@ -1,82 +0,0 @@ -#![deny(clippy::all)] -/*! - -This crate implements the core of TaskChampion, the [replica](crate::Replica). - -Users of this crate can manipulate a task database using this API, including synchronizing that task database with others via a synchronization server. - -Example uses of this crate: - * user interfaces for task management, such as mobile apps, web apps, or command-line interfaces - * integrations for task management, such as synchronization with ticket-tracking systems or - request forms. - -# Replica - -A TaskChampion replica is a local copy of a user's task data. As the name suggests, several -replicas of the same data can exist (such as on a user's laptop and on their phone) and can -synchronize with one another. - -Replicas are accessed using the [`Replica`](crate::Replica) type. - -# Task Storage - -Replicas access the task database via a [storage object](crate::storage::Storage). -Create a storage object with [`StorageConfig`](crate::storage::StorageConfig). - -The [`storage`](crate::storage) module supports pluggable storage for a replica's data. -An implementation is provided, but users of this crate can provide their own implementation as well. - -# Server - -Replica synchronization takes place against a server. -Create a server with [`ServerConfig`](crate::ServerConfig). - -The [`server`](crate::server) module defines the interface a server must meet. -Users can define their own server impelementations. - -# Feature Flags - -Support for some optional functionality is controlled by feature flags. - -Sync server client support: - - * `server-gcp` - sync to Google Cloud Platform - * `server-sync` - sync to the taskchampion-sync-server - -# See Also - -See the [TaskChampion Book](http://taskchampion.github.com/taskchampion) -for more information about the design and usage of the tool. - -# Minimum Supported Rust Version (MSRV) - -This crate supports Rust version 1.70.0 and higher. - - */ - -// NOTE: it's important that this 'mod' comes first so that the macros can be used in other modules -mod macros; - -mod depmap; -mod errors; -mod replica; -pub mod server; -pub mod storage; -mod task; -mod taskdb; -mod utils; -mod workingset; - -pub use depmap::DependencyMap; -pub use errors::Error; -pub use replica::Replica; -pub use server::{Server, ServerConfig}; -pub use storage::StorageConfig; -pub use task::{utc_timestamp, Annotation, Status, Tag, Task, TaskMut}; -pub use workingset::WorkingSet; - -/// Re-exported type from the `uuid` crate, for ease of compatibility for consumers of this crate. -pub use uuid::Uuid; - -/// Re-exported chrono module. -pub use chrono; diff --git a/taskchampion/taskchampion/src/macros.rs b/taskchampion/taskchampion/src/macros.rs deleted file mode 100644 index eb34b4640..000000000 --- a/taskchampion/taskchampion/src/macros.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![macro_use] - -/// Create a hashset, similar to vec! -// NOTE: in Rust 1.56.0, this can be changed to HashSet::from([..]) -#[cfg(test)] -macro_rules! set( - { $($key:expr),* $(,)? } => { - { - #[allow(unused_mut)] - let mut s = ::std::collections::HashSet::new(); - $( - s.insert($key); - )* - s - } - }; -); diff --git a/taskchampion/taskchampion/src/replica.rs b/taskchampion/taskchampion/src/replica.rs deleted file mode 100644 index bad6cceba..000000000 --- a/taskchampion/taskchampion/src/replica.rs +++ /dev/null @@ -1,677 +0,0 @@ -use crate::depmap::DependencyMap; -use crate::errors::Result; -use crate::server::{Server, SyncOp}; -use crate::storage::{ReplicaOp, Storage, TaskMap}; -use crate::task::{Status, Task}; -use crate::taskdb::TaskDb; -use crate::workingset::WorkingSet; -use anyhow::Context; -use chrono::{Duration, Utc}; -use log::trace; -use std::collections::HashMap; -use std::rc::Rc; -use uuid::Uuid; - -/// A replica represents an instance of a user's task data, providing an easy interface -/// for querying and modifying that data. -/// -/// ## Tasks -/// -/// Tasks are uniquely identified by UUIDs. -/// Most task modifications are performed via the [`Task`](crate::Task) and -/// [`TaskMut`](crate::TaskMut) types. Use of two types for tasks allows easy -/// read-only manipulation of lots of tasks, with exclusive access required only -/// for modifications. -/// -/// ## Working Set -/// -/// A replica maintains a "working set" of tasks that are of current concern to the user, -/// specifically pending tasks. These are indexed with small, easy-to-type integers. Newly -/// pending tasks are automatically added to the working set, and the working set is "renumbered" -/// during the garbage-collection process. -pub struct Replica { - taskdb: TaskDb, - - /// If true, this replica has already added an undo point. - added_undo_point: bool, - - /// The dependency map for this replica, if it has been calculated. - depmap: Option>, -} - -impl Replica { - pub fn new(storage: Box) -> Replica { - Replica { - taskdb: TaskDb::new(storage), - added_undo_point: false, - depmap: None, - } - } - - #[cfg(test)] - pub fn new_inmemory() -> Replica { - Replica::new(Box::new(crate::storage::InMemoryStorage::new())) - } - - /// Update an existing task. If the value is Some, the property is added or updated. If the - /// value is None, the property is deleted. It is not an error to delete a nonexistent - /// property. - /// - /// This is a low-level method, and requires knowledge of the Task data model. Prefer to - /// use the [`TaskMut`] methods to modify tasks, where possible. - pub fn update_task( - &mut self, - uuid: Uuid, - property: S1, - value: Option, - ) -> Result - where - S1: Into, - S2: Into, - { - self.add_undo_point(false)?; - self.taskdb.apply(SyncOp::Update { - uuid, - property: property.into(), - value: value.map(|v| v.into()), - timestamp: Utc::now(), - }) - } - - /// Add the given uuid to the working set, returning its index. - pub(crate) fn add_to_working_set(&mut self, uuid: Uuid) -> Result { - self.taskdb.add_to_working_set(uuid) - } - - /// Get all tasks represented as a map keyed by UUID - pub fn all_tasks(&mut self) -> Result> { - let depmap = self.dependency_map(false)?; - let mut res = HashMap::new(); - for (uuid, tm) in self.taskdb.all_tasks()?.drain(..) { - res.insert(uuid, Task::new(uuid, tm, depmap.clone())); - } - Ok(res) - } - - /// Get the UUIDs of all tasks - pub fn all_task_uuids(&mut self) -> Result> { - self.taskdb.all_task_uuids() - } - - /// Get the "working set" for this replica. This is a snapshot of the current state, - /// and it is up to the caller to decide how long to store this value. - pub fn working_set(&mut self) -> Result { - Ok(WorkingSet::new(self.taskdb.working_set()?)) - } - - /// Get the dependency map for all pending tasks. - /// - /// A task dependency is recognized when a task in the working set depends on a task with - /// status equal to Pending. - /// - /// The data in this map is cached when it is first requested and may not contain modifications - /// made locally in this Replica instance. The result is reference-counted and may - /// outlive the Replica. - /// - /// If `force` is true, then the result is re-calculated from the current state of the replica, - /// although previously-returned dependency maps are not updated. - pub fn dependency_map(&mut self, force: bool) -> Result> { - if force || self.depmap.is_none() { - // note: we can't use self.get_task here, as that depends on a - // DependencyMap - - let mut dm = DependencyMap::new(); - // temporary cache tracking whether tasks are considered Pending or not. - let mut is_pending_cache: HashMap = HashMap::new(); - let ws = self.working_set()?; - // for each task in the working set - for i in 1..=ws.largest_index() { - // get the task UUID - if let Some(u) = ws.by_index(i) { - // get the task - if let Some(taskmap) = self.taskdb.get_task(u)? { - // search the task's keys - for p in taskmap.keys() { - // for one matching `dep_..` - if let Some(dep_str) = p.strip_prefix("dep_") { - // and extract the UUID from the key - if let Ok(dep) = Uuid::parse_str(dep_str) { - // the dependency is pending if - let dep_pending = { - // we've determined this before and cached the result - if let Some(dep_pending) = is_pending_cache.get(&dep) { - *dep_pending - } else if let Some(dep_taskmap) = - // or if we get the task - self.taskdb.get_task(dep)? - { - // and its status is "pending" - let dep_pending = matches!( - dep_taskmap - .get("status") - .map(|tm| Status::from_taskmap(tm)), - Some(Status::Pending) - ); - is_pending_cache.insert(dep, dep_pending); - dep_pending - } else { - false - } - }; - if dep_pending { - dm.add_dependency(u, dep); - } - } - } - } - } - } - } - self.depmap = Some(Rc::new(dm)); - } - - // at this point self.depmap is guaranteed to be Some(_) - Ok(self.depmap.as_ref().unwrap().clone()) - } - - /// Get an existing task by its UUID - pub fn get_task(&mut self, uuid: Uuid) -> Result> { - let depmap = self.dependency_map(false)?; - Ok(self - .taskdb - .get_task(uuid)? - .map(move |tm| Task::new(uuid, tm, depmap))) - } - - /// Create a new task. - pub fn new_task(&mut self, status: Status, description: String) -> Result { - let uuid = Uuid::new_v4(); - self.add_undo_point(false)?; - let taskmap = self.taskdb.apply(SyncOp::Create { uuid })?; - let depmap = self.dependency_map(false)?; - let mut task = Task::new(uuid, taskmap, depmap).into_mut(self); - task.set_description(description)?; - task.set_status(status)?; - task.set_entry(Some(Utc::now()))?; - trace!("task {} created", uuid); - Ok(task.into_immut()) - } - - /// Create a new, empty task with the given UUID. This is useful for importing tasks, but - /// otherwise should be avoided in favor of `new_task`. If the task already exists, this - /// does nothing and returns the existing task. - pub fn import_task_with_uuid(&mut self, uuid: Uuid) -> Result { - self.add_undo_point(false)?; - let taskmap = self.taskdb.apply(SyncOp::Create { uuid })?; - let depmap = self.dependency_map(false)?; - Ok(Task::new(uuid, taskmap, depmap)) - } - - /// Delete a task. The task must exist. Note that this is different from setting status to - /// Deleted; this is the final purge of the task. This is not a public method as deletion - /// should only occur through expiration. - fn delete_task(&mut self, uuid: Uuid) -> Result<()> { - self.add_undo_point(false)?; - self.taskdb.apply(SyncOp::Delete { uuid })?; - trace!("task {} deleted", uuid); - Ok(()) - } - - /// Synchronize this replica against the given server. The working set is rebuilt after - /// this occurs, but without renumbering, so any newly-pending tasks should appear in - /// the working set. - /// - /// If `avoid_snapshots` is true, the sync operations produces a snapshot only when the server - /// indicate it is urgent (snapshot urgency "high"). This allows time for other replicas to - /// create a snapshot before this one does. - /// - /// Set this to true on systems more constrained in CPU, memory, or bandwidth than a typical desktop - /// system - pub fn sync(&mut self, server: &mut Box, avoid_snapshots: bool) -> Result<()> { - self.taskdb - .sync(server, avoid_snapshots) - .context("Failed to synchronize with server")?; - self.rebuild_working_set(false) - .context("Failed to rebuild working set after sync")?; - Ok(()) - } - - /// Return undo local operations until the most recent UndoPoint, returning an empty Vec if there are no - /// local operations to undo. - pub fn get_undo_ops(&mut self) -> Result> { - self.taskdb.get_undo_ops() - } - - /// Undo local operations in storage, returning a boolean indicating success. - pub fn commit_undo_ops(&mut self, undo_ops: Vec) -> Result { - self.taskdb.commit_undo_ops(undo_ops) - } - - /// Rebuild this replica's working set, based on whether tasks are pending or not. If - /// `renumber` is true, then existing tasks may be moved to new working-set indices; in any - /// case, on completion all pending and recurring tasks are in the working set and all tasks - /// with other statuses are not. - pub fn rebuild_working_set(&mut self, renumber: bool) -> Result<()> { - let pending = String::from(Status::Pending.to_taskmap()); - let recurring = String::from(Status::Recurring.to_taskmap()); - self.taskdb.rebuild_working_set( - |t| { - if let Some(st) = t.get("status") { - st == &pending || st == &recurring - } else { - false - } - }, - renumber, - )?; - Ok(()) - } - - /// Expire old, deleted tasks. - /// - /// Expiration entails removal of tasks from the replica. Any modifications that occur after - /// the deletion (such as operations synchronized from other replicas) will do nothing. - /// - /// Tasks are eligible for expiration when they have status Deleted and have not been modified - /// for 180 days (about six months). Note that completed tasks are not eligible. - pub fn expire_tasks(&mut self) -> Result<()> { - let six_mos_ago = Utc::now() - Duration::days(180); - self.all_tasks()? - .iter() - .filter(|(_, t)| t.get_status() == Status::Deleted) - .filter(|(_, t)| { - if let Some(m) = t.get_modified() { - m < six_mos_ago - } else { - false - } - }) - .try_for_each(|(u, _)| self.delete_task(*u))?; - Ok(()) - } - - /// Add an UndoPoint, if one has not already been added by this Replica. This occurs - /// automatically when a change is made. The `force` flag allows forcing a new UndoPoint - /// even if one has already been created by this Replica, and may be useful when a Replica - /// instance is held for a long time and used to apply more than one user-visible change. - pub fn add_undo_point(&mut self, force: bool) -> Result<()> { - if force || !self.added_undo_point { - self.taskdb.add_undo_point()?; - self.added_undo_point = true; - } - Ok(()) - } - - /// Get the number of operations local to this replica and not yet synchronized to the server. - pub fn num_local_operations(&mut self) -> Result { - self.taskdb.num_operations() - } - - /// Get the number of undo points available (number of times `undo` will succeed). - pub fn num_undo_points(&mut self) -> Result { - self.taskdb.num_undo_points() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::storage::ReplicaOp; - use crate::task::Status; - use chrono::TimeZone; - use pretty_assertions::assert_eq; - use std::collections::HashSet; - use uuid::Uuid; - - #[test] - fn new_task() { - let mut rep = Replica::new_inmemory(); - - let t = rep.new_task(Status::Pending, "a task".into()).unwrap(); - assert_eq!(t.get_description(), String::from("a task")); - assert_eq!(t.get_status(), Status::Pending); - assert!(t.get_modified().is_some()); - } - - #[test] - fn modify_task() { - let mut rep = Replica::new_inmemory(); - - let t = rep.new_task(Status::Pending, "a task".into()).unwrap(); - - let mut t = t.into_mut(&mut rep); - t.set_description(String::from("past tense")).unwrap(); - t.set_status(Status::Completed).unwrap(); - // check that values have changed on the TaskMut - assert_eq!(t.get_description(), "past tense"); - assert_eq!(t.get_status(), Status::Completed); - - // check that values have changed after into_immut - let t = t.into_immut(); - assert_eq!(t.get_description(), "past tense"); - assert_eq!(t.get_status(), Status::Completed); - - // check that values have changed in storage, too - let t = rep.get_task(t.get_uuid()).unwrap().unwrap(); - assert_eq!(t.get_description(), "past tense"); - assert_eq!(t.get_status(), Status::Completed); - - // and check for the corresponding operations, cleaning out the timestamps - // and modified properties as these are based on the current time - let now = Utc::now(); - let clean_op = |op: ReplicaOp| { - if let ReplicaOp::Update { - uuid, - property, - mut old_value, - mut value, - .. - } = op - { - // rewrite automatically-created dates to "just-now" for ease - // of testing - if property == "modified" || property == "end" || property == "entry" { - if value.is_some() { - value = Some("just-now".into()); - } - if old_value.is_some() { - old_value = Some("just-now".into()); - } - } - ReplicaOp::Update { - uuid, - property, - old_value, - value, - timestamp: now, - } - } else { - op - } - }; - assert_eq!( - rep.taskdb - .operations() - .drain(..) - .map(clean_op) - .collect::>(), - vec![ - ReplicaOp::UndoPoint, - ReplicaOp::Create { uuid: t.get_uuid() }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "modified".into(), - old_value: None, - value: Some("just-now".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "description".into(), - old_value: None, - value: Some("a task".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "status".into(), - old_value: None, - value: Some("pending".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "entry".into(), - old_value: None, - value: Some("just-now".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "modified".into(), - old_value: Some("just-now".into()), - value: Some("just-now".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "description".into(), - old_value: Some("a task".into()), - value: Some("past tense".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "end".into(), - old_value: None, - value: Some("just-now".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid: t.get_uuid(), - property: "status".into(), - old_value: Some("pending".into()), - value: Some("completed".into()), - timestamp: now, - }, - ] - ); - - // num_local_operations includes all but the undo point - assert_eq!(rep.num_local_operations().unwrap(), 9); - - // num_undo_points includes only the undo point - assert_eq!(rep.num_undo_points().unwrap(), 1); - } - - #[test] - fn delete_task() { - let mut rep = Replica::new_inmemory(); - - let t = rep.new_task(Status::Pending, "a task".into()).unwrap(); - let uuid = t.get_uuid(); - - rep.delete_task(uuid).unwrap(); - assert_eq!(rep.get_task(uuid).unwrap(), None); - } - - #[test] - fn get_and_modify() { - let mut rep = Replica::new_inmemory(); - - let t = rep - .new_task(Status::Pending, "another task".into()) - .unwrap(); - let uuid = t.get_uuid(); - - let t = rep.get_task(uuid).unwrap().unwrap(); - assert_eq!(t.get_description(), String::from("another task")); - - let mut t = t.into_mut(&mut rep); - t.set_status(Status::Deleted).unwrap(); - t.set_description("gone".into()).unwrap(); - - let t = rep.get_task(uuid).unwrap().unwrap(); - assert_eq!(t.get_status(), Status::Deleted); - assert_eq!(t.get_description(), "gone"); - - rep.rebuild_working_set(true).unwrap(); - - let ws = rep.working_set().unwrap(); - assert!(ws.by_uuid(t.get_uuid()).is_none()); - } - - #[test] - fn rebuild_working_set_includes_recurring() { - let mut rep = Replica::new_inmemory(); - - let t = rep - .new_task(Status::Completed, "another task".into()) - .unwrap(); - let uuid = t.get_uuid(); - - let t = rep.get_task(uuid).unwrap().unwrap(); - { - let mut t = t.into_mut(&mut rep); - t.set_status(Status::Recurring).unwrap(); - } - - rep.rebuild_working_set(true).unwrap(); - - let ws = rep.working_set().unwrap(); - assert!(ws.by_uuid(uuid).is_some()); - } - - #[test] - fn new_pending_adds_to_working_set() { - let mut rep = Replica::new_inmemory(); - - let t = rep - .new_task(Status::Pending, "to-be-pending".into()) - .unwrap(); - let uuid = t.get_uuid(); - - let ws = rep.working_set().unwrap(); - assert_eq!(ws.len(), 1); // only one non-none value - assert!(ws.by_index(0).is_none()); - assert_eq!(ws.by_index(1), Some(uuid)); - - let ws = rep.working_set().unwrap(); - assert_eq!(ws.by_uuid(t.get_uuid()), Some(1)); - } - - #[test] - fn new_recurring_adds_to_working_set() { - let mut rep = Replica::new_inmemory(); - - let t = rep - .new_task(Status::Recurring, "to-be-recurring".into()) - .unwrap(); - let uuid = t.get_uuid(); - - let ws = rep.working_set().unwrap(); - assert_eq!(ws.len(), 1); // only one non-none value - assert!(ws.by_index(0).is_none()); - assert_eq!(ws.by_index(1), Some(uuid)); - - let ws = rep.working_set().unwrap(); - assert_eq!(ws.by_uuid(t.get_uuid()), Some(1)); - } - - #[test] - fn get_does_not_exist() { - let mut rep = Replica::new_inmemory(); - let uuid = Uuid::new_v4(); - assert_eq!(rep.get_task(uuid).unwrap(), None); - } - - #[test] - fn expire() { - let mut rep = Replica::new_inmemory(); - let mut t; - - rep.new_task(Status::Pending, "keeper 1".into()).unwrap(); - rep.new_task(Status::Completed, "keeper 2".into()).unwrap(); - - t = rep.new_task(Status::Deleted, "keeper 3".into()).unwrap(); - { - let mut t = t.into_mut(&mut rep); - // set entry, with modification set as a side-effect - t.set_entry(Some(Utc::now())).unwrap(); - } - - t = rep.new_task(Status::Deleted, "goner".into()).unwrap(); - { - let mut t = t.into_mut(&mut rep); - t.set_modified(Utc.ymd(1980, 1, 1).and_hms(0, 0, 0)) - .unwrap(); - } - - rep.expire_tasks().unwrap(); - - for (_, t) in rep.all_tasks().unwrap() { - println!("got task {}", t.get_description()); - assert!(t.get_description().starts_with("keeper")); - } - } - - #[test] - fn dependency_map() { - let mut rep = Replica::new_inmemory(); - - let mut tasks = vec![]; - for _ in 0..4 { - tasks.push(rep.new_task(Status::Pending, "t".into()).unwrap()); - } - - let uuids: Vec<_> = tasks.iter().map(|t| t.get_uuid()).collect(); - - // t[3] depends on t[2], and t[1] - { - let mut t = tasks.pop().unwrap().into_mut(&mut rep); - t.add_dependency(uuids[2]).unwrap(); - t.add_dependency(uuids[1]).unwrap(); - } - - // t[2] depends on t[0] - { - let mut t = tasks.pop().unwrap().into_mut(&mut rep); - t.add_dependency(uuids[0]).unwrap(); - } - - // t[1] depends on t[0] - { - let mut t = tasks.pop().unwrap().into_mut(&mut rep); - t.add_dependency(uuids[0]).unwrap(); - } - - // generate the dependency map, forcing an update based on the newly-added - // dependencies - let dm = rep.dependency_map(true).unwrap(); - - assert_eq!( - dm.dependencies(uuids[3]).collect::>(), - set![uuids[1], uuids[2]] - ); - assert_eq!( - dm.dependencies(uuids[2]).collect::>(), - set![uuids[0]] - ); - assert_eq!( - dm.dependencies(uuids[1]).collect::>(), - set![uuids[0]] - ); - assert_eq!(dm.dependencies(uuids[0]).collect::>(), set![]); - - assert_eq!(dm.dependents(uuids[3]).collect::>(), set![]); - assert_eq!( - dm.dependents(uuids[2]).collect::>(), - set![uuids[3]] - ); - assert_eq!( - dm.dependents(uuids[1]).collect::>(), - set![uuids[3]] - ); - assert_eq!( - dm.dependents(uuids[0]).collect::>(), - set![uuids[1], uuids[2]] - ); - - // mark t[0] as done, removing it from the working set - rep.get_task(uuids[0]) - .unwrap() - .unwrap() - .into_mut(&mut rep) - .done() - .unwrap(); - let dm = rep.dependency_map(true).unwrap(); - - assert_eq!( - dm.dependencies(uuids[3]).collect::>(), - set![uuids[1], uuids[2]] - ); - assert_eq!(dm.dependencies(uuids[2]).collect::>(), set![]); - assert_eq!(dm.dependencies(uuids[1]).collect::>(), set![]); - assert_eq!(dm.dependents(uuids[0]).collect::>(), set![]); - } -} diff --git a/taskchampion/taskchampion/src/server/cloud/gcp.rs b/taskchampion/taskchampion/src/server/cloud/gcp.rs deleted file mode 100644 index a53ad6e48..000000000 --- a/taskchampion/taskchampion/src/server/cloud/gcp.rs +++ /dev/null @@ -1,407 +0,0 @@ -use super::service::{ObjectInfo, Service}; -use crate::errors::Result; -use google_cloud_storage::client::google_cloud_auth::credentials::CredentialsFile; -use google_cloud_storage::client::{Client, ClientConfig}; -use google_cloud_storage::http::error::ErrorResponse; -use google_cloud_storage::http::Error as GcsError; -use google_cloud_storage::http::{self, objects}; -use tokio::runtime::Runtime; - -/// A [`Service`] implementation based on the Google Cloud Storage service. -pub(in crate::server) struct GcpService { - client: Client, - rt: Runtime, - bucket: String, -} - -/// Determine whether the given result contains an HTTP error with the given code. -fn is_http_error(query: u16, res: &std::result::Result) -> bool { - match res { - // Errors from RPC's. - Err(GcsError::Response(ErrorResponse { code, .. })) => *code == query, - // Errors from reqwest (downloads, uploads). - Err(GcsError::HttpClient(e)) => e.status().map(|s| s.as_u16()) == Some(query), - _ => false, - } -} - -impl GcpService { - pub(in crate::server) fn new(bucket: String, credential_path: Option) -> Result { - let rt = Runtime::new()?; - - let credentialpathstring = credential_path.clone().unwrap(); - let config: ClientConfig = if credential_path.unwrap() == "" { - rt.block_on(ClientConfig::default().with_auth())? - } else { - let credentials = rt.block_on(CredentialsFile::new_from_file(credentialpathstring))?; - rt.block_on(ClientConfig::default().with_credentials(credentials))? - }; - - Ok(Self { - client: Client::new(config), - rt, - bucket, - }) - } -} - -impl Service for GcpService { - fn put(&mut self, name: &[u8], value: &[u8]) -> Result<()> { - let name = String::from_utf8(name.to_vec()).expect("non-UTF8 object name"); - let upload_type = objects::upload::UploadType::Simple(objects::upload::Media::new(name)); - self.rt.block_on(self.client.upload_object( - &objects::upload::UploadObjectRequest { - bucket: self.bucket.clone(), - ..Default::default() - }, - value.to_vec(), - &upload_type, - ))?; - Ok(()) - } - - fn get(&mut self, name: &[u8]) -> Result>> { - let name = String::from_utf8(name.to_vec()).expect("non-UTF8 object name"); - let download_res = self.rt.block_on(self.client.download_object( - &objects::get::GetObjectRequest { - bucket: self.bucket.clone(), - object: name, - ..Default::default() - }, - &objects::download::Range::default(), - )); - if is_http_error(404, &download_res) { - Ok(None) - } else { - Ok(Some(download_res?)) - } - } - - fn del(&mut self, name: &[u8]) -> Result<()> { - let name = String::from_utf8(name.to_vec()).expect("non-UTF8 object name"); - let del_res = self.rt.block_on(self.client.delete_object( - &objects::delete::DeleteObjectRequest { - bucket: self.bucket.clone(), - object: name, - ..Default::default() - }, - )); - if !is_http_error(404, &del_res) { - del_res?; - } - Ok(()) - } - - fn list<'a>(&'a mut self, prefix: &[u8]) -> Box> + 'a> { - let prefix = String::from_utf8(prefix.to_vec()).expect("non-UTF8 object prefix"); - Box::new(ObjectIterator { - service: self, - prefix, - last_response: None, - next_index: 0, - }) - } - - fn compare_and_swap( - &mut self, - name: &[u8], - existing_value: Option>, - new_value: Vec, - ) -> Result { - let name = String::from_utf8(name.to_vec()).expect("non-UTF8 object name"); - let get_res = self - .rt - .block_on(self.client.get_object(&objects::get::GetObjectRequest { - bucket: self.bucket.clone(), - object: name.clone(), - ..Default::default() - })); - // Determine the object's generation. See https://cloud.google.com/storage/docs/metadata#generation-number - let generation = if is_http_error(404, &get_res) { - // If a value was expected, that expectation has not been met. - if existing_value.is_some() { - return Ok(false); - } - // Generation 0 indicates that the object does not yet exist. - 0 - } else { - get_res?.generation - }; - - // If the file existed, then verify its contents. - if generation > 0 { - let data = self.rt.block_on(self.client.download_object( - &objects::get::GetObjectRequest { - bucket: self.bucket.clone(), - object: name.clone(), - // Fetch the same generation. - generation: Some(generation), - ..Default::default() - }, - &objects::download::Range::default(), - ))?; - if Some(data) != existing_value { - return Ok(false); - } - } - - // Finally, put the new value with a condition that the generation hasn't changed. - let upload_type = objects::upload::UploadType::Simple(objects::upload::Media::new(name)); - let upload_res = self.rt.block_on(self.client.upload_object( - &objects::upload::UploadObjectRequest { - bucket: self.bucket.clone(), - if_generation_match: Some(generation), - ..Default::default() - }, - new_value.to_vec(), - &upload_type, - )); - if is_http_error(412, &upload_res) { - // A 412 indicates the precondition was not satisfied: the given generation - // is no longer the latest. - Ok(false) - } else { - upload_res?; - Ok(true) - } - } -} - -/// An Iterator returning names of objects from `list_objects`. -/// -/// This handles response pagination by fetching one page at a time. -struct ObjectIterator<'a> { - service: &'a mut GcpService, - prefix: String, - last_response: Option, - next_index: usize, -} - -impl<'a> ObjectIterator<'a> { - fn fetch_batch(&mut self) -> Result<()> { - let mut page_token = None; - if let Some(ref resp) = self.last_response { - page_token = resp.next_page_token.clone(); - } - self.last_response = Some(self.service.rt.block_on(self.service.client.list_objects( - &objects::list::ListObjectsRequest { - bucket: self.service.bucket.clone(), - prefix: Some(self.prefix.clone()), - page_token, - #[cfg(test)] // For testing, use a small page size. - max_results: Some(6), - ..Default::default() - }, - ))?); - self.next_index = 0; - Ok(()) - } -} - -impl<'a> Iterator for ObjectIterator<'a> { - type Item = Result; - fn next(&mut self) -> Option { - // If the iterator is just starting, fetch the first response. - if self.last_response.is_none() { - if let Err(e) = self.fetch_batch() { - return Some(Err(e)); - } - } - if let Some(ref result) = self.last_response { - if let Some(ref items) = result.items { - if self.next_index < items.len() { - // Return a result from the existing response. - let obj = &items[self.next_index]; - self.next_index += 1; - // It's unclear when `time_created` would be None, so default to 0 in that case - // or when the timestamp is not a valid u64 (before 1970). - let creation = obj.time_created.map(|t| t.unix_timestamp()).unwrap_or(0); - let creation: u64 = creation.try_into().unwrap_or(0); - return Some(Ok(ObjectInfo { - name: obj.name.as_bytes().to_vec(), - creation, - })); - } else if result.next_page_token.is_some() { - // Fetch the next page and try again. - if let Err(e) = self.fetch_batch() { - return Some(Err(e)); - } - return self.next(); - } - } - } - None - } -} - -#[cfg(test)] -mod tests { - use super::*; - use uuid::Uuid; - - /// Make a service if `GCP_TEST_BUCKET` is set, as well as a function to put a unique prefix on - /// an object name, so that tests do not interfere with one another. - /// - /// Set up this bucket with a lifecyle policy to delete objects with age > 1 day. While passing - /// tests should correctly clean up after themselves, failing tests may leave objects in the - /// bucket. - /// - /// When the environment variable is not set, this returns false and the test does not run. - /// Note that the Rust test runner will still show "ok" for the test, as there is no way to - /// indicate anything else. - fn make_service() -> Option<(GcpService, impl Fn(&str) -> Vec)> { - let Ok(bucket) = std::env::var("GCP_TEST_BUCKET") else { - return None; - }; - - let Ok(credential_path) = std::env::var("GCP_TEST_CREDENTIAL_PATH") else { - return None; - }; - - let prefix = Uuid::new_v4(); - Some(( - GcpService::new(bucket, Some(credential_path)).unwrap(), - move |n: &_| format!("{}-{}", prefix.as_simple(), n).into_bytes(), - )) - } - - #[test] - fn put_and_get() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - svc.put(&pfx("testy"), b"foo").unwrap(); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, Some(b"foo".to_vec())); - - // Clean up. - svc.del(&pfx("testy")).unwrap(); - } - - #[test] - fn get_missing() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, None); - } - - #[test] - fn del() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - svc.put(&pfx("testy"), b"data").unwrap(); - svc.del(&pfx("testy")).unwrap(); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, None); - } - - #[test] - fn del_missing() { - // Deleting an object that does not exist is not an error. - let Some((mut svc, pfx)) = make_service() else { - return; - }; - - assert!(svc.del(&pfx("testy")).is_ok()); - } - - #[test] - fn list() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - let mut names: Vec<_> = (0..20).map(|i| pfx(&format!("pp-{i:02}"))).collect(); - names.sort(); - // Create 20 objects that will be listed. - for n in &names { - svc.put(n, b"data").unwrap(); - } - // And another object that should not be included in the list. - svc.put(&pfx("xxx"), b"data").unwrap(); - - let got_objects: Vec<_> = svc.list(&pfx("pp-")).collect::>().unwrap(); - let mut got_names: Vec<_> = got_objects.into_iter().map(|oi| oi.name).collect(); - got_names.sort(); - assert_eq!(got_names, names); - - // Clean up. - for n in got_names { - svc.del(&n).unwrap(); - } - svc.del(&pfx("xxx")).unwrap(); - } - - #[test] - fn compare_and_swap_create() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - - assert!(svc - .compare_and_swap(&pfx("testy"), None, b"bar".to_vec()) - .unwrap()); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, Some(b"bar".to_vec())); - - // Clean up. - svc.del(&pfx("testy")).unwrap(); - } - - #[test] - fn compare_and_swap_matches() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - - // Create the existing file, with two generations. - svc.put(&pfx("testy"), b"foo1").unwrap(); - svc.put(&pfx("testy"), b"foo2").unwrap(); - assert!(svc - .compare_and_swap(&pfx("testy"), Some(b"foo2".to_vec()), b"bar".to_vec()) - .unwrap()); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, Some(b"bar".to_vec())); - - // Clean up. - svc.del(&pfx("testy")).unwrap(); - } - - #[test] - fn compare_and_swap_expected_no_file() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - - svc.put(&pfx("testy"), b"foo1").unwrap(); - assert!(!svc - .compare_and_swap(&pfx("testy"), None, b"bar".to_vec()) - .unwrap()); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, Some(b"foo1".to_vec())); - - // Clean up. - svc.del(&pfx("testy")).unwrap(); - } - - #[test] - fn compare_and_swap_mismatch() { - let Some((mut svc, pfx)) = make_service() else { - return; - }; - - // Create the existing file, with two generations. - svc.put(&pfx("testy"), b"foo1").unwrap(); - svc.put(&pfx("testy"), b"foo2").unwrap(); - assert!(!svc - .compare_and_swap(&pfx("testy"), Some(b"foo1".to_vec()), b"bar".to_vec()) - .unwrap()); - let got = svc.get(&pfx("testy")).unwrap(); - assert_eq!(got, Some(b"foo2".to_vec())); - - // Clean up. - svc.del(&pfx("testy")).unwrap(); - } -} diff --git a/taskchampion/taskchampion/src/server/cloud/mod.rs b/taskchampion/taskchampion/src/server/cloud/mod.rs deleted file mode 100644 index 970ced75c..000000000 --- a/taskchampion/taskchampion/src/server/cloud/mod.rs +++ /dev/null @@ -1,16 +0,0 @@ -/*! -* Support for cloud-service-backed sync. -* -* All of these operate using a similar approach, with specific patterns of object names. The -* process of adding a new version requires a compare-and-swap operation that sets a new version -* as the "latest" only if the existing "latest" has the expected value. This ensures a continuous -* chain of versions, even if multiple replicas attempt to sync at the same time. -*/ - -mod server; -mod service; - -pub(in crate::server) use server::CloudServer; - -#[cfg(feature = "server-gcp")] -pub(in crate::server) mod gcp; diff --git a/taskchampion/taskchampion/src/server/cloud/server.rs b/taskchampion/taskchampion/src/server/cloud/server.rs deleted file mode 100644 index 6aaee585b..000000000 --- a/taskchampion/taskchampion/src/server/cloud/server.rs +++ /dev/null @@ -1,1183 +0,0 @@ -use super::service::{ObjectInfo, Service}; -use crate::errors::{Error, Result}; -use crate::server::encryption::{Cryptor, Sealed, Unsealed}; -use crate::server::{ - AddVersionResult, GetVersionResult, HistorySegment, Server, Snapshot, SnapshotUrgency, - VersionId, -}; -use ring::rand; -use std::collections::{HashMap, HashSet}; -#[cfg(not(test))] -use std::time::{SystemTime, UNIX_EPOCH}; -use uuid::Uuid; - -/// Implement the Server trait for a cloud service implemented by [`Service`]. -/// -/// This type implements a TaskChampion server over a basic object-storage service. It encapsulates -/// all of the logic to ensure a linear sequence of versions, encrypt and decrypt data, and clean -/// up old data so that this can be supported on a variety of cloud services. -/// -/// ## Encryption -/// -/// The encryption scheme is described in `sync-protocol.md`. The salt value used for key -/// derivation is stored in "salt", which is created if it does not exist. Object names are not -/// encrypted, by the nature of key/value stores. Since the content of the "latest" object can -/// usually be inferred from object names, it, too, is not encrypted. -/// -/// ## Object Organization -/// -/// UUIDs emebedded in names and values appear in their "simple" form: lower-case hexadecimal with -/// no hyphens. -/// -/// Versions are stored as objects with name `v-PARENT-VERSION` where `PARENT` is the parent -/// version's UUID and `VERSION` is the version's UUID. The object value is the raw history -/// segment. These objects are created with simple `put` requests, as the name uniquely identifies -/// the content. -/// -/// The latest version is stored as an object with name "latest", containing the UUID of the latest -/// version. This file is updated with `compare_and_swap`. After a successful update of this -/// object, the version is considered committed. -/// -/// Since there are no strong constraints on creation of version objects, it is possible -/// to have multiple such files with the same `PARENT`. However, only one such object will be -/// contained in the chain of parent-child relationships beginning with the value in "latest". -/// All other objects are invalid and not visible outside this type. -/// -/// Snapshots are stored as objects with name `s-VERSION` where `VERSION` is the version at which -/// the snapshot was made. These objects are created with simple `put` requests, as any snapshot -/// for a given version is functionally equivalent to any other. -/// -/// ## Cleanup -/// -/// Cleanup of unnecessary data is performed probabalistically after `add_version`, although any -/// errors are ignored. -/// -/// - Any versions not reachable from "latest" and which cannot become "latest" are deleted. -/// - Any snapshots older than the most recent are deleted. -/// - Any versions older than [`MAX_VERSION_AGE_SECS`] which are incorporated into a snapshot -/// are deleted. -pub(in crate::server) struct CloudServer { - service: SVC, - - /// The Cryptor supporting encryption and decryption of objects in this server. - cryptor: Cryptor, - - /// The probability (0..255) that this run will perform cleanup. - cleanup_probability: u8, - - /// For testing, a function that is called in the middle of `add_version` to simulate - /// a concurrent change in the service. - #[cfg(test)] - add_version_intercept: Option, -} - -const LATEST: &[u8] = b"latest"; -const DEFAULT_CLEANUP_PROBABILITY: u8 = 13; // about 5% - -#[cfg(not(test))] -const MAX_VERSION_AGE_SECS: u64 = 3600 * 24 * 180; // about half a year - -fn version_to_bytes(v: VersionId) -> Vec { - v.as_simple().to_string().into_bytes() -} - -impl CloudServer { - pub(in crate::server) fn new(mut service: SVC, encryption_secret: Vec) -> Result { - let salt = Self::get_salt(&mut service)?; - let cryptor = Cryptor::new(salt, &encryption_secret.into())?; - Ok(Self { - service, - cryptor, - cleanup_probability: DEFAULT_CLEANUP_PROBABILITY, - #[cfg(test)] - add_version_intercept: None, - }) - } - - /// Get the salt value stored in the service, creating a new random one if necessary. - fn get_salt(service: &mut SVC) -> Result> { - const SALT_NAME: &[u8] = b"salt"; - loop { - if let Some(salt) = service.get(SALT_NAME)? { - return Ok(salt); - } - service.compare_and_swap(SALT_NAME, None, Cryptor::gen_salt()?)?; - } - } - - /// Generate an object name for the given parent and child versions. - fn version_name(parent_version_id: &VersionId, child_version_id: &VersionId) -> Vec { - format!( - "v-{}-{}", - parent_version_id.as_simple(), - child_version_id.as_simple() - ) - .into_bytes() - } - - /// Parse a version name as generated by `version_name`, returning None if the name does not - /// have a valid format. - fn parse_version_name(name: &[u8]) -> Option<(VersionId, VersionId)> { - if name.len() != 2 + 32 + 1 + 32 || !name.starts_with(b"v-") || name[2 + 32] != b'-' { - return None; - } - let Ok(parent_version_id) = VersionId::try_parse_ascii(&name[2..2 + 32]) else { - return None; - }; - let Ok(child_version_id) = VersionId::try_parse_ascii(&name[2 + 32 + 1..]) else { - return None; - }; - Some((parent_version_id, child_version_id)) - } - - /// Generate an object name for a snapshot at the given version. - fn snapshot_name(version_id: &VersionId) -> Vec { - format!("s-{}", version_id.as_simple()).into_bytes() - } - - /// Parse a snapshot name as generated by `snapshot_name`, returning None if the name does not - /// have a valid format. - fn parse_snapshot_name(name: &[u8]) -> Option { - if name.len() != 2 + 32 || !name.starts_with(b"s-") { - return None; - } - let Ok(version_id) = VersionId::try_parse_ascii(&name[2..2 + 32]) else { - return None; - }; - Some(version_id) - } - - /// Generate a random integer in (0..255) for use in probabalistic decisions. - fn randint(&self) -> Result { - use rand::SecureRandom; - let mut randint = [0u8]; - rand::SystemRandom::new() - .fill(&mut randint) - .map_err(|_| Error::Server("Random number generator failure".into()))?; - Ok(randint[0]) - } - - /// Get the version from "latest", or None if the object does not exist. This always fetches a fresh - /// value from storage. - fn get_latest(&mut self) -> Result> { - let Some(latest) = self.service.get(LATEST)? else { - return Ok(None); - }; - let latest = VersionId::try_parse_ascii(&latest) - .map_err(|_| Error::Server("'latest' object contains invalid data".into()))?; - Ok(Some(latest)) - } - - /// Get the possible child versions of the given parent version, based only on the object - /// names. - fn get_child_versions(&mut self, parent_version_id: &VersionId) -> Result> { - self.service - .list(format!("v-{}-", parent_version_id.as_simple()).as_bytes()) - .filter_map(|res| match res { - Ok(ObjectInfo { name, .. }) => { - if let Some((_, c)) = Self::parse_version_name(&name) { - Some(Ok(c)) - } else { - None - } - } - Err(e) => Some(Err(e)), - }) - .collect::>>() - } - - /// Determine the snapshot urgency. This is done probabalistically: - /// - High urgency approximately 1% of the time. - /// - Low urgency approximately 10% of the time. - fn snapshot_urgency(&self) -> Result { - let r = self.randint()?; - if r < 2 { - Ok(SnapshotUrgency::High) - } else if r < 25 { - Ok(SnapshotUrgency::Low) - } else { - Ok(SnapshotUrgency::None) - } - } - - /// Maybe call `cleanup` depending on `cleanup_probability`. - fn maybe_cleanup(&mut self) -> Result<()> { - if self.randint()? < self.cleanup_probability { - self.cleanup_probability = DEFAULT_CLEANUP_PROBABILITY; - self.cleanup() - } else { - Ok(()) - } - } - - /// Perform cleanup, deleting unnecessary data. - fn cleanup(&mut self) -> Result<()> { - // Construct a vector containing all (child, parent, creation) tuples - let mut versions = self - .service - .list(b"v-") - .filter_map(|res| match res { - Ok(ObjectInfo { name, creation }) => { - if let Some((p, c)) = Self::parse_version_name(&name) { - Some(Ok((c, p, creation))) - } else { - None - } - } - Err(e) => Some(Err(e)), - }) - .collect::>>()?; - versions.sort(); - - // Function to find the parent of a given child version in `versions`, taking - // advantage of having sorted the vector by child version ID. - let parent_of = |c| match versions.binary_search_by_key(&c, |tup| tup.0) { - Ok(idx) => Some(versions[idx].1), - Err(_) => None, - }; - - // Create chains mapping forward (parent -> child) and backward (child -> parent), starting - // at "latest". - let mut rev_chain = HashMap::new(); - let mut iterations = versions.len() + 1; // For cycle detection. - let latest = self.get_latest()?; - if let Some(mut c) = latest { - while let Some(p) = parent_of(c) { - rev_chain.insert(c, p); - c = p; - iterations -= 1; - if iterations == 0 { - return Err(Error::Server("Version cycle detected".into())); - } - } - } - - // Collect all versions older than MAX_VERSION_AGE_SECS - #[cfg(not(test))] - let age_threshold = { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|t| t.as_secs()) - .unwrap_or(0); - now.saturating_sub(MAX_VERSION_AGE_SECS) - }; - - // In testing, cutoff age is 1000. - #[cfg(test)] - let age_threshold = 1000; - - let old_versions: HashSet = versions - .iter() - .filter_map(|(c, _, creation)| { - if *creation < age_threshold { - Some(*c) - } else { - None - } - }) - .collect(); - - // Now, any pair not present in that chain can be deleted. However, another replica - // may be in the state where it has uploaded a version but not changed "latest" yet, - // so any pair with parent equal to latest is allowed to stay. - for (c, p, _) in versions { - if rev_chain.get(&c) != Some(&p) && Some(p) != latest { - self.service.del(&Self::version_name(&p, &c))?; - } - } - - // Collect a set of all snapshots. - let snapshots = self - .service - .list(b"s-") - .filter_map(|res| match res { - Ok(ObjectInfo { name, .. }) => Self::parse_snapshot_name(&name).map(Ok), - Err(e) => Some(Err(e)), - }) - .collect::>>()?; - - // Find the latest snapshot by iterating back from "latest". Note that this iteration is - // guaranteed not to be cyclical, as that was checked above. - let mut latest_snapshot = None; - if let Some(mut version) = latest { - loop { - if snapshots.contains(&version) { - latest_snapshot = Some(version); - break; - } - if let Some(v) = rev_chain.get(&version) { - version = *v; - } else { - break; - } - } - } - - // If there's a latest snapshot, delete all other snapshots. - let Some(latest_snapshot) = latest_snapshot else { - // If there's no snapshot, no further cleanup is possible. - return Ok(()); - }; - for version in snapshots { - if version != latest_snapshot { - self.service.del(&Self::snapshot_name(&version))?; - } - } - - // Now continue iterating backward from that version; any version in `old_versions` can be - // deleted. - let mut version = latest_snapshot; - while let Some(parent) = rev_chain.get(&version) { - if old_versions.contains(&version) { - self.service.del(&Self::version_name(parent, &version))?; - } - version = *parent; - } - - Ok(()) - } -} - -impl Server for CloudServer { - fn add_version( - &mut self, - parent_version_id: VersionId, - history_segment: HistorySegment, - ) -> Result<(AddVersionResult, SnapshotUrgency)> { - let latest = self.get_latest()?; - if let Some(l) = latest { - if l != parent_version_id { - return Ok(( - AddVersionResult::ExpectedParentVersion(l), - self.snapshot_urgency()?, - )); - } - } - - // Invent a new version ID and upload the version data. - let version_id = VersionId::new_v4(); - let new_name = Self::version_name(&parent_version_id, &version_id); - let sealed = self.cryptor.seal(Unsealed { - version_id, - payload: history_segment, - })?; - self.service.put(&new_name, sealed.as_ref())?; - - #[cfg(test)] - if let Some(f) = self.add_version_intercept { - f(&mut self.service); - } - - // Try to compare-and-swap this value into LATEST - let old_value = latest.map(version_to_bytes); - let new_value = version_to_bytes(version_id); - if !self - .service - .compare_and_swap(LATEST, old_value, new_value)? - { - // Delete the version data, since it was not latest. - self.service.del(&new_name)?; - let latest = self.get_latest()?; - let latest = latest.unwrap_or(Uuid::nil()); - return Ok(( - AddVersionResult::ExpectedParentVersion(latest), - self.snapshot_urgency()?, - )); - } - - // Attempt a cleanup, but ignore errors. - let _ = self.maybe_cleanup(); - - Ok((AddVersionResult::Ok(version_id), self.snapshot_urgency()?)) - } - - fn get_child_version(&mut self, parent_version_id: VersionId) -> Result { - // The `get_child_versions` function will usually return only one child version for a - // parent, in which case the work is easy. Otherwise, if there are several possible - // children, only one of those will lead to `latest`, and importantly the others will not - // have their own children. So we can detect the "true" child as the one that is equal to - // "latest" or has children. - let version_id = match &(self.get_child_versions(&parent_version_id)?)[..] { - [] => return Ok(GetVersionResult::NoSuchVersion), - [child] => *child, - children => { - // There are some extra version objects, so a cleanup is warranted. - self.cleanup_probability = 255; - let latest = self.get_latest()?; - let mut true_child = None; - for child in children { - if Some(*child) == latest { - true_child = Some(*child); - break; - } - } - if true_child.is_none() { - for child in children { - if !self.get_child_versions(child)?.is_empty() { - true_child = Some(*child) - } - } - } - match true_child { - Some(true_child) => true_child, - None => return Ok(GetVersionResult::NoSuchVersion), - } - } - }; - - let Some(sealed) = self - .service - .get(&Self::version_name(&parent_version_id, &version_id))? - else { - // This really shouldn't happen, since the chain was derived from object names, but - // perhaps the object was deleted. - return Ok(GetVersionResult::NoSuchVersion); - }; - let unsealed = self.cryptor.unseal(Sealed { - version_id, - payload: sealed, - })?; - Ok(GetVersionResult::Version { - version_id, - parent_version_id, - history_segment: unsealed.into(), - }) - } - - fn add_snapshot(&mut self, version_id: VersionId, snapshot: Snapshot) -> Result<()> { - let name = Self::snapshot_name(&version_id); - let sealed = self.cryptor.seal(Unsealed { - version_id, - payload: snapshot, - })?; - self.service.put(&name, sealed.as_ref())?; - Ok(()) - } - - fn get_snapshot(&mut self) -> Result> { - // Pick the first snapshot we find. - let Some(name) = self.service.list(b"s-").next() else { - return Ok(None); - }; - let ObjectInfo { name, .. } = name?; - let Some(version_id) = Self::parse_snapshot_name(&name) else { - return Ok(None); - }; - let Some(payload) = self.service.get(&name)? else { - return Ok(None); - }; - let unsealed = self.cryptor.unseal(Sealed { - version_id, - payload, - })?; - Ok(Some((version_id, unsealed.payload))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::server::NIL_VERSION_ID; - - /// A simple in-memory service for testing. All insertions via Service methods occur at time - /// `INSERTION_TIME`. All versions older that 1000 are considered "old". - #[derive(Clone)] - struct MockService(HashMap, (u64, Vec)>); - - const INSERTION_TIME: u64 = 9999999999; - - impl MockService { - fn new() -> Self { - let mut map = HashMap::new(); - // Use a fixed salt for consistent results - map.insert(b"salt".to_vec(), (0, b"abcdefghabcdefgh".to_vec())); - Self(map) - } - } - - impl Service for MockService { - fn put(&mut self, name: &[u8], value: &[u8]) -> Result<()> { - self.0 - .insert(name.to_vec(), (INSERTION_TIME, value.to_vec())); - Ok(()) - } - - fn get(&mut self, name: &[u8]) -> Result>> { - Ok(self.0.get(name).map(|(_, data)| data.clone())) - } - - fn del(&mut self, name: &[u8]) -> Result<()> { - self.0.remove(name); - Ok(()) - } - - fn compare_and_swap( - &mut self, - name: &[u8], - existing_value: Option>, - new_value: Vec, - ) -> Result { - if self.0.get(name).map(|(_, d)| d) == existing_value.as_ref() { - self.0.insert(name.to_vec(), (INSERTION_TIME, new_value)); - return Ok(true); - } - Ok(false) - } - - fn list<'a>( - &'a mut self, - prefix: &[u8], - ) -> Box> + 'a> { - let prefix = prefix.to_vec(); - Box::new( - self.0 - .iter() - .filter(move |(k, _)| k.starts_with(&prefix)) - .map(|(k, (t, _))| { - Ok(ObjectInfo { - name: k.to_vec(), - creation: *t, - }) - }), - ) - } - } - - impl std::fmt::Debug for MockService { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_map() - .entries( - self.0 - .iter() - .map(|(k, v)| (std::str::from_utf8(k).unwrap(), v)), - ) - .finish() - } - } - - // Add some testing utilities to CloudServer. - impl CloudServer { - fn mock_add_version( - &mut self, - parent: VersionId, - child: VersionId, - creation: u64, - data: &[u8], - ) { - let name = Self::version_name(&parent, &child); - let sealed = self - .cryptor - .seal(Unsealed { - version_id: child, - payload: data.into(), - }) - .unwrap(); - self.service.0.insert(name, (creation, sealed.into())); - } - - fn mock_add_snapshot(&mut self, version: VersionId, creation: u64, snapshot: &[u8]) { - let name = Self::snapshot_name(&version); - let sealed = self - .cryptor - .seal(Unsealed { - version_id: version, - payload: snapshot.into(), - }) - .unwrap(); - self.service.0.insert(name, (creation, sealed.into())); - } - - fn mock_set_latest(&mut self, latest: VersionId) { - let latest = version_to_bytes(latest); - self.service - .0 - .insert(LATEST.to_vec(), (INSERTION_TIME, latest)); - } - - /// Create a copy of this server without any data; used for creating a MockService - /// to compare to with `assert_eq!` - fn empty_clone(&self) -> Self { - Self { - cryptor: self.cryptor.clone(), - cleanup_probability: 0, - service: MockService::new(), - add_version_intercept: None, - } - } - - /// Get a decrypted, string-y copy of the data in the HashMap. - fn unencrypted(&self) -> HashMap { - self.service - .0 - .iter() - .map(|(k, v)| { - let kstr = String::from_utf8(k.to_vec()).unwrap(); - if kstr == "latest" { - return (kstr, (v.0, String::from_utf8(v.1.to_vec()).unwrap())); - } - - let version_id; - if let Some((_, v)) = Self::parse_version_name(k) { - version_id = v; - } else if let Some(v) = Self::parse_snapshot_name(k) { - version_id = v; - } else { - return (kstr, (v.0, format!("{:?}", v.1))); - } - - let unsealed = self - .cryptor - .unseal(Sealed { - version_id, - payload: v.1.to_vec(), - }) - .unwrap(); - let vstr = String::from_utf8(unsealed.into()).unwrap(); - (kstr, (v.0, vstr)) - }) - .collect() - } - } - impl Clone for CloudServer { - fn clone(&self) -> Self { - Self { - cryptor: self.cryptor.clone(), - cleanup_probability: self.cleanup_probability, - service: self.service.clone(), - add_version_intercept: None, - } - } - } - - const SECRET: &[u8] = b"testing"; - - fn make_server() -> CloudServer { - let mut server = CloudServer::new(MockService::new(), SECRET.into()).unwrap(); - // Prevent cleanup during tests. - server.cleanup_probability = 0; - server - } - - #[test] - fn version_name() { - let p = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8").unwrap(); - let c = Uuid::parse_str("adcf4e350fa54e4aaf9d3f20f3ba5a32").unwrap(); - assert_eq!( - CloudServer::::version_name(&p, &c), - b"v-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8-adcf4e350fa54e4aaf9d3f20f3ba5a32" - ); - } - - #[test] - fn version_name_round_trip() { - let p = Uuid::new_v4(); - let c = Uuid::new_v4(); - assert_eq!( - CloudServer::::parse_version_name( - &CloudServer::::version_name(&p, &c) - ), - Some((p, c)) - ); - } - - #[test] - fn parse_version_name_bad_prefix() { - assert_eq!( - CloudServer::::parse_version_name( - b"X-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8-adcf4e350fa54e4aaf9d3f20f3ba5a32" - ), - None - ); - } - - #[test] - fn parse_version_name_bad_separator() { - assert_eq!( - CloudServer::::parse_version_name( - b"v-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8xadcf4e350fa54e4aaf9d3f20f3ba5a32" - ), - None - ); - } - - #[test] - fn parse_version_name_too_short() { - assert_eq!( - CloudServer::::parse_version_name( - b"v-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8-adcf4e350fa54e4aaf9d3f20f3ba5a3" - ), - None - ); - } - - #[test] - fn parse_version_name_too_long() { - assert_eq!( - CloudServer::::parse_version_name( - b"v-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8-adcf4e350fa54e4aaf9d3f20f3ba5a320" - ), - None - ); - } - - #[test] - fn snapshot_name_round_trip() { - let v = Uuid::new_v4(); - assert_eq!( - CloudServer::::parse_snapshot_name( - &CloudServer::::snapshot_name(&v) - ), - Some(v) - ); - } - - #[test] - fn parse_snapshot_name_invalid() { - assert_eq!( - CloudServer::::parse_snapshot_name(b"s-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), - None - ); - } - - #[test] - fn parse_snapshot_name_bad_prefix() { - assert_eq!( - CloudServer::::parse_snapshot_name(b"s:a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8"), - None - ); - } - - #[test] - fn parse_snapshot_name_too_short() { - assert_eq!( - CloudServer::::parse_snapshot_name(b"s-a1a2a3a4b1b2c1c2d1d2d3d4d5d6"), - None - ); - } - - #[test] - fn parse_snapshot_name_too_long() { - assert_eq!( - CloudServer::::parse_snapshot_name( - b"s-a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8000" - ), - None - ); - } - - #[test] - fn get_salt_existing() { - let mut service = MockService::new(); - assert_eq!( - CloudServer::::get_salt(&mut service).unwrap(), - b"abcdefghabcdefgh".to_vec() - ); - } - - #[test] - fn get_salt_create() { - let mut service = MockService::new(); - service.del(b"salt").unwrap(); - let got_salt = CloudServer::::get_salt(&mut service).unwrap(); - let salt_obj = service.get(b"salt").unwrap().unwrap(); - assert_eq!(got_salt, salt_obj); - } - - #[test] - fn get_latest_empty() { - let mut server = make_server(); - assert_eq!(server.get_latest().unwrap(), None); - } - - #[test] - fn get_latest_exists() { - let mut server = make_server(); - let latest = Uuid::new_v4(); - server.mock_set_latest(latest); - assert_eq!(server.get_latest().unwrap(), Some(latest)); - } - - #[test] - fn get_latest_invalid() { - let mut server = make_server(); - server - .service - .0 - .insert(LATEST.to_vec(), (999, b"not-a-uuid".to_vec())); - assert!(server.get_latest().is_err()); - } - - #[test] - fn get_child_versions_empty() { - let mut server = make_server(); - assert_eq!(server.get_child_versions(&Uuid::new_v4()).unwrap(), vec![]); - } - - #[test] - fn get_child_versions_single() { - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v2, v1, 1000, b"first"); - assert_eq!(server.get_child_versions(&v1).unwrap(), vec![]); - assert_eq!(server.get_child_versions(&v2).unwrap(), vec![v1]); - } - - #[test] - fn get_child_versions_multiple() { - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v3, v1, 1000, b"first"); - server.mock_add_version(v3, v2, 1000, b"second"); - assert_eq!(server.get_child_versions(&v1).unwrap(), vec![]); - assert_eq!(server.get_child_versions(&v2).unwrap(), vec![]); - let versions = server.get_child_versions(&v3).unwrap(); - assert!(versions == vec![v1, v2] || versions == vec![v2, v1]); - } - - #[test] - fn add_version_empty() { - let mut server = make_server(); - let parent = Uuid::new_v4(); - let (res, _) = server.add_version(parent, b"history".to_vec()).unwrap(); - assert!(matches!(res, AddVersionResult::Ok(_))); - } - - #[test] - fn add_version_good() { - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"first"); - server.mock_set_latest(v2); - - let (res, _) = server.add_version(v2, b"history".to_vec()).unwrap(); - let AddVersionResult::Ok(new_version) = res else { - panic!("expected OK"); - }; - - let mut expected = server.empty_clone(); - expected.mock_add_version(v1, v2, 1000, b"first"); - expected.mock_add_version(v2, new_version, INSERTION_TIME, b"history"); - expected.mock_set_latest(new_version); - - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn add_version_not_latest() { - // The `add_version` method does nothing if the version is not latest. - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"first"); - server.mock_set_latest(v2); - - let expected = server.clone(); - - let (res, _) = server.add_version(v1, b"history".to_vec()).unwrap(); - assert_eq!(res, AddVersionResult::ExpectedParentVersion(v2)); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn add_version_not_latest_race() { - // The `add_version` function effectively checks twice for a conflict: once by just - // fetching "latest", returning early if the value is not as expected; and once in the - // compare-and-swap. This test uses `add_version_intercept` to force the first check to - // succeed and the second test to fail. - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - const V3: Uuid = Uuid::max(); - server.mock_add_version(v1, v2, 1000, b"first"); - server.mock_add_version(v2, V3, 1000, b"second"); - server.mock_set_latest(v2); - server.add_version_intercept = Some(|service| { - service.put(LATEST, &version_to_bytes(V3)).unwrap(); - }); - - let mut expected = server.empty_clone(); - expected.mock_add_version(v1, v2, 1000, b"first"); - expected.mock_add_version(v2, V3, 1000, b"second"); - expected.mock_set_latest(V3); // updated by the intercept - - assert_ne!(server.unencrypted(), expected.unencrypted()); - let (res, _) = server.add_version(v2, b"history".to_vec()).unwrap(); - assert_eq!(res, AddVersionResult::ExpectedParentVersion(V3)); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn add_version_unknown() { - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"first"); - server.mock_set_latest(v2); - - let expected = server.clone(); - - let (res, _) = server - .add_version(Uuid::new_v4(), b"history".to_vec()) - .unwrap(); - assert_eq!(res, AddVersionResult::ExpectedParentVersion(v2)); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn get_child_version_empty() { - let mut server = make_server(); - assert_eq!( - server.get_child_version(Uuid::new_v4()).unwrap(), - GetVersionResult::NoSuchVersion - ); - } - - #[test] - fn get_child_version_single() { - let mut server = make_server(); - let (v1, v2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v2, v1, 1000, b"first"); - assert_eq!( - server.get_child_version(v1).unwrap(), - GetVersionResult::NoSuchVersion - ); - assert_eq!( - server.get_child_version(v2).unwrap(), - GetVersionResult::Version { - version_id: v1, - parent_version_id: v2, - history_segment: b"first".to_vec(), - } - ); - } - - #[test] - fn get_child_version_multiple() { - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let (vx, vy, vz) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v1, vx, 1000, b"false start x"); - server.mock_add_version(v1, vy, 1000, b"false start y"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_add_version(v2, vz, 1000, b"false start z"); - server.mock_set_latest(v3); - assert_eq!( - server.get_child_version(v1).unwrap(), - GetVersionResult::Version { - version_id: v2, - parent_version_id: v1, - history_segment: b"second".to_vec(), - } - ); - assert_eq!( - server.get_child_version(v2).unwrap(), - GetVersionResult::Version { - version_id: v3, - parent_version_id: v2, - history_segment: b"third".to_vec(), - } - ); - assert_eq!( - server.get_child_version(v3).unwrap(), - GetVersionResult::NoSuchVersion - ); - } - - #[test] - fn cleanup_empty() { - let mut server = make_server(); - server.cleanup().unwrap(); - } - - #[test] - fn cleanup_linear() { - // Test that cleanup does nothing for a linear version history with a snapshot at the - // oldest version. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(NIL_VERSION_ID, v1, 1000, b"first"); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_add_snapshot(v1, 1000, b"snap 1"); - server.mock_set_latest(v3); - - let expected = server.clone(); - - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_cycle() { - // When a cycle is present, cleanup succeeds and makes no changes. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v3, v1, 1000, b"first"); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_set_latest(v3); - - let expected = server.clone(); - - assert!(server.cleanup().is_err()); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_extra_branches() { - // Cleanup deletes extra branches in the versions. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let (vx, vy) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v1, vx, 1000, b"false start x"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_add_version(v2, vy, 1000, b"false start y"); - server.mock_set_latest(v3); - - let mut expected = server.empty_clone(); - expected.mock_add_version(v1, v2, 1000, b"second"); - expected.mock_add_version(v2, v3, 1000, b"third"); - expected.mock_set_latest(v3); - - assert_ne!(server.unencrypted(), expected.unencrypted()); - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_extra_snapshots() { - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let vy = Uuid::new_v4(); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_add_version(v2, vy, 1000, b"false start y"); - server.mock_add_snapshot(v1, 1000, b"snap 1"); - server.mock_add_snapshot(v2, 1000, b"snap 2"); - server.mock_add_snapshot(vy, 1000, b"snap y"); - server.mock_set_latest(v3); - - let mut expected = server.empty_clone(); - expected.mock_add_version(v1, v2, 1000, b"second"); - expected.mock_add_version(v2, v3, 1000, b"third"); - expected.mock_add_snapshot(v2, 1000, b"snap 2"); - expected.mock_set_latest(v3); - - assert_ne!(server.unencrypted(), expected.unencrypted()); - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_old_versions_no_snapshot() { - // If there are old versions ,but no snapshot, nothing is cleaned up. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 200, b"second"); - server.mock_add_version(v2, v3, 300, b"third"); - server.mock_set_latest(v3); - - let expected = server.clone(); - - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_old_versions_with_snapshot() { - // If there are old versions that are also older than a snapshot, they are - // cleaned up. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let (v4, v5, v6) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 200, b"second"); - server.mock_add_version(v2, v3, 300, b"third"); - server.mock_add_version(v3, v4, 1400, b"fourth"); - server.mock_add_version(v4, v5, 1500, b"fifth"); - server.mock_add_snapshot(v5, 1501, b"snap 1"); - server.mock_add_version(v5, v6, 1600, b"sixth"); - server.mock_set_latest(v6); - - let mut expected = server.empty_clone(); - expected.mock_add_version(v3, v4, 1400, b"fourth"); // Not old enough to be deleted. - expected.mock_add_version(v4, v5, 1500, b"fifth"); - expected.mock_add_snapshot(v5, 1501, b"snap 1"); - expected.mock_add_version(v5, v6, 1600, b"sixth"); - expected.mock_set_latest(v6); - - assert_ne!(server.unencrypted(), expected.unencrypted()); - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_old_versions_newer_than_snapshot() { - // Old versions that are newer than the latest snapshot are not cleaned up. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let (v4, v5, v6) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 200, b"second"); - server.mock_add_version(v2, v3, 300, b"third"); - server.mock_add_snapshot(v3, 301, b"snap 1"); - server.mock_add_version(v3, v4, 400, b"fourth"); - server.mock_add_version(v4, v5, 500, b"fifth"); - server.mock_add_version(v5, v6, 600, b"sixth"); - server.mock_set_latest(v6); - - let mut expected = server.empty_clone(); - expected.mock_add_snapshot(v3, 301, b"snap 1"); - expected.mock_add_version(v3, v4, 400, b"fourth"); - expected.mock_add_version(v4, v5, 500, b"fifth"); - expected.mock_add_version(v5, v6, 600, b"sixth"); - expected.mock_set_latest(v6); - - assert_ne!(server.unencrypted(), expected.unencrypted()); - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn cleanup_children_of_latest() { - // New versions that are children of the latest version are not cleaned up. - let mut server = make_server(); - let (v1, v2, v3) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let (vnew1, vnew2) = (Uuid::new_v4(), Uuid::new_v4()); - server.mock_add_version(v1, v2, 1000, b"second"); - server.mock_add_version(v2, v3, 1000, b"third"); - server.mock_add_version(v3, vnew1, 1000, b"new 1"); - server.mock_add_version(v3, vnew2, 1000, b"new 2"); - // Two replicas are adding new versions, but v3 is still latest. - server.mock_set_latest(v3); - - let expected = server.clone(); - - server.cleanup().unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn add_snapshot() { - let mut server = make_server(); - let v = Uuid::new_v4(); - - let mut expected = server.empty_clone(); - expected.mock_add_snapshot(v, INSERTION_TIME, b"SNAP"); - - assert_ne!(server.unencrypted(), expected.unencrypted()); - server.add_snapshot(v, b"SNAP".to_vec()).unwrap(); - assert_eq!(server.unencrypted(), expected.unencrypted()); - } - - #[test] - fn get_snapshot_missing() { - let mut server = make_server(); - assert_eq!(server.get_snapshot().unwrap(), None); - } - - #[test] - fn get_snapshot_present() { - let mut server = make_server(); - let v = Uuid::new_v4(); - server.mock_add_snapshot(v, 1000, b"SNAP"); - assert_eq!(server.get_snapshot().unwrap(), Some((v, b"SNAP".to_vec()))); - } -} diff --git a/taskchampion/taskchampion/src/server/cloud/service.rs b/taskchampion/taskchampion/src/server/cloud/service.rs deleted file mode 100644 index 84b1c24ef..000000000 --- a/taskchampion/taskchampion/src/server/cloud/service.rs +++ /dev/null @@ -1,38 +0,0 @@ -use crate::errors::Result; - -/// Information about an object as returned from `Service::list` -pub(in crate::server) struct ObjectInfo { - /// Name of the object. - pub(in crate::server) name: Vec, - /// Creation time of the object, in seconds since the UNIX epoch. - pub(in crate::server) creation: u64, -} - -/// An abstraction of a cloud-storage service. -/// -/// The underlying cloud storage is assumed to be a map from object names to object values, -/// similar to a HashMap, with the addition of a compare-and-swap operation. Object names -/// are always simple strings from the character set `[a-zA-Z0-9-]`, no more than 100 characters -/// in length. -pub(in crate::server) trait Service { - /// Put an object into cloud storage. If the object exists, it is overwritten. - fn put(&mut self, name: &[u8], value: &[u8]) -> Result<()>; - - /// Get an object from cloud storage, or None if the object does not exist. - fn get(&mut self, name: &[u8]) -> Result>>; - - /// Delete an object. Does nothing if the object does not exist. - fn del(&mut self, name: &[u8]) -> Result<()>; - - /// Enumerate objects with the given prefix. - fn list<'a>(&'a mut self, prefix: &[u8]) -> Box> + 'a>; - - /// Compare the existing object's value with `existing_value`, and replace with `new_value` - /// only if the values match. Returns true if the replacement occurred. - fn compare_and_swap( - &mut self, - name: &[u8], - existing_value: Option>, - new_value: Vec, - ) -> Result; -} diff --git a/taskchampion/taskchampion/src/server/config.rs b/taskchampion/taskchampion/src/server/config.rs deleted file mode 100644 index 20e0e6598..000000000 --- a/taskchampion/taskchampion/src/server/config.rs +++ /dev/null @@ -1,74 +0,0 @@ -use super::types::Server; -use crate::errors::Result; -#[cfg(feature = "server-gcp")] -use crate::server::cloud::gcp::GcpService; -#[cfg(feature = "cloud")] -use crate::server::cloud::CloudServer; -use crate::server::local::LocalServer; -#[cfg(feature = "server-sync")] -use crate::server::sync::SyncServer; -use std::path::PathBuf; -#[cfg(feature = "server-sync")] -use uuid::Uuid; - -/// The configuration for a replica's access to a sync server. -pub enum ServerConfig { - /// A local task database, for situations with a single replica. - Local { - /// Path containing the server's DB - server_dir: PathBuf, - }, - /// A remote taskchampion-sync-server instance - #[cfg(feature = "server-sync")] - Remote { - /// Sync server "origin"; a URL with schema and hostname but no path or trailing `/` - origin: String, - - /// Client ID to identify and authenticate this replica to the server - client_id: Uuid, - - /// Private encryption secret used to encrypt all data sent to the server. This can - /// be any suitably un-guessable string of bytes. - encryption_secret: Vec, - }, - /// A remote taskchampion-sync-server instance - #[cfg(feature = "server-gcp")] - Gcp { - /// Bucket in which to store the task data. This bucket must not be used for any other - /// purpose. - bucket: String, - /// Path to a GCP credential file, in JSON format. This is required for GCP access incase - /// some other application already makes use of Application Default Credentials. - /// See https://cloud.google.com/docs/authentication#service-accounts for more details. - /// See https://cloud.google.com/iam/docs/keys-create-delete for instructions on how to - /// create a service account key. - credential_path: Option, - /// Private encryption secret used to encrypt all data sent to the server. This can - /// be any suitably un-guessable string of bytes. - encryption_secret: Vec, - }, -} - -impl ServerConfig { - /// Get a server based on this configuration - pub fn into_server(self) -> Result> { - Ok(match self { - ServerConfig::Local { server_dir } => Box::new(LocalServer::new(server_dir)?), - #[cfg(feature = "server-sync")] - ServerConfig::Remote { - origin, - client_id, - encryption_secret, - } => Box::new(SyncServer::new(origin, client_id, encryption_secret)?), - #[cfg(feature = "server-gcp")] - ServerConfig::Gcp { - bucket, - credential_path, - encryption_secret, - } => Box::new(CloudServer::new( - GcpService::new(bucket, credential_path)?, - encryption_secret, - )?), - }) - } -} diff --git a/taskchampion/taskchampion/src/server/encryption.rs b/taskchampion/taskchampion/src/server/encryption.rs deleted file mode 100644 index 23fa17a9c..000000000 --- a/taskchampion/taskchampion/src/server/encryption.rs +++ /dev/null @@ -1,414 +0,0 @@ -/// This module implements the encryption specified in the sync-protocol -/// document. -use crate::errors::{Error, Result}; -use ring::{aead, pbkdf2, rand, rand::SecureRandom}; -use uuid::Uuid; - -const PBKDF2_ITERATIONS: u32 = 600000; -const ENVELOPE_VERSION: u8 = 1; -const AAD_LEN: usize = 17; -const TASK_APP_ID: u8 = 1; - -/// An Cryptor stores a secret and allows sealing and unsealing. It derives a key from the secret, -/// which takes a nontrivial amount of time, so it should be created once and re-used for the given -/// context. -#[derive(Clone)] -pub(super) struct Cryptor { - key: aead::LessSafeKey, - rng: rand::SystemRandom, -} - -impl Cryptor { - pub(super) fn new(salt: impl AsRef<[u8]>, secret: &Secret) -> Result { - Ok(Cryptor { - key: Self::derive_key(salt, secret)?, - rng: rand::SystemRandom::new(), - }) - } - - /// Generate a suitable random salt. - pub(super) fn gen_salt() -> Result> { - let rng = rand::SystemRandom::new(); - let mut salt = [0u8; 16]; - rng.fill(&mut salt) - .map_err(|_| anyhow::anyhow!("error generating random salt"))?; - Ok(salt.to_vec()) - } - - /// Derive a key as specified for version 1. Note that this may take 10s of ms. - fn derive_key(salt: impl AsRef<[u8]>, secret: &Secret) -> Result { - let mut key_bytes = vec![0u8; aead::CHACHA20_POLY1305.key_len()]; - pbkdf2::derive( - pbkdf2::PBKDF2_HMAC_SHA256, - std::num::NonZeroU32::new(PBKDF2_ITERATIONS).unwrap(), - salt.as_ref(), - secret.as_ref(), - &mut key_bytes, - ); - - let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key_bytes) - .map_err(|_| anyhow::anyhow!("error while creating AEAD key"))?; - Ok(aead::LessSafeKey::new(unbound_key)) - } - - /// Encrypt the given payload. - pub(super) fn seal(&self, payload: Unsealed) -> Result { - let Unsealed { - version_id, - mut payload, - } = payload; - - let mut nonce_buf = [0u8; aead::NONCE_LEN]; - self.rng - .fill(&mut nonce_buf) - .map_err(|_| anyhow::anyhow!("error generating random nonce"))?; - let nonce = aead::Nonce::assume_unique_for_key(nonce_buf); - - let aad = self.make_aad(version_id); - - let tag = self - .key - .seal_in_place_separate_tag(nonce, aad, &mut payload) - .map_err(|_| anyhow::anyhow!("error while sealing"))?; - payload.extend_from_slice(tag.as_ref()); - - let env = Envelope { - nonce: &nonce_buf, - payload: payload.as_ref(), - }; - - Ok(Sealed { - version_id, - payload: env.to_bytes(), - }) - } - - /// Decrypt the given payload, verifying it was created for the given version_id - pub(super) fn unseal(&self, payload: Sealed) -> Result { - let Sealed { - version_id, - payload, - } = payload; - - let env = Envelope::from_bytes(&payload)?; - - let mut nonce = [0u8; aead::NONCE_LEN]; - nonce.copy_from_slice(env.nonce); - let nonce = aead::Nonce::assume_unique_for_key(nonce); - let aad = self.make_aad(version_id); - - let mut payload = env.payload.to_vec(); - let plaintext = self - .key - .open_in_place(nonce, aad, payload.as_mut()) - .map_err(|_| anyhow::anyhow!("error while unsealing encrypted value"))?; - - Ok(Unsealed { - version_id, - payload: plaintext.to_vec(), - }) - } - - fn make_aad(&self, version_id: Uuid) -> aead::Aad<[u8; AAD_LEN]> { - let mut aad = [0u8; AAD_LEN]; - aad[0] = TASK_APP_ID; - aad[1..].copy_from_slice(version_id.as_bytes()); - aead::Aad::from(aad) - } -} - -/// Secret represents a secret key as used for encryption and decryption. -pub(super) struct Secret(pub(super) Vec); - -impl From> for Secret { - fn from(bytes: Vec) -> Self { - Self(bytes) - } -} - -impl AsRef<[u8]> for Secret { - fn as_ref(&self) -> &[u8] { - &self.0 - } -} - -/// Envelope for the data stored on the server, containing the information -/// required to decrypt. -#[derive(Debug, PartialEq, Eq)] -struct Envelope<'a> { - nonce: &'a [u8], - payload: &'a [u8], -} - -impl<'a> Envelope<'a> { - fn from_bytes(buf: &'a [u8]) -> Result> { - if buf.len() <= 1 + aead::NONCE_LEN { - return Err(Error::Server(String::from("envelope is too small"))); - } - - let version = buf[0]; - if version != ENVELOPE_VERSION { - return Err(Error::Server(format!( - "unrecognized encryption envelope version {}", - version - ))); - } - - Ok(Envelope { - nonce: &buf[1..1 + aead::NONCE_LEN], - payload: &buf[1 + aead::NONCE_LEN..], - }) - } - - fn to_bytes(&self) -> Vec { - let mut buf = Vec::with_capacity(1 + self.nonce.len() + self.payload.len()); - - buf.push(ENVELOPE_VERSION); - buf.extend_from_slice(self.nonce); - buf.extend_from_slice(self.payload); - buf - } -} - -/// A unsealed payload with an attached version_id. The version_id is used to -/// validate the context of the payload on unsealing. -pub(super) struct Unsealed { - pub(super) version_id: Uuid, - pub(super) payload: Vec, -} - -impl From for Vec { - fn from(val: Unsealed) -> Self { - val.payload - } -} - -/// An encrypted payload -pub(super) struct Sealed { - pub(super) version_id: Uuid, - pub(super) payload: Vec, -} - -impl AsRef<[u8]> for Sealed { - fn as_ref(&self) -> &[u8] { - self.payload.as_ref() - } -} - -impl From for Vec { - fn from(val: Sealed) -> Self { - val.payload - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - - fn make_salt() -> Vec { - Cryptor::gen_salt().unwrap() - } - - #[test] - fn envelope_round_trip() { - let env = Envelope { - nonce: &[2; 12], - payload: b"HELLO", - }; - - let bytes = env.to_bytes(); - let env2 = Envelope::from_bytes(&bytes).unwrap(); - assert_eq!(env, env2); - } - - #[test] - fn envelope_bad_version() { - let env = Envelope { - nonce: &[2; 12], - payload: b"HELLO", - }; - - let mut bytes = env.to_bytes(); - bytes[0] = 99; - assert!(Envelope::from_bytes(&bytes).is_err()); - } - - #[test] - fn envelope_too_short() { - let env = Envelope { - nonce: &[2; 12], - payload: b"HELLO", - }; - - let bytes = env.to_bytes(); - let bytes = &bytes[..10]; - assert!(Envelope::from_bytes(bytes).is_err()); - } - - #[test] - fn round_trip() { - let version_id = Uuid::new_v4(); - let payload = b"HISTORY REPEATS ITSELF".to_vec(); - - let secret = Secret(b"SEKRIT".to_vec()); - let cryptor = Cryptor::new(make_salt(), &secret).unwrap(); - - let unsealed = Unsealed { - version_id, - payload: payload.clone(), - }; - let sealed = cryptor.seal(unsealed).unwrap(); - let unsealed = cryptor.unseal(sealed).unwrap(); - - assert_eq!(unsealed.payload, payload); - assert_eq!(unsealed.version_id, version_id); - } - - #[test] - fn round_trip_bad_key() { - let version_id = Uuid::new_v4(); - let payload = b"HISTORY REPEATS ITSELF".to_vec(); - let salt = make_salt(); - - let secret = Secret(b"SEKRIT".to_vec()); - let cryptor = Cryptor::new(&salt, &secret).unwrap(); - - let unsealed = Unsealed { - version_id, - payload, - }; - let sealed = cryptor.seal(unsealed).unwrap(); - - let secret = Secret(b"DIFFERENT_SECRET".to_vec()); - let cryptor = Cryptor::new(&salt, &secret).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn round_trip_bad_version() { - let version_id = Uuid::new_v4(); - let payload = b"HISTORY REPEATS ITSELF".to_vec(); - - let secret = Secret(b"SEKRIT".to_vec()); - let cryptor = Cryptor::new(make_salt(), &secret).unwrap(); - - let unsealed = Unsealed { - version_id, - payload, - }; - let mut sealed = cryptor.seal(unsealed).unwrap(); - sealed.version_id = Uuid::new_v4(); // change the version_id - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn round_trip_bad_salt() { - let version_id = Uuid::new_v4(); - let payload = b"HISTORY REPEATS ITSELF".to_vec(); - - let secret = Secret(b"SEKRIT".to_vec()); - let cryptor = Cryptor::new(make_salt(), &secret).unwrap(); - - let unsealed = Unsealed { - version_id, - payload, - }; - let sealed = cryptor.seal(unsealed).unwrap(); - - let cryptor = Cryptor::new(make_salt(), &secret).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - mod externally_valid { - // validate data generated by generate-test-data.py. The intent is to - // validate that this format matches the specification by implementing - // the specification in a second language - use super::*; - use pretty_assertions::assert_eq; - - /// The values in generate-test-data.py - fn defaults() -> (Uuid, Vec, Vec) { - let version_id = Uuid::parse_str("b0517957-f912-4d49-8330-f612e73030c4").unwrap(); - let encryption_secret = b"b4a4e6b7b811eda1dc1a2693ded".to_vec(); - let client_id = Uuid::parse_str("0666d464-418a-4a08-ad53-6f15c78270cd").unwrap(); - let salt = client_id.as_bytes().to_vec(); - (version_id, salt, encryption_secret) - } - - #[test] - fn good() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-good.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - let unsealed = cryptor.unseal(sealed).unwrap(); - - assert_eq!(unsealed.payload, b"SUCCESS"); - assert_eq!(unsealed.version_id, version_id); - } - - #[test] - fn bad_version_id() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-bad-version-id.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn bad_salt() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-bad-client-id.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn bad_secret() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-bad-secret.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn bad_version() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-bad-version.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - - #[test] - fn bad_app_id() { - let (version_id, salt, encryption_secret) = defaults(); - let sealed = Sealed { - version_id, - payload: include_bytes!("test-bad-app-id.data").to_vec(), - }; - - let cryptor = Cryptor::new(salt, &Secret(encryption_secret)).unwrap(); - assert!(cryptor.unseal(sealed).is_err()); - } - } -} diff --git a/taskchampion/taskchampion/src/server/generate-test-data.py b/taskchampion/taskchampion/src/server/generate-test-data.py deleted file mode 100644 index d4f818190..000000000 --- a/taskchampion/taskchampion/src/server/generate-test-data.py +++ /dev/null @@ -1,77 +0,0 @@ -# This file generates test-encrypted.data. To run it: -# - pip install cryptography pbkdf2 -# - python taskchampion/taskchampion/src/server/generate-test-data.py taskchampion/taskchampion/src/server/ - -import os -import hashlib -import pbkdf2 -import secrets -import sys -import uuid - -from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 - -# these values match values used in the rust tests -client_id = "0666d464-418a-4a08-ad53-6f15c78270cd" -encryption_secret = b"b4a4e6b7b811eda1dc1a2693ded" -version_id = "b0517957-f912-4d49-8330-f612e73030c4" - -def gen( - version_id=version_id, client_id=client_id, encryption_secret=encryption_secret, - app_id=1, version=1): - # first, generate the encryption key - salt = uuid.UUID(client_id).bytes - key = pbkdf2.PBKDF2( - encryption_secret, - salt, - digestmodule=hashlib.sha256, - iterations=600000, - ).read(32) - - # create a nonce - nonce = secrets.token_bytes(12) - - assert len(b"\x01") == 1 - # create the AAD - aad = b''.join([ - bytes([app_id]), - uuid.UUID(version_id).bytes, - ]) - - # encrypt using AEAD - chacha = ChaCha20Poly1305(key) - ciphertext = chacha.encrypt(nonce, b"SUCCESS", aad) - - # create the envelope - envelope = b''.join([ - bytes([version]), - nonce, - ciphertext, - ]) - - return envelope - - -def main(): - dir = sys.argv[1] - - with open(os.path.join(dir, 'test-good.data'), "wb") as f: - f.write(gen()) - - with open(os.path.join(dir, 'test-bad-version-id.data'), "wb") as f: - f.write(gen(version_id=uuid.uuid4().hex)) - - with open(os.path.join(dir, 'test-bad-client-id.data'), "wb") as f: - f.write(gen(client_id=uuid.uuid4().hex)) - - with open(os.path.join(dir, 'test-bad-secret.data'), "wb") as f: - f.write(gen(encryption_secret=b"xxxxxxxxxxxxxxxxxxxxx")) - - with open(os.path.join(dir, 'test-bad-version.data'), "wb") as f: - f.write(gen(version=99)) - - with open(os.path.join(dir, 'test-bad-app-id.data'), "wb") as f: - f.write(gen(app_id=99)) - - -main() diff --git a/taskchampion/taskchampion/src/server/local/mod.rs b/taskchampion/taskchampion/src/server/local/mod.rs deleted file mode 100644 index a5a4d2f98..000000000 --- a/taskchampion/taskchampion/src/server/local/mod.rs +++ /dev/null @@ -1,258 +0,0 @@ -use crate::errors::Result; -use crate::server::{ - AddVersionResult, GetVersionResult, HistorySegment, Server, Snapshot, SnapshotUrgency, - VersionId, NIL_VERSION_ID, -}; -use crate::storage::sqlite::StoredUuid; -use anyhow::Context; -use rusqlite::params; -use rusqlite::OptionalExtension; -use serde::{Deserialize, Serialize}; -use std::path::Path; -use uuid::Uuid; - -#[derive(Serialize, Deserialize, Debug)] -struct Version { - version_id: VersionId, - parent_version_id: VersionId, - history_segment: HistorySegment, -} - -pub struct LocalServer { - con: rusqlite::Connection, -} - -impl LocalServer { - fn txn(&mut self) -> Result { - let txn = self.con.transaction()?; - Ok(txn) - } - - /// A server which has no notion of clients, signatures, encryption, etc. - pub fn new>(directory: P) -> Result { - let db_file = directory - .as_ref() - .join("taskchampion-local-sync-server.sqlite3"); - let con = rusqlite::Connection::open(db_file)?; - - let queries = vec![ - "CREATE TABLE IF NOT EXISTS data (key STRING PRIMARY KEY, value STRING);", - "CREATE TABLE IF NOT EXISTS versions (version_id STRING PRIMARY KEY, parent_version_id STRING, data STRING);", - ]; - for q in queries { - con.execute(q, []).context("Creating table")?; - } - - Ok(LocalServer { con }) - } - - fn get_latest_version_id(&mut self) -> Result { - let t = self.txn()?; - let result: Option = t - .query_row( - "SELECT value FROM data WHERE key = 'latest_version_id' LIMIT 1", - rusqlite::params![], - |r| r.get(0), - ) - .optional()?; - Ok(result.map(|x| x.0).unwrap_or(NIL_VERSION_ID)) - } - - fn set_latest_version_id(&mut self, version_id: VersionId) -> Result<()> { - let t = self.txn()?; - t.execute( - "INSERT OR REPLACE INTO data (key, value) VALUES ('latest_version_id', ?)", - params![&StoredUuid(version_id)], - ) - .context("Update task query")?; - t.commit()?; - Ok(()) - } - - fn get_version_by_parent_version_id( - &mut self, - parent_version_id: VersionId, - ) -> Result> { - let t = self.txn()?; - let r = t.query_row( - "SELECT version_id, parent_version_id, data FROM versions WHERE parent_version_id = ?", - params![&StoredUuid(parent_version_id)], - |r| { - let version_id: StoredUuid = r.get("version_id")?; - let parent_version_id: StoredUuid = r.get("parent_version_id")?; - - Ok(Version{ - version_id: version_id.0, - parent_version_id: parent_version_id.0, - history_segment: r.get("data")?, - })} - ) - .optional() - .context("Get version query") - ?; - Ok(r) - } - - fn add_version_by_parent_version_id(&mut self, version: Version) -> Result<()> { - let t = self.txn()?; - t.execute( - "INSERT INTO versions (version_id, parent_version_id, data) VALUES (?, ?, ?)", - params![ - StoredUuid(version.version_id), - StoredUuid(version.parent_version_id), - version.history_segment - ], - )?; - t.commit()?; - Ok(()) - } -} - -impl Server for LocalServer { - // TODO: better transaction isolation for add_version (gets and sets should be in the same - // transaction) - - fn add_version( - &mut self, - parent_version_id: VersionId, - history_segment: HistorySegment, - ) -> Result<(AddVersionResult, SnapshotUrgency)> { - // no client lookup - // no signature validation - - // check the parent_version_id for linearity - let latest_version_id = self.get_latest_version_id()?; - if latest_version_id != NIL_VERSION_ID && parent_version_id != latest_version_id { - return Ok(( - AddVersionResult::ExpectedParentVersion(latest_version_id), - SnapshotUrgency::None, - )); - } - - // invent a new ID for this version - let version_id = Uuid::new_v4(); - - self.add_version_by_parent_version_id(Version { - version_id, - parent_version_id, - history_segment, - })?; - self.set_latest_version_id(version_id)?; - - Ok((AddVersionResult::Ok(version_id), SnapshotUrgency::None)) - } - - fn get_child_version(&mut self, parent_version_id: VersionId) -> Result { - if let Some(version) = self.get_version_by_parent_version_id(parent_version_id)? { - Ok(GetVersionResult::Version { - version_id: version.version_id, - parent_version_id: version.parent_version_id, - history_segment: version.history_segment, - }) - } else { - Ok(GetVersionResult::NoSuchVersion) - } - } - - fn add_snapshot(&mut self, _version_id: VersionId, _snapshot: Snapshot) -> Result<()> { - // the local server never requests a snapshot, so it should never get one - unreachable!() - } - - fn get_snapshot(&mut self) -> Result> { - Ok(None) - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn test_empty() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut server = LocalServer::new(tmp_dir.path())?; - let child_version = server.get_child_version(NIL_VERSION_ID)?; - assert_eq!(child_version, GetVersionResult::NoSuchVersion); - Ok(()) - } - - #[test] - fn test_add_zero_base() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut server = LocalServer::new(tmp_dir.path())?; - let history = b"1234".to_vec(); - match server.add_version(NIL_VERSION_ID, history.clone())?.0 { - AddVersionResult::ExpectedParentVersion(_) => { - panic!("should have accepted the version") - } - AddVersionResult::Ok(version_id) => { - let new_version = server.get_child_version(NIL_VERSION_ID)?; - assert_eq!( - new_version, - GetVersionResult::Version { - version_id, - parent_version_id: NIL_VERSION_ID, - history_segment: history, - } - ); - } - } - - Ok(()) - } - - #[test] - fn test_add_nonzero_base() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut server = LocalServer::new(tmp_dir.path())?; - let history = b"1234".to_vec(); - let parent_version_id = Uuid::new_v4() as VersionId; - - // This is OK because the server has no latest_version_id yet - match server.add_version(parent_version_id, history.clone())?.0 { - AddVersionResult::ExpectedParentVersion(_) => { - panic!("should have accepted the version") - } - AddVersionResult::Ok(version_id) => { - let new_version = server.get_child_version(parent_version_id)?; - assert_eq!( - new_version, - GetVersionResult::Version { - version_id, - parent_version_id, - history_segment: history, - } - ); - } - } - - Ok(()) - } - - #[test] - fn test_add_nonzero_base_forbidden() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut server = LocalServer::new(tmp_dir.path())?; - let history = b"1234".to_vec(); - let parent_version_id = Uuid::new_v4() as VersionId; - - // add a version - if let (AddVersionResult::ExpectedParentVersion(_), SnapshotUrgency::None) = - server.add_version(parent_version_id, history.clone())? - { - panic!("should have accepted the version") - } - - // then add another, not based on that one - if let (AddVersionResult::Ok(_), SnapshotUrgency::None) = - server.add_version(parent_version_id, history)? - { - panic!("should not have accepted the version") - } - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/server/mod.rs b/taskchampion/taskchampion/src/server/mod.rs deleted file mode 100644 index caccdee02..000000000 --- a/taskchampion/taskchampion/src/server/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -/** - -This module defines the client interface to TaskChampion sync servers. -It defines a [trait](crate::server::Server) for servers, and implements both local and remote servers. - -Typical uses of this crate do not interact directly with this module; [`ServerConfig`](crate::ServerConfig) is sufficient. -However, users who wish to implement their own server interfaces can implement the traits defined here and pass the result to [`Replica`](crate::Replica). - -*/ - -#[cfg(test)] -pub(crate) mod test; - -mod config; -mod local; -mod op; -mod types; - -#[cfg(feature = "encryption")] -mod encryption; - -#[cfg(feature = "server-sync")] -mod sync; - -#[cfg(feature = "cloud")] -mod cloud; - -pub use config::ServerConfig; -pub use types::*; - -pub(crate) use op::SyncOp; diff --git a/taskchampion/taskchampion/src/server/op.rs b/taskchampion/taskchampion/src/server/op.rs deleted file mode 100644 index abd592d17..000000000 --- a/taskchampion/taskchampion/src/server/op.rs +++ /dev/null @@ -1,421 +0,0 @@ -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -/// A SyncOp defines a single change to the task database, that can be synchronized -/// via a server. -#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] -pub enum SyncOp { - /// Create a new task. - /// - /// On application, if the task already exists, the operation does nothing. - Create { uuid: Uuid }, - - /// Delete an existing task. - /// - /// On application, if the task does not exist, the operation does nothing. - Delete { uuid: Uuid }, - - /// Update an existing task, setting the given property to the given value. If the value is - /// None, then the corresponding property is deleted. - /// - /// If the given task does not exist, the operation does nothing. - Update { - uuid: Uuid, - property: String, - value: Option, - timestamp: DateTime, - }, -} - -use SyncOp::*; - -impl SyncOp { - // Transform takes two operations A and B that happened concurrently and produces two - // operations A' and B' such that `apply(apply(S, A), B') = apply(apply(S, B), A')`. This - // function is used to serialize operations in a process similar to a Git "rebase". - // - // * - // / \ - // op1 / \ op2 - // / \ - // * * - // - // this function "completes the diamond: - // - // * * - // \ / - // op2' \ / op1' - // \ / - // * - // - // such that applying op2' after op1 has the same effect as applying op1' after op2. This - // allows two different systems which have already applied op1 and op2, respectively, and thus - // reached different states, to return to the same state by applying op2' and op1', - // respectively. - pub fn transform(operation1: SyncOp, operation2: SyncOp) -> (Option, Option) { - match (&operation1, &operation2) { - // Two creations or deletions of the same uuid reach the same state, so there's no need - // for any further operations to bring the state together. - (&Create { uuid: uuid1 }, &Create { uuid: uuid2 }) if uuid1 == uuid2 => (None, None), - (&Delete { uuid: uuid1 }, &Delete { uuid: uuid2 }) if uuid1 == uuid2 => (None, None), - - // Given a create and a delete of the same task, one of the operations is invalid: the - // create implies the task does not exist, but the delete implies it exists. Somewhat - // arbitrarily, we prefer the Create - (&Create { uuid: uuid1 }, &Delete { uuid: uuid2 }) if uuid1 == uuid2 => { - (Some(operation1), None) - } - (&Delete { uuid: uuid1 }, &Create { uuid: uuid2 }) if uuid1 == uuid2 => { - (None, Some(operation2)) - } - - // And again from an Update and a Create, prefer the Update - (&Update { uuid: uuid1, .. }, &Create { uuid: uuid2 }) if uuid1 == uuid2 => { - (Some(operation1), None) - } - (&Create { uuid: uuid1 }, &Update { uuid: uuid2, .. }) if uuid1 == uuid2 => { - (None, Some(operation2)) - } - - // Given a delete and an update, prefer the delete - (&Update { uuid: uuid1, .. }, &Delete { uuid: uuid2 }) if uuid1 == uuid2 => { - (None, Some(operation2)) - } - (&Delete { uuid: uuid1 }, &Update { uuid: uuid2, .. }) if uuid1 == uuid2 => { - (Some(operation1), None) - } - - // Two updates to the same property of the same task might conflict. - ( - Update { - uuid: uuid1, - property: property1, - value: value1, - timestamp: timestamp1, - }, - Update { - uuid: uuid2, - property: property2, - value: value2, - timestamp: timestamp2, - }, - ) if uuid1 == uuid2 && property1 == property2 => { - // if the value is the same, there's no conflict - if value1 == value2 { - (None, None) - } else if timestamp1 < timestamp2 { - // prefer the later modification - (None, Some(operation2)) - } else { - // prefer the later modification or, if the modifications are the same, - // just choose one of them - (Some(operation1), None) - } - } - - // anything else is not a conflict of any sort, so return the operations unchanged - (_, _) => (Some(operation1), Some(operation2)), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::errors::Result; - use crate::storage::InMemoryStorage; - use crate::taskdb::TaskDb; - use chrono::{Duration, Utc}; - use pretty_assertions::assert_eq; - use proptest::prelude::*; - - #[test] - fn test_json_create() -> Result<()> { - let uuid = Uuid::new_v4(); - let op = Create { uuid }; - let json = serde_json::to_string(&op)?; - assert_eq!(json, format!(r#"{{"Create":{{"uuid":"{}"}}}}"#, uuid)); - let deser: SyncOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_delete() -> Result<()> { - let uuid = Uuid::new_v4(); - let op = Delete { uuid }; - let json = serde_json::to_string(&op)?; - assert_eq!(json, format!(r#"{{"Delete":{{"uuid":"{}"}}}}"#, uuid)); - let deser: SyncOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_update() -> Result<()> { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - let op = Update { - uuid, - property: "abc".into(), - value: Some("false".into()), - timestamp, - }; - - let json = serde_json::to_string(&op)?; - assert_eq!( - json, - format!( - r#"{{"Update":{{"uuid":"{}","property":"abc","value":"false","timestamp":"{:?}"}}}}"#, - uuid, timestamp, - ) - ); - let deser: SyncOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_update_none() -> Result<()> { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - let op = Update { - uuid, - property: "abc".into(), - value: None, - timestamp, - }; - - let json = serde_json::to_string(&op)?; - assert_eq!( - json, - format!( - r#"{{"Update":{{"uuid":"{}","property":"abc","value":null,"timestamp":"{:?}"}}}}"#, - uuid, timestamp, - ) - ); - let deser: SyncOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - fn test_transform( - setup: Option, - o1: SyncOp, - o2: SyncOp, - exp1p: Option, - exp2p: Option, - ) { - let (o1p, o2p) = SyncOp::transform(o1.clone(), o2.clone()); - assert_eq!((&o1p, &o2p), (&exp1p, &exp2p)); - - // check that the two operation sequences have the same effect, enforcing the invariant of - // the transform function. - let mut db1 = TaskDb::new_inmemory(); - if let Some(ref o) = setup { - db1.apply(o.clone()).unwrap(); - } - db1.apply(o1).unwrap(); - if let Some(o) = o2p { - db1.apply(o).unwrap(); - } - - let mut db2 = TaskDb::new_inmemory(); - if let Some(ref o) = setup { - db2.apply(o.clone()).unwrap(); - } - db2.apply(o2).unwrap(); - if let Some(o) = o1p { - db2.apply(o).unwrap(); - } - - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - } - - #[test] - fn test_unrelated_create() { - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - test_transform( - None, - Create { uuid: uuid1 }, - Create { uuid: uuid2 }, - Some(Create { uuid: uuid1 }), - Some(Create { uuid: uuid2 }), - ); - } - - #[test] - fn test_related_updates_different_props() { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - test_transform( - Some(Create { uuid }), - Update { - uuid, - property: "abc".into(), - value: Some("true".into()), - timestamp, - }, - Update { - uuid, - property: "def".into(), - value: Some("false".into()), - timestamp, - }, - Some(Update { - uuid, - property: "abc".into(), - value: Some("true".into()), - timestamp, - }), - Some(Update { - uuid, - property: "def".into(), - value: Some("false".into()), - timestamp, - }), - ); - } - - #[test] - fn test_related_updates_same_prop() { - let uuid = Uuid::new_v4(); - let timestamp1 = Utc::now(); - let timestamp2 = timestamp1 + Duration::seconds(10); - - test_transform( - Some(Create { uuid }), - Update { - uuid, - property: "abc".into(), - value: Some("true".into()), - timestamp: timestamp1, - }, - Update { - uuid, - property: "abc".into(), - value: Some("false".into()), - timestamp: timestamp2, - }, - None, - Some(Update { - uuid, - property: "abc".into(), - value: Some("false".into()), - timestamp: timestamp2, - }), - ); - } - - #[test] - fn test_related_updates_same_prop_same_time() { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - test_transform( - Some(Create { uuid }), - Update { - uuid, - property: "abc".into(), - value: Some("true".into()), - timestamp, - }, - Update { - uuid, - property: "abc".into(), - value: Some("false".into()), - timestamp, - }, - Some(Update { - uuid, - property: "abc".into(), - value: Some("true".into()), - timestamp, - }), - None, - ); - } - - fn uuid_strategy() -> impl Strategy { - prop_oneof![ - Just(Uuid::parse_str("83a2f9ef-f455-4195-b92e-a54c161eebfc").unwrap()), - Just(Uuid::parse_str("56e0be07-c61f-494c-a54c-bdcfdd52d2a7").unwrap()), - Just(Uuid::parse_str("4b7ed904-f7b0-4293-8a10-ad452422c7b3").unwrap()), - Just(Uuid::parse_str("9bdd0546-07c8-4e1f-a9bc-9d6299f4773b").unwrap()), - ] - } - - fn operation_strategy() -> impl Strategy { - prop_oneof![ - uuid_strategy().prop_map(|uuid| Create { uuid }), - uuid_strategy().prop_map(|uuid| Delete { uuid }), - (uuid_strategy(), "(title|project|status)").prop_map(|(uuid, property)| { - Update { - uuid, - property, - value: Some("true".into()), - timestamp: Utc::now(), - } - }), - ] - } - - proptest! { - #![proptest_config(ProptestConfig { - cases: 1024, .. ProptestConfig::default() - })] - #[test] - // check that the two operation sequences have the same effect, enforcing the invariant of - // the transform function. - fn transform_invariant_holds(o1 in operation_strategy(), o2 in operation_strategy()) { - let (o1p, o2p) = SyncOp::transform(o1.clone(), o2.clone()); - - let mut db1 = TaskDb::new(Box::new(InMemoryStorage::new())); - let mut db2 = TaskDb::new(Box::new(InMemoryStorage::new())); - - // Ensure that any expected tasks already exist - if let Update{ uuid, .. } = o1 { - let _ = db1.apply(Create{uuid}); - let _ = db2.apply(Create{uuid}); - } - - if let Update{ uuid, .. } = o2 { - let _ = db1.apply(Create{uuid}); - let _ = db2.apply(Create{uuid}); - } - - if let Delete{ uuid } = o1 { - let _ = db1.apply(Create{uuid}); - let _ = db2.apply(Create{uuid}); - } - - if let Delete{ uuid } = o2 { - let _ = db1.apply(Create{uuid}); - let _ = db2.apply(Create{uuid}); - } - - // if applying the initial operations fail, that indicates the operation was invalid - // in the base state, so consider the case successful. - if db1.apply(o1).is_err() { - return Ok(()); - } - if db2.apply(o2).is_err() { - return Ok(()); - } - - if let Some(o) = o2p { - db1.apply(o).map_err(|e| TestCaseError::Fail(format!("Applying to db1: {}", e).into()))?; - } - if let Some(o) = o1p { - db2.apply(o).map_err(|e| TestCaseError::Fail(format!("Applying to db2: {}", e).into()))?; - } - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - } - } -} diff --git a/taskchampion/taskchampion/src/server/sync/mod.rs b/taskchampion/taskchampion/src/server/sync/mod.rs deleted file mode 100644 index 3ae86aa23..000000000 --- a/taskchampion/taskchampion/src/server/sync/mod.rs +++ /dev/null @@ -1,192 +0,0 @@ -use crate::errors::{Error, Result}; -use crate::server::{ - AddVersionResult, GetVersionResult, HistorySegment, Server, Snapshot, SnapshotUrgency, - VersionId, -}; -use std::time::Duration; -use url::Url; -use uuid::Uuid; - -use super::encryption::{Cryptor, Sealed, Secret, Unsealed}; - -pub struct SyncServer { - origin: String, - client_id: Uuid, - cryptor: Cryptor, - agent: ureq::Agent, -} - -/// The content-type for history segments (opaque blobs of bytes) -const HISTORY_SEGMENT_CONTENT_TYPE: &str = "application/vnd.taskchampion.history-segment"; - -/// The content-type for snapshots (opaque blobs of bytes) -const SNAPSHOT_CONTENT_TYPE: &str = "application/vnd.taskchampion.snapshot"; - -/// A SyncServer communicates with a sync server over HTTP. -impl SyncServer { - /// Construct a new SyncServer. The `origin` is the sync server's protocol and hostname - /// without a trailing slash, such as `https://tcsync.example.com`. Pass a client_id to - /// identify this client to the server. Multiple replicas synchronizing the same task history - /// should use the same client_id. - pub fn new(origin: String, client_id: Uuid, encryption_secret: Vec) -> Result { - let origin = Url::parse(&origin) - .map_err(|_| Error::Server(format!("Could not parse {} as a URL", origin)))?; - if origin.path() != "/" { - return Err(Error::Server(format!( - "Server origin must have an empty path; got {}", - origin - ))); - } - Ok(SyncServer { - origin: origin.to_string(), - client_id, - cryptor: Cryptor::new(client_id, &Secret(encryption_secret.to_vec()))?, - agent: ureq::AgentBuilder::new() - .timeout_connect(Duration::from_secs(10)) - .timeout_read(Duration::from_secs(60)) - .build(), - }) - } -} - -/// Read a UUID-bearing header or fail trying -fn get_uuid_header(resp: &ureq::Response, name: &str) -> Result { - let value = resp - .header(name) - .ok_or_else(|| anyhow::anyhow!("Response does not have {} header", name))?; - let value = Uuid::parse_str(value) - .map_err(|e| anyhow::anyhow!("{} header is not a valid UUID: {}", name, e))?; - Ok(value) -} - -/// Read the X-Snapshot-Request header and return a SnapshotUrgency -fn get_snapshot_urgency(resp: &ureq::Response) -> SnapshotUrgency { - match resp.header("X-Snapshot-Request") { - None => SnapshotUrgency::None, - Some(hdr) => match hdr { - "urgency=low" => SnapshotUrgency::Low, - "urgency=high" => SnapshotUrgency::High, - _ => SnapshotUrgency::None, - }, - } -} - -fn sealed_from_resp(resp: ureq::Response, version_id: Uuid, content_type: &str) -> Result { - use std::io::Read; - if resp.header("Content-Type") == Some(content_type) { - let mut reader = resp.into_reader(); - let mut payload = vec![]; - reader.read_to_end(&mut payload)?; - Ok(Sealed { - version_id, - payload, - }) - } else { - Err(Error::Server(String::from( - "Response did not have expected content-type", - ))) - } -} - -impl Server for SyncServer { - fn add_version( - &mut self, - parent_version_id: VersionId, - history_segment: HistorySegment, - ) -> Result<(AddVersionResult, SnapshotUrgency)> { - let url = format!("{}v1/client/add-version/{}", self.origin, parent_version_id); - let unsealed = Unsealed { - version_id: parent_version_id, - payload: history_segment, - }; - let sealed = self.cryptor.seal(unsealed)?; - match self - .agent - .post(&url) - .set("Content-Type", HISTORY_SEGMENT_CONTENT_TYPE) - .set("X-Client-Id", &self.client_id.to_string()) - .send_bytes(sealed.as_ref()) - { - Ok(resp) => { - let version_id = get_uuid_header(&resp, "X-Version-Id")?; - Ok(( - AddVersionResult::Ok(version_id), - get_snapshot_urgency(&resp), - )) - } - Err(ureq::Error::Status(status, resp)) if status == 409 => { - let parent_version_id = get_uuid_header(&resp, "X-Parent-Version-Id")?; - Ok(( - AddVersionResult::ExpectedParentVersion(parent_version_id), - SnapshotUrgency::None, - )) - } - Err(err) => Err(err.into()), - } - } - - fn get_child_version(&mut self, parent_version_id: VersionId) -> Result { - let url = format!( - "{}v1/client/get-child-version/{}", - self.origin, parent_version_id - ); - match self - .agent - .get(&url) - .set("X-Client-Id", &self.client_id.to_string()) - .call() - { - Ok(resp) => { - let parent_version_id = get_uuid_header(&resp, "X-Parent-Version-Id")?; - let version_id = get_uuid_header(&resp, "X-Version-Id")?; - let sealed = - sealed_from_resp(resp, parent_version_id, HISTORY_SEGMENT_CONTENT_TYPE)?; - let history_segment = self.cryptor.unseal(sealed)?.payload; - Ok(GetVersionResult::Version { - version_id, - parent_version_id, - history_segment, - }) - } - Err(ureq::Error::Status(status, _)) if status == 404 => { - Ok(GetVersionResult::NoSuchVersion) - } - Err(err) => Err(err.into()), - } - } - - fn add_snapshot(&mut self, version_id: VersionId, snapshot: Snapshot) -> Result<()> { - let url = format!("{}v1/client/add-snapshot/{}", self.origin, version_id); - let unsealed = Unsealed { - version_id, - payload: snapshot, - }; - let sealed = self.cryptor.seal(unsealed)?; - Ok(self - .agent - .post(&url) - .set("Content-Type", SNAPSHOT_CONTENT_TYPE) - .set("X-Client-Id", &self.client_id.to_string()) - .send_bytes(sealed.as_ref()) - .map(|_| ())?) - } - - fn get_snapshot(&mut self) -> Result> { - let url = format!("{}v1/client/snapshot", self.origin); - match self - .agent - .get(&url) - .set("X-Client-Id", &self.client_id.to_string()) - .call() - { - Ok(resp) => { - let version_id = get_uuid_header(&resp, "X-Version-Id")?; - let sealed = sealed_from_resp(resp, version_id, SNAPSHOT_CONTENT_TYPE)?; - let snapshot = self.cryptor.unseal(sealed)?.payload; - Ok(Some((version_id, snapshot))) - } - Err(ureq::Error::Status(status, _)) if status == 404 => Ok(None), - Err(err) => Err(err.into()), - } - } -} diff --git a/taskchampion/taskchampion/src/server/test-bad-app-id.data b/taskchampion/taskchampion/src/server/test-bad-app-id.data deleted file mode 100644 index e0dbb5f69..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-app-id.data +++ /dev/null @@ -1,2 +0,0 @@ -IµNêuÈ -;“Æ^¤¼¢9Iê±Ä‰·ïç©ÿiïbÀ› \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-bad-client-id.data b/taskchampion/taskchampion/src/server/test-bad-client-id.data deleted file mode 100644 index 10885b533..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-client-id.data +++ /dev/null @@ -1 +0,0 @@ -ÐÝhXÉå.ŠìEI” /Ç ÌÇBóë„Ô øÍè \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-bad-secret.data b/taskchampion/taskchampion/src/server/test-bad-secret.data deleted file mode 100644 index 435585345..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-secret.data +++ /dev/null @@ -1 +0,0 @@ -YÎ|ˆz JuâѾK¹çzFñ]Àáò¨bCxÎÞ˜ \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-bad-version-id.data b/taskchampion/taskchampion/src/server/test-bad-version-id.data deleted file mode 100644 index 3b14c54db..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-version-id.data +++ /dev/null @@ -1 +0,0 @@ -Ss´“ßL´‚|ð:=“Ë";ü—Ñž²¥5ï JK™=í \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-bad-version.data b/taskchampion/taskchampion/src/server/test-bad-version.data deleted file mode 100644 index 7a1380c57..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-version.data +++ /dev/null @@ -1 +0,0 @@ -czÇyÉäø3ìâ2Ýí­•ˆÌ6ÑLzôÚAà};„BÅ6@ \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-bad-version_id.data b/taskchampion/taskchampion/src/server/test-bad-version_id.data deleted file mode 100644 index 4a228ec4a..000000000 --- a/taskchampion/taskchampion/src/server/test-bad-version_id.data +++ /dev/null @@ -1,2 +0,0 @@ -B• -áÔ-×3%¦j£,*ߺ7ê©–QØKúO¦œFPZÝ \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test-good.data b/taskchampion/taskchampion/src/server/test-good.data deleted file mode 100644 index afe7678ba..000000000 --- a/taskchampion/taskchampion/src/server/test-good.data +++ /dev/null @@ -1 +0,0 @@ - tþ`&’ÇÑ_)Ó‰çÛúÇûÞgÿr}ˆ-øZ¸Às \ No newline at end of file diff --git a/taskchampion/taskchampion/src/server/test.rs b/taskchampion/taskchampion/src/server/test.rs deleted file mode 100644 index 165fa557b..000000000 --- a/taskchampion/taskchampion/src/server/test.rs +++ /dev/null @@ -1,131 +0,0 @@ -use crate::errors::Result; -use crate::server::{ - AddVersionResult, GetVersionResult, HistorySegment, Server, Snapshot, SnapshotUrgency, - VersionId, NIL_VERSION_ID, -}; -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; -use uuid::Uuid; - -struct Version { - version_id: VersionId, - parent_version_id: VersionId, - history_segment: HistorySegment, -} - -/// TestServer implements the Server trait with a test implementation. -#[derive(Clone)] -pub(crate) struct TestServer(Arc>); - -pub(crate) struct Inner { - latest_version_id: VersionId, - // NOTE: indexed by parent_version_id! - versions: HashMap, - snapshot_urgency: SnapshotUrgency, - snapshot: Option<(VersionId, Snapshot)>, -} - -impl TestServer { - /// A test server has no notion of clients, signatures, encryption, etc. - pub(crate) fn new() -> TestServer { - TestServer(Arc::new(Mutex::new(Inner { - latest_version_id: NIL_VERSION_ID, - versions: HashMap::new(), - snapshot_urgency: SnapshotUrgency::None, - snapshot: None, - }))) - } - // feel free to add any test utility functions here - - /// Get a boxed Server implementation referring to this TestServer - pub(crate) fn server(&self) -> Box { - Box::new(self.clone()) - } - - pub(crate) fn set_snapshot_urgency(&self, urgency: SnapshotUrgency) { - let mut inner = self.0.lock().unwrap(); - inner.snapshot_urgency = urgency; - } - - /// Get the latest snapshot added to this server - pub(crate) fn snapshot(&self) -> Option<(VersionId, Snapshot)> { - let inner = self.0.lock().unwrap(); - inner.snapshot.as_ref().cloned() - } - - /// Delete a version from storage - pub(crate) fn delete_version(&mut self, parent_version_id: VersionId) { - let mut inner = self.0.lock().unwrap(); - inner.versions.remove(&parent_version_id); - } -} - -impl Server for TestServer { - /// Add a new version. If the given version number is incorrect, this responds with the - /// appropriate version and expects the caller to try again. - fn add_version( - &mut self, - parent_version_id: VersionId, - history_segment: HistorySegment, - ) -> Result<(AddVersionResult, SnapshotUrgency)> { - let mut inner = self.0.lock().unwrap(); - - // no client lookup - // no signature validation - - // check the parent_version_id for linearity - if inner.latest_version_id != NIL_VERSION_ID && parent_version_id != inner.latest_version_id - { - return Ok(( - AddVersionResult::ExpectedParentVersion(inner.latest_version_id), - SnapshotUrgency::None, - )); - } - - // invent a new ID for this version - let version_id = Uuid::new_v4(); - - inner.versions.insert( - parent_version_id, - Version { - version_id, - parent_version_id, - history_segment, - }, - ); - inner.latest_version_id = version_id; - - // reply with the configured urgency and reset it to None - let urgency = inner.snapshot_urgency; - inner.snapshot_urgency = SnapshotUrgency::None; - Ok((AddVersionResult::Ok(version_id), urgency)) - } - - /// Get a vector of all versions after `since_version` - fn get_child_version(&mut self, parent_version_id: VersionId) -> Result { - let inner = self.0.lock().unwrap(); - - if let Some(version) = inner.versions.get(&parent_version_id) { - Ok(GetVersionResult::Version { - version_id: version.version_id, - parent_version_id: version.parent_version_id, - history_segment: version.history_segment.clone(), - }) - } else { - Ok(GetVersionResult::NoSuchVersion) - } - } - - fn add_snapshot(&mut self, version_id: VersionId, snapshot: Snapshot) -> Result<()> { - let mut inner = self.0.lock().unwrap(); - - // test implementation -- does not perform any validation - inner.snapshot = Some((version_id, snapshot)); - Ok(()) - } - - fn get_snapshot(&mut self) -> Result> { - let inner = self.0.lock().unwrap(); - Ok(inner.snapshot.clone()) - } -} diff --git a/taskchampion/taskchampion/src/server/types.rs b/taskchampion/taskchampion/src/server/types.rs deleted file mode 100644 index 8929ae23b..000000000 --- a/taskchampion/taskchampion/src/server/types.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::errors::Result; -use uuid::Uuid; - -/// Versions are referred to with UUIDs. -pub type VersionId = Uuid; - -/// The distinguished value for "no version" -pub const NIL_VERSION_ID: VersionId = Uuid::nil(); - -/// A segment in the history of this task database, in the form of a sequence of operations. This -/// data is pre-encoded, and from the protocol level appears as a sequence of bytes. -pub type HistorySegment = Vec; - -/// A snapshot of the state of the task database. This is encoded by the taskdb implementation -/// and treated as a sequence of bytes by the server implementation. -pub type Snapshot = Vec; - -/// AddVersionResult is the response type from [`crate::server::Server::add_version`]. -#[derive(Debug, PartialEq, Eq)] -pub enum AddVersionResult { - /// OK, version added with the given ID - Ok(VersionId), - /// Rejected; expected a version with the given parent version - ExpectedParentVersion(VersionId), -} - -/// SnapshotUrgency indicates how much the server would like this replica to send a snapshot. -#[derive(PartialEq, Debug, Clone, Copy, Eq, PartialOrd, Ord)] -pub enum SnapshotUrgency { - /// Don't need a snapshot right now. - None, - /// A snapshot would be good, but can wait for other replicas to provide it. - Low, - /// A snapshot is needed right now. - High, -} - -/// A version as downloaded from the server -#[derive(Debug, PartialEq, Eq)] -pub enum GetVersionResult { - /// No such version exists - NoSuchVersion, - - /// The requested version - Version { - version_id: VersionId, - parent_version_id: VersionId, - history_segment: HistorySegment, - }, -} - -/// A value implementing this trait can act as a server against which a replica can sync. -pub trait Server { - /// Add a new version. - /// - /// This must ensure that the new version is the only version with the given - /// `parent_version_id`, and that all versions form a single parent-child chain. Inductively, - /// this means that if there are any versions on the server, then `parent_version_id` must be - /// the only version that does not already have a child. - fn add_version( - &mut self, - parent_version_id: VersionId, - history_segment: HistorySegment, - ) -> Result<(AddVersionResult, SnapshotUrgency)>; - - /// Get the version with the given parent VersionId - fn get_child_version(&mut self, parent_version_id: VersionId) -> Result; - - /// Add a snapshot on the server - fn add_snapshot(&mut self, version_id: VersionId, snapshot: Snapshot) -> Result<()>; - - fn get_snapshot(&mut self) -> Result>; -} diff --git a/taskchampion/taskchampion/src/storage/config.rs b/taskchampion/taskchampion/src/storage/config.rs deleted file mode 100644 index cabc6de54..000000000 --- a/taskchampion/taskchampion/src/storage/config.rs +++ /dev/null @@ -1,29 +0,0 @@ -use super::{InMemoryStorage, SqliteStorage, Storage}; -use crate::errors::Result; -use std::path::PathBuf; - -/// The configuration required for a replica's storage. -pub enum StorageConfig { - /// Store the data on disk. This is the common choice. - OnDisk { - /// Path containing the task DB. - taskdb_dir: PathBuf, - - /// Create the DB if it does not already exist - create_if_missing: bool, - }, - /// Store the data in memory. This is only useful for testing. - InMemory, -} - -impl StorageConfig { - pub fn into_storage(self) -> Result> { - Ok(match self { - StorageConfig::OnDisk { - taskdb_dir, - create_if_missing, - } => Box::new(SqliteStorage::new(taskdb_dir, create_if_missing)?), - StorageConfig::InMemory => Box::new(InMemoryStorage::new()), - }) - } -} diff --git a/taskchampion/taskchampion/src/storage/inmemory.rs b/taskchampion/taskchampion/src/storage/inmemory.rs deleted file mode 100644 index 6bf771a93..000000000 --- a/taskchampion/taskchampion/src/storage/inmemory.rs +++ /dev/null @@ -1,246 +0,0 @@ -#![allow(clippy::new_without_default)] - -use crate::errors::{Error, Result}; -use crate::storage::{ReplicaOp, Storage, StorageTxn, TaskMap, VersionId, DEFAULT_BASE_VERSION}; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -use uuid::Uuid; - -#[derive(PartialEq, Debug, Clone)] -struct Data { - tasks: HashMap, - base_version: VersionId, - operations: Vec, - working_set: Vec>, -} - -struct Txn<'t> { - storage: &'t mut InMemoryStorage, - new_data: Option, -} - -impl<'t> Txn<'t> { - fn mut_data_ref(&mut self) -> &mut Data { - if self.new_data.is_none() { - self.new_data = Some(self.storage.data.clone()); - } - if let Some(ref mut data) = self.new_data { - data - } else { - unreachable!(); - } - } - - fn data_ref(&mut self) -> &Data { - if let Some(ref data) = self.new_data { - data - } else { - &self.storage.data - } - } -} - -impl<'t> StorageTxn for Txn<'t> { - fn get_task(&mut self, uuid: Uuid) -> Result> { - match self.data_ref().tasks.get(&uuid) { - None => Ok(None), - Some(t) => Ok(Some(t.clone())), - } - } - - fn create_task(&mut self, uuid: Uuid) -> Result { - if let ent @ Entry::Vacant(_) = self.mut_data_ref().tasks.entry(uuid) { - ent.or_insert_with(TaskMap::new); - Ok(true) - } else { - Ok(false) - } - } - - fn set_task(&mut self, uuid: Uuid, task: TaskMap) -> Result<()> { - self.mut_data_ref().tasks.insert(uuid, task); - Ok(()) - } - - fn delete_task(&mut self, uuid: Uuid) -> Result { - Ok(self.mut_data_ref().tasks.remove(&uuid).is_some()) - } - - fn all_tasks<'a>(&mut self) -> Result> { - Ok(self - .data_ref() - .tasks - .iter() - .map(|(u, t)| (*u, t.clone())) - .collect()) - } - - fn all_task_uuids<'a>(&mut self) -> Result> { - Ok(self.data_ref().tasks.keys().copied().collect()) - } - - fn base_version(&mut self) -> Result { - Ok(self.data_ref().base_version) - } - - fn set_base_version(&mut self, version: VersionId) -> Result<()> { - self.mut_data_ref().base_version = version; - Ok(()) - } - - fn operations(&mut self) -> Result> { - Ok(self.data_ref().operations.clone()) - } - - fn num_operations(&mut self) -> Result { - Ok(self.data_ref().operations.len()) - } - - fn add_operation(&mut self, op: ReplicaOp) -> Result<()> { - self.mut_data_ref().operations.push(op); - Ok(()) - } - - fn set_operations(&mut self, ops: Vec) -> Result<()> { - self.mut_data_ref().operations = ops; - Ok(()) - } - - fn get_working_set(&mut self) -> Result>> { - Ok(self.data_ref().working_set.clone()) - } - - fn add_to_working_set(&mut self, uuid: Uuid) -> Result { - let working_set = &mut self.mut_data_ref().working_set; - working_set.push(Some(uuid)); - Ok(working_set.len()) - } - - fn set_working_set_item(&mut self, index: usize, uuid: Option) -> Result<()> { - let working_set = &mut self.mut_data_ref().working_set; - if index >= working_set.len() { - return Err(Error::Database(format!( - "Index {} is not in the working set", - index - ))); - } - working_set[index] = uuid; - Ok(()) - } - - fn clear_working_set(&mut self) -> Result<()> { - self.mut_data_ref().working_set = vec![None]; - Ok(()) - } - - fn commit(&mut self) -> Result<()> { - // copy the new_data back into storage to commit the transaction - if let Some(data) = self.new_data.take() { - self.storage.data = data; - } - Ok(()) - } -} - -/// InMemoryStorage is a simple in-memory task storage implementation. It is not useful for -/// production data, but is useful for testing purposes. -#[derive(PartialEq, Debug, Clone)] -pub struct InMemoryStorage { - data: Data, -} - -impl InMemoryStorage { - pub fn new() -> InMemoryStorage { - InMemoryStorage { - data: Data { - tasks: HashMap::new(), - base_version: DEFAULT_BASE_VERSION, - operations: vec![], - working_set: vec![None], - }, - } - } -} - -impl Storage for InMemoryStorage { - fn txn<'a>(&'a mut self) -> Result> { - Ok(Box::new(Txn { - storage: self, - new_data: None, - })) - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - - // (note: this module is heavily used in tests so most of its functionality is well-tested - // elsewhere and not tested here) - - #[test] - fn get_working_set_empty() -> Result<()> { - let mut storage = InMemoryStorage::new(); - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None]); - } - - Ok(()) - } - - #[test] - fn add_to_working_set() -> Result<()> { - let mut storage = InMemoryStorage::new(); - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - txn.add_to_working_set(uuid1)?; - txn.add_to_working_set(uuid2)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, Some(uuid1), Some(uuid2)]); - } - - Ok(()) - } - - #[test] - fn clear_working_set() -> Result<()> { - let mut storage = InMemoryStorage::new(); - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - txn.add_to_working_set(uuid1)?; - txn.add_to_working_set(uuid2)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - txn.clear_working_set()?; - txn.add_to_working_set(uuid2)?; - txn.add_to_working_set(uuid1)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, Some(uuid2), Some(uuid1)]); - } - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/storage/mod.rs b/taskchampion/taskchampion/src/storage/mod.rs deleted file mode 100644 index 5674e1baf..000000000 --- a/taskchampion/taskchampion/src/storage/mod.rs +++ /dev/null @@ -1,133 +0,0 @@ -use crate::errors::Result; -/** -This module defines the backend storage used by [`Replica`](crate::Replica). -It defines a [trait](crate::storage::Storage) for storage implementations, and provides a default on-disk implementation as well as an in-memory implementation for testing. - -Typical uses of this crate do not interact directly with this module; [`StorageConfig`](crate::StorageConfig) is sufficient. -However, users who wish to implement their own storage backends can implement the traits defined here and pass the result to [`Replica`](crate::Replica). -*/ -use std::collections::HashMap; -use uuid::Uuid; - -mod config; -mod inmemory; -mod op; -pub(crate) mod sqlite; - -pub use config::StorageConfig; -pub use inmemory::InMemoryStorage; -pub use sqlite::SqliteStorage; - -pub use op::ReplicaOp; - -/// An in-memory representation of a task as a simple hashmap -pub type TaskMap = HashMap; - -#[cfg(test)] -fn taskmap_with(mut properties: Vec<(String, String)>) -> TaskMap { - let mut rv = TaskMap::new(); - for (p, v) in properties.drain(..) { - rv.insert(p, v); - } - rv -} - -/// The type of VersionIds -pub use crate::server::VersionId; - -/// The default for base_version. -pub(crate) const DEFAULT_BASE_VERSION: Uuid = crate::server::NIL_VERSION_ID; - -/// A Storage transaction, in which storage operations are performed. -/// -/// # Concurrency -/// -/// Serializable consistency must be maintained. Concurrent access is unusual -/// and some implementations may simply apply a mutex to limit access to -/// one transaction at a time. -/// -/// # Commiting and Aborting -/// -/// A transaction is not visible to other readers until it is committed with -/// [`crate::storage::StorageTxn::commit`]. Transactions are aborted if they are dropped. -/// It is safe and performant to drop transactions that did not modify any data without committing. -pub trait StorageTxn { - /// Get an (immutable) task, if it is in the storage - fn get_task(&mut self, uuid: Uuid) -> Result>; - - /// Create an (empty) task, only if it does not already exist. Returns true if - /// the task was created (did not already exist). - fn create_task(&mut self, uuid: Uuid) -> Result; - - /// Set a task, overwriting any existing task. If the task does not exist, this implicitly - /// creates it (use `get_task` to check first, if necessary). - fn set_task(&mut self, uuid: Uuid, task: TaskMap) -> Result<()>; - - /// Delete a task, if it exists. Returns true if the task was deleted (already existed) - fn delete_task(&mut self, uuid: Uuid) -> Result; - - /// Get the uuids and bodies of all tasks in the storage, in undefined order. - fn all_tasks(&mut self) -> Result>; - - /// Get the uuids of all tasks in the storage, in undefined order. - fn all_task_uuids(&mut self) -> Result>; - - /// Get the current base_version for this storage -- the last version synced from the server. - fn base_version(&mut self) -> Result; - - /// Set the current base_version for this storage. - fn set_base_version(&mut self, version: VersionId) -> Result<()>; - - /// Get the current set of outstanding operations (operations that have not been sync'd to the - /// server yet) - fn operations(&mut self) -> Result>; - - /// Get the current set of outstanding operations (operations that have not been sync'd to the - /// server yet) - fn num_operations(&mut self) -> Result; - - /// Add an operation to the end of the list of operations in the storage. Note that this - /// merely *stores* the operation; it is up to the TaskDb to apply it. - fn add_operation(&mut self, op: ReplicaOp) -> Result<()>; - - /// Replace the current list of operations with a new list. - fn set_operations(&mut self, ops: Vec) -> Result<()>; - - /// Get the entire working set, with each task UUID at its appropriate (1-based) index. - /// Element 0 is always None. - fn get_working_set(&mut self) -> Result>>; - - /// Add a task to the working set and return its (one-based) index. This index will be one greater - /// than the highest used index. - fn add_to_working_set(&mut self, uuid: Uuid) -> Result; - - /// Update the working set task at the given index. This cannot add a new item to the - /// working set. - fn set_working_set_item(&mut self, index: usize, uuid: Option) -> Result<()>; - - /// Clear all tasks from the working set in preparation for a garbage-collection operation. - /// Note that this is the only way items are removed from the set. - fn clear_working_set(&mut self) -> Result<()>; - - /// Check whether this storage is entirely empty - #[allow(clippy::wrong_self_convention)] // mut is required here for storage access - fn is_empty(&mut self) -> Result { - let mut empty = true; - empty = empty && self.all_tasks()?.is_empty(); - empty = empty && self.get_working_set()? == vec![None]; - empty = empty && self.base_version()? == Uuid::nil(); - empty = empty && self.operations()?.is_empty(); - Ok(empty) - } - - /// Commit any changes made in the transaction. It is an error to call this more than - /// once. - fn commit(&mut self) -> Result<()>; -} - -/// A trait for objects able to act as task storage. Most of the interesting behavior is in the -/// [`crate::storage::StorageTxn`] trait. -pub trait Storage { - /// Begin a transaction - fn txn<'a>(&'a mut self) -> Result>; -} diff --git a/taskchampion/taskchampion/src/storage/op.rs b/taskchampion/taskchampion/src/storage/op.rs deleted file mode 100644 index c63e9efa6..000000000 --- a/taskchampion/taskchampion/src/storage/op.rs +++ /dev/null @@ -1,289 +0,0 @@ -use crate::server::SyncOp; -use crate::storage::TaskMap; -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -/// A ReplicaOp defines a single change to the task database, as stored locally in the replica. -/// This contains additional information not included in SyncOp. -#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] -pub enum ReplicaOp { - /// Create a new task. - /// - /// On undo, the task is deleted. - Create { uuid: Uuid }, - - /// Delete an existing task. - /// - /// On undo, the task's data is restored from old_task. - Delete { uuid: Uuid, old_task: TaskMap }, - - /// Update an existing task, setting the given property to the given value. If the value is - /// None, then the corresponding property is deleted. - /// - /// On undo, the property is set back to its previous value. - Update { - uuid: Uuid, - property: String, - old_value: Option, - value: Option, - timestamp: DateTime, - }, - - /// Mark a point in the operations history to which the user might like to undo. Users - /// typically want to undo more than one operation at a time (for example, most changes update - /// both the `modified` property and some other task property -- the user would like to "undo" - /// both updates at the same time). Applying an UndoPoint does nothing. - UndoPoint, -} - -impl ReplicaOp { - /// Convert this operation into a [`SyncOp`]. - pub fn into_sync(self) -> Option { - match self { - Self::Create { uuid } => Some(SyncOp::Create { uuid }), - Self::Delete { uuid, .. } => Some(SyncOp::Delete { uuid }), - Self::Update { - uuid, - property, - value, - timestamp, - .. - } => Some(SyncOp::Update { - uuid, - property, - value, - timestamp, - }), - Self::UndoPoint => None, - } - } - - /// Determine whether this is an undo point. - pub fn is_undo_point(&self) -> bool { - self == &Self::UndoPoint - } - - /// Generate a sequence of SyncOp's to reverse the effects of this ReplicaOp. - pub fn reverse_ops(self) -> Vec { - match self { - Self::Create { uuid } => vec![SyncOp::Delete { uuid }], - Self::Delete { uuid, mut old_task } => { - let mut ops = vec![SyncOp::Create { uuid }]; - // We don't have the original update timestamp, but it doesn't - // matter because this SyncOp will just be applied and discarded. - let timestamp = Utc::now(); - for (property, value) in old_task.drain() { - ops.push(SyncOp::Update { - uuid, - property, - value: Some(value), - timestamp, - }); - } - ops - } - Self::Update { - uuid, - property, - old_value, - timestamp, - .. - } => vec![SyncOp::Update { - uuid, - property, - value: old_value, - timestamp, - }], - Self::UndoPoint => vec![], - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::errors::Result; - use crate::storage::taskmap_with; - use chrono::Utc; - use pretty_assertions::assert_eq; - - use ReplicaOp::*; - - #[test] - fn test_json_create() -> Result<()> { - let uuid = Uuid::new_v4(); - let op = Create { uuid }; - let json = serde_json::to_string(&op)?; - assert_eq!(json, format!(r#"{{"Create":{{"uuid":"{}"}}}}"#, uuid)); - let deser: ReplicaOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_delete() -> Result<()> { - let uuid = Uuid::new_v4(); - let old_task = vec![("foo".into(), "bar".into())].drain(..).collect(); - let op = Delete { uuid, old_task }; - let json = serde_json::to_string(&op)?; - assert_eq!( - json, - format!( - r#"{{"Delete":{{"uuid":"{}","old_task":{{"foo":"bar"}}}}}}"#, - uuid - ) - ); - let deser: ReplicaOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_update() -> Result<()> { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - let op = Update { - uuid, - property: "abc".into(), - old_value: Some("true".into()), - value: Some("false".into()), - timestamp, - }; - - let json = serde_json::to_string(&op)?; - assert_eq!( - json, - format!( - r#"{{"Update":{{"uuid":"{}","property":"abc","old_value":"true","value":"false","timestamp":"{:?}"}}}}"#, - uuid, timestamp, - ) - ); - let deser: ReplicaOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_json_update_none() -> Result<()> { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - - let op = Update { - uuid, - property: "abc".into(), - old_value: None, - value: None, - timestamp, - }; - - let json = serde_json::to_string(&op)?; - assert_eq!( - json, - format!( - r#"{{"Update":{{"uuid":"{}","property":"abc","old_value":null,"value":null,"timestamp":"{:?}"}}}}"#, - uuid, timestamp, - ) - ); - let deser: ReplicaOp = serde_json::from_str(&json)?; - assert_eq!(deser, op); - Ok(()) - } - - #[test] - fn test_into_sync_create() { - let uuid = Uuid::new_v4(); - assert_eq!(Create { uuid }.into_sync(), Some(SyncOp::Create { uuid })); - } - - #[test] - fn test_into_sync_delete() { - let uuid = Uuid::new_v4(); - assert_eq!( - Delete { - uuid, - old_task: TaskMap::new() - } - .into_sync(), - Some(SyncOp::Delete { uuid }) - ); - } - - #[test] - fn test_into_sync_update() { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - assert_eq!( - Update { - uuid, - property: "prop".into(), - old_value: Some("foo".into()), - value: Some("v".into()), - timestamp, - } - .into_sync(), - Some(SyncOp::Update { - uuid, - property: "prop".into(), - value: Some("v".into()), - timestamp, - }) - ); - } - - #[test] - fn test_into_sync_undo_point() { - assert_eq!(UndoPoint.into_sync(), None); - } - - #[test] - fn test_reverse_create() { - let uuid = Uuid::new_v4(); - assert_eq!(Create { uuid }.reverse_ops(), vec![SyncOp::Delete { uuid }]); - } - - #[test] - fn test_reverse_delete() { - let uuid = Uuid::new_v4(); - let reversed = Delete { - uuid, - old_task: taskmap_with(vec![("prop1".into(), "v1".into())]), - } - .reverse_ops(); - assert_eq!(reversed.len(), 2); - assert_eq!(reversed[0], SyncOp::Create { uuid }); - assert!(matches!( - &reversed[1], - SyncOp::Update { uuid: u, property: p, value: Some(v), ..} - if u == &uuid && p == "prop1" && v == "v1" - )); - } - - #[test] - fn test_reverse_update() { - let uuid = Uuid::new_v4(); - let timestamp = Utc::now(); - assert_eq!( - Update { - uuid, - property: "prop".into(), - old_value: Some("foo".into()), - value: Some("v".into()), - timestamp, - } - .reverse_ops(), - vec![SyncOp::Update { - uuid, - property: "prop".into(), - value: Some("foo".into()), - timestamp, - }] - ); - } - - #[test] - fn test_reverse_undo_point() { - assert_eq!(UndoPoint.reverse_ops(), vec![]); - } -} diff --git a/taskchampion/taskchampion/src/storage/sqlite.rs b/taskchampion/taskchampion/src/storage/sqlite.rs deleted file mode 100644 index 8abdde476..000000000 --- a/taskchampion/taskchampion/src/storage/sqlite.rs +++ /dev/null @@ -1,819 +0,0 @@ -use crate::errors::Result; -use crate::storage::{ReplicaOp, Storage, StorageTxn, TaskMap, VersionId, DEFAULT_BASE_VERSION}; -use anyhow::Context; -use rusqlite::types::{FromSql, ToSql}; -use rusqlite::{params, Connection, OpenFlags, OptionalExtension}; -use std::path::Path; -use uuid::Uuid; - -#[derive(Debug, thiserror::Error)] -pub enum SqliteError { - #[error("SQLite transaction already committted")] - TransactionAlreadyCommitted, -} - -/// Newtype to allow implementing `FromSql` for foreign `uuid::Uuid` -pub(crate) struct StoredUuid(pub(crate) Uuid); - -/// Conversion from Uuid stored as a string (rusqlite's uuid feature stores as binary blob) -impl FromSql for StoredUuid { - fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { - let u = Uuid::parse_str(value.as_str()?) - .map_err(|_| rusqlite::types::FromSqlError::InvalidType)?; - Ok(StoredUuid(u)) - } -} - -/// Store Uuid as string in database -impl ToSql for StoredUuid { - fn to_sql(&self) -> rusqlite::Result> { - let s = self.0.to_string(); - Ok(s.into()) - } -} - -/// Wraps [`TaskMap`] (type alias for HashMap) so we can implement rusqlite conversion traits for it -struct StoredTaskMap(TaskMap); - -/// Parses TaskMap stored as JSON in string column -impl FromSql for StoredTaskMap { - fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { - let o: TaskMap = serde_json::from_str(value.as_str()?) - .map_err(|_| rusqlite::types::FromSqlError::InvalidType)?; - Ok(StoredTaskMap(o)) - } -} - -/// Stores TaskMap in string column -impl ToSql for StoredTaskMap { - fn to_sql(&self) -> rusqlite::Result> { - let s = serde_json::to_string(&self.0) - .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?; - Ok(s.into()) - } -} - -/// Stores [`ReplicaOp`] in SQLite -impl FromSql for ReplicaOp { - fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { - let o: ReplicaOp = serde_json::from_str(value.as_str()?) - .map_err(|_| rusqlite::types::FromSqlError::InvalidType)?; - Ok(o) - } -} - -/// Parses ReplicaOp stored as JSON in string column -impl ToSql for ReplicaOp { - fn to_sql(&self) -> rusqlite::Result> { - let s = serde_json::to_string(&self) - .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?; - Ok(s.into()) - } -} - -/// SqliteStorage is an on-disk storage backed by SQLite3. -pub struct SqliteStorage { - con: Connection, -} - -impl SqliteStorage { - pub fn new>(directory: P, create_if_missing: bool) -> Result { - if create_if_missing { - // Ensure parent folder exists - std::fs::create_dir_all(&directory)?; - } - - // Open (or create) database - let db_file = directory.as_ref().join("taskchampion.sqlite3"); - let mut flags = OpenFlags::default(); - // default contains SQLITE_OPEN_CREATE, so remove it if we are not to - // create a DB when missing. - if !create_if_missing { - flags.remove(OpenFlags::SQLITE_OPEN_CREATE); - } - let con = Connection::open_with_flags(db_file, flags)?; - - // Initialize database - let queries = vec![ - "CREATE TABLE IF NOT EXISTS operations (id INTEGER PRIMARY KEY AUTOINCREMENT, data STRING);", - "CREATE TABLE IF NOT EXISTS sync_meta (key STRING PRIMARY KEY, value STRING);", - "CREATE TABLE IF NOT EXISTS tasks (uuid STRING PRIMARY KEY, data STRING);", - "CREATE TABLE IF NOT EXISTS working_set (id INTEGER PRIMARY KEY, uuid STRING);", - ]; - for q in queries { - con.execute(q, []).context("Creating table")?; - } - - Ok(SqliteStorage { con }) - } -} - -struct Txn<'t> { - txn: Option>, -} - -impl<'t> Txn<'t> { - fn get_txn(&self) -> std::result::Result<&rusqlite::Transaction<'t>, SqliteError> { - self.txn - .as_ref() - .ok_or(SqliteError::TransactionAlreadyCommitted) - } - - fn get_next_working_set_number(&self) -> Result { - let t = self.get_txn()?; - let next_id: Option = t - .query_row( - "SELECT COALESCE(MAX(id), 0) + 1 FROM working_set", - [], - |r| r.get(0), - ) - .optional() - .context("Getting highest working set ID")?; - - Ok(next_id.unwrap_or(0)) - } -} - -impl Storage for SqliteStorage { - fn txn<'a>(&'a mut self) -> Result> { - let txn = self.con.transaction()?; - Ok(Box::new(Txn { txn: Some(txn) })) - } -} - -impl<'t> StorageTxn for Txn<'t> { - fn get_task(&mut self, uuid: Uuid) -> Result> { - let t = self.get_txn()?; - let result: Option = t - .query_row( - "SELECT data FROM tasks WHERE uuid = ? LIMIT 1", - [&StoredUuid(uuid)], - |r| r.get("data"), - ) - .optional()?; - - // Get task from "stored" wrapper - Ok(result.map(|t| t.0)) - } - - fn create_task(&mut self, uuid: Uuid) -> Result { - let t = self.get_txn()?; - let count: usize = t.query_row( - "SELECT count(uuid) FROM tasks WHERE uuid = ?", - [&StoredUuid(uuid)], - |x| x.get(0), - )?; - if count > 0 { - return Ok(false); - } - - let data = TaskMap::default(); - t.execute( - "INSERT INTO tasks (uuid, data) VALUES (?, ?)", - params![&StoredUuid(uuid), &StoredTaskMap(data)], - ) - .context("Create task query")?; - Ok(true) - } - - fn set_task(&mut self, uuid: Uuid, task: TaskMap) -> Result<()> { - let t = self.get_txn()?; - t.execute( - "INSERT OR REPLACE INTO tasks (uuid, data) VALUES (?, ?)", - params![&StoredUuid(uuid), &StoredTaskMap(task)], - ) - .context("Update task query")?; - Ok(()) - } - - fn delete_task(&mut self, uuid: Uuid) -> Result { - let t = self.get_txn()?; - let changed = t - .execute("DELETE FROM tasks WHERE uuid = ?", [&StoredUuid(uuid)]) - .context("Delete task query")?; - Ok(changed > 0) - } - - fn all_tasks(&mut self) -> Result> { - let t = self.get_txn()?; - - let mut q = t.prepare("SELECT uuid, data FROM tasks")?; - let rows = q.query_map([], |r| { - let uuid: StoredUuid = r.get("uuid")?; - let data: StoredTaskMap = r.get("data")?; - Ok((uuid.0, data.0)) - })?; - - let mut ret = vec![]; - for r in rows { - ret.push(r?); - } - Ok(ret) - } - - fn all_task_uuids(&mut self) -> Result> { - let t = self.get_txn()?; - - let mut q = t.prepare("SELECT uuid FROM tasks")?; - let rows = q.query_map([], |r| { - let uuid: StoredUuid = r.get("uuid")?; - Ok(uuid.0) - })?; - - let mut ret = vec![]; - for r in rows { - ret.push(r?); - } - Ok(ret) - } - - fn base_version(&mut self) -> Result { - let t = self.get_txn()?; - - let version: Option = t - .query_row( - "SELECT value FROM sync_meta WHERE key = 'base_version'", - [], - |r| r.get("value"), - ) - .optional()?; - Ok(version.map(|u| u.0).unwrap_or(DEFAULT_BASE_VERSION)) - } - - fn set_base_version(&mut self, version: VersionId) -> Result<()> { - let t = self.get_txn()?; - t.execute( - "INSERT OR REPLACE INTO sync_meta (key, value) VALUES (?, ?)", - params!["base_version", &StoredUuid(version)], - ) - .context("Set base version")?; - Ok(()) - } - - fn operations(&mut self) -> Result> { - let t = self.get_txn()?; - - let mut q = t.prepare("SELECT data FROM operations ORDER BY id ASC")?; - let rows = q.query_map([], |r| { - let data: ReplicaOp = r.get("data")?; - Ok(data) - })?; - - let mut ret = vec![]; - for r in rows { - ret.push(r?); - } - Ok(ret) - } - - fn num_operations(&mut self) -> Result { - let t = self.get_txn()?; - let count: usize = t.query_row("SELECT count(*) FROM operations", [], |x| x.get(0))?; - Ok(count) - } - - fn add_operation(&mut self, op: ReplicaOp) -> Result<()> { - let t = self.get_txn()?; - - t.execute("INSERT INTO operations (data) VALUES (?)", params![&op]) - .context("Add operation query")?; - Ok(()) - } - - fn set_operations(&mut self, ops: Vec) -> Result<()> { - let t = self.get_txn()?; - t.execute("DELETE FROM operations", []) - .context("Clear all existing operations")?; - t.execute("DELETE FROM sqlite_sequence WHERE name = 'operations'", []) - .context("Clear all existing operations")?; - - for o in ops { - self.add_operation(o)?; - } - Ok(()) - } - - fn get_working_set(&mut self) -> Result>> { - let t = self.get_txn()?; - - let mut q = t.prepare("SELECT id, uuid FROM working_set ORDER BY id ASC")?; - let rows = q - .query_map([], |r| { - let id: usize = r.get("id")?; - let uuid: StoredUuid = r.get("uuid")?; - Ok((id, uuid.0)) - }) - .context("Get working set query")?; - - let rows: Vec> = rows.collect(); - let mut res = Vec::with_capacity(rows.len()); - for _ in 0..self - .get_next_working_set_number() - .context("Getting working set number")? - { - res.push(None); - } - for r in rows { - let (id, uuid) = r?; - res[id] = Some(uuid); - } - - Ok(res) - } - - fn add_to_working_set(&mut self, uuid: Uuid) -> Result { - let t = self.get_txn()?; - - let next_working_id = self.get_next_working_set_number()?; - - t.execute( - "INSERT INTO working_set (id, uuid) VALUES (?, ?)", - params![next_working_id, &StoredUuid(uuid)], - ) - .context("Create task query")?; - - Ok(next_working_id) - } - - fn set_working_set_item(&mut self, index: usize, uuid: Option) -> Result<()> { - let t = self.get_txn()?; - match uuid { - // Add or override item - Some(uuid) => t.execute( - "INSERT OR REPLACE INTO working_set (id, uuid) VALUES (?, ?)", - params![index, &StoredUuid(uuid)], - ), - // Setting to None removes the row from database - None => t.execute("DELETE FROM working_set WHERE id = ?", [index]), - } - .context("Set working set item query")?; - Ok(()) - } - - fn clear_working_set(&mut self) -> Result<()> { - let t = self.get_txn()?; - t.execute("DELETE FROM working_set", []) - .context("Clear working set query")?; - Ok(()) - } - - fn commit(&mut self) -> Result<()> { - let t = self - .txn - .take() - .ok_or(SqliteError::TransactionAlreadyCommitted)?; - t.commit().context("Committing transaction")?; - Ok(()) - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::storage::taskmap_with; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn test_empty_dir() -> Result<()> { - let tmp_dir = TempDir::new()?; - let non_existant = tmp_dir.path().join("subdir"); - let mut storage = SqliteStorage::new(non_existant, true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid)?); - txn.commit()?; - } - { - let mut txn = storage.txn()?; - let task = txn.get_task(uuid)?; - assert_eq!(task, Some(taskmap_with(vec![]))); - } - Ok(()) - } - - #[test] - fn drop_transaction() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid1)?); - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid2)?); - std::mem::drop(txn); // Unnecessary explicit drop of transaction - } - - { - let mut txn = storage.txn()?; - let uuids = txn.all_task_uuids()?; - - assert_eq!(uuids, [uuid1]); - } - - Ok(()) - } - - #[test] - fn test_create() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid)?); - txn.commit()?; - } - { - let mut txn = storage.txn()?; - let task = txn.get_task(uuid)?; - assert_eq!(task, Some(taskmap_with(vec![]))); - } - Ok(()) - } - - #[test] - fn test_create_exists() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid)?); - txn.commit()?; - } - { - let mut txn = storage.txn()?; - assert!(!txn.create_task(uuid)?); - txn.commit()?; - } - Ok(()) - } - - #[test] - fn test_get_missing() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - let task = txn.get_task(uuid)?; - assert_eq!(task, None); - } - Ok(()) - } - - #[test] - fn test_set_task() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - txn.set_task(uuid, taskmap_with(vec![("k".to_string(), "v".to_string())]))?; - txn.commit()?; - } - { - let mut txn = storage.txn()?; - let task = txn.get_task(uuid)?; - assert_eq!( - task, - Some(taskmap_with(vec![("k".to_string(), "v".to_string())])) - ); - } - Ok(()) - } - - #[test] - fn test_delete_task_missing() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(!txn.delete_task(uuid)?); - } - Ok(()) - } - - #[test] - fn test_delete_task_exists() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid)?); - txn.commit()?; - } - { - let mut txn = storage.txn()?; - assert!(txn.delete_task(uuid)?); - } - Ok(()) - } - - #[test] - fn test_all_tasks_empty() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - { - let mut txn = storage.txn()?; - let tasks = txn.all_tasks()?; - assert_eq!(tasks, vec![]); - } - Ok(()) - } - - #[test] - fn test_all_tasks_and_uuids() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - assert!(txn.create_task(uuid1)?); - txn.set_task( - uuid1, - taskmap_with(vec![("num".to_string(), "1".to_string())]), - )?; - assert!(txn.create_task(uuid2)?); - txn.set_task( - uuid2, - taskmap_with(vec![("num".to_string(), "2".to_string())]), - )?; - txn.commit()?; - } - { - let mut txn = storage.txn()?; - let mut tasks = txn.all_tasks()?; - - // order is nondeterministic, so sort by uuid - tasks.sort_by(|a, b| a.0.cmp(&b.0)); - - let mut exp = vec![ - ( - uuid1, - taskmap_with(vec![("num".to_string(), "1".to_string())]), - ), - ( - uuid2, - taskmap_with(vec![("num".to_string(), "2".to_string())]), - ), - ]; - exp.sort_by(|a, b| a.0.cmp(&b.0)); - - assert_eq!(tasks, exp); - } - { - let mut txn = storage.txn()?; - let mut uuids = txn.all_task_uuids()?; - uuids.sort(); - - let mut exp = vec![uuid1, uuid2]; - exp.sort(); - - assert_eq!(uuids, exp); - } - Ok(()) - } - - #[test] - fn test_base_version_default() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - { - let mut txn = storage.txn()?; - assert_eq!(txn.base_version()?, DEFAULT_BASE_VERSION); - } - Ok(()) - } - - #[test] - fn test_base_version_setting() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let u = Uuid::new_v4(); - { - let mut txn = storage.txn()?; - txn.set_base_version(u)?; - txn.commit()?; - } - { - let mut txn = storage.txn()?; - assert_eq!(txn.base_version()?, u); - } - Ok(()) - } - - #[test] - fn test_operations() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - let uuid3 = Uuid::new_v4(); - - // create some operations - { - let mut txn = storage.txn()?; - txn.add_operation(ReplicaOp::Create { uuid: uuid1 })?; - txn.add_operation(ReplicaOp::Create { uuid: uuid2 })?; - txn.commit()?; - } - - // read them back - { - let mut txn = storage.txn()?; - let ops = txn.operations()?; - assert_eq!( - ops, - vec![ - ReplicaOp::Create { uuid: uuid1 }, - ReplicaOp::Create { uuid: uuid2 }, - ] - ); - - assert_eq!(txn.num_operations()?, 2); - } - - // set them to a different bunch - { - let mut txn = storage.txn()?; - txn.set_operations(vec![ - ReplicaOp::Delete { - uuid: uuid2, - old_task: TaskMap::new(), - }, - ReplicaOp::Delete { - uuid: uuid1, - old_task: TaskMap::new(), - }, - ])?; - txn.commit()?; - } - - // create some more operations (to test adding operations after clearing) - { - let mut txn = storage.txn()?; - txn.add_operation(ReplicaOp::Create { uuid: uuid3 })?; - txn.add_operation(ReplicaOp::Delete { - uuid: uuid3, - old_task: TaskMap::new(), - })?; - txn.commit()?; - } - - // read them back - { - let mut txn = storage.txn()?; - let ops = txn.operations()?; - assert_eq!( - ops, - vec![ - ReplicaOp::Delete { - uuid: uuid2, - old_task: TaskMap::new() - }, - ReplicaOp::Delete { - uuid: uuid1, - old_task: TaskMap::new() - }, - ReplicaOp::Create { uuid: uuid3 }, - ReplicaOp::Delete { - uuid: uuid3, - old_task: TaskMap::new() - }, - ] - ); - assert_eq!(txn.num_operations()?, 4); - } - Ok(()) - } - - #[test] - fn get_working_set_empty() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None]); - } - - Ok(()) - } - - #[test] - fn add_to_working_set() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - txn.add_to_working_set(uuid1)?; - txn.add_to_working_set(uuid2)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, Some(uuid1), Some(uuid2)]); - } - - Ok(()) - } - - #[test] - fn clear_working_set() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - txn.add_to_working_set(uuid1)?; - txn.add_to_working_set(uuid2)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - txn.clear_working_set()?; - txn.add_to_working_set(uuid2)?; - txn.add_to_working_set(uuid1)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, Some(uuid2), Some(uuid1)]); - } - - Ok(()) - } - - #[test] - fn set_working_set_item() -> Result<()> { - let tmp_dir = TempDir::new()?; - let mut storage = SqliteStorage::new(tmp_dir.path(), true)?; - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - { - let mut txn = storage.txn()?; - txn.add_to_working_set(uuid1)?; - txn.add_to_working_set(uuid2)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, Some(uuid1), Some(uuid2)]); - } - - // Clear one item - { - let mut txn = storage.txn()?; - txn.set_working_set_item(1, None)?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, None, Some(uuid2)]); - } - - // Override item - { - let mut txn = storage.txn()?; - txn.set_working_set_item(2, Some(uuid1))?; - txn.commit()?; - } - - { - let mut txn = storage.txn()?; - let ws = txn.get_working_set()?; - assert_eq!(ws, vec![None, None, Some(uuid1)]); - } - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/task/annotation.rs b/taskchampion/taskchampion/src/task/annotation.rs deleted file mode 100644 index 951dc3f11..000000000 --- a/taskchampion/taskchampion/src/task/annotation.rs +++ /dev/null @@ -1,10 +0,0 @@ -use super::Timestamp; - -/// An annotation for a task -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct Annotation { - /// Time the annotation was made - pub entry: Timestamp, - /// Content of the annotation - pub description: String, -} diff --git a/taskchampion/taskchampion/src/task/mod.rs b/taskchampion/taskchampion/src/task/mod.rs deleted file mode 100644 index 259ed6ab0..000000000 --- a/taskchampion/taskchampion/src/task/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -#![allow(clippy::module_inception)] -mod annotation; -mod status; -mod tag; -mod task; -mod time; - -pub use annotation::Annotation; -pub use status::Status; -pub use tag::Tag; -pub use task::{Task, TaskMut}; -pub use time::{utc_timestamp, Timestamp}; diff --git a/taskchampion/taskchampion/src/task/status.rs b/taskchampion/taskchampion/src/task/status.rs deleted file mode 100644 index 38d017df7..000000000 --- a/taskchampion/taskchampion/src/task/status.rs +++ /dev/null @@ -1,74 +0,0 @@ -/// The status of a task, as defined by the task data model. -#[derive(Debug, PartialEq, Eq, Clone, strum_macros::Display)] -#[repr(C)] -pub enum Status { - Pending, - Completed, - Deleted, - Recurring, - /// Unknown signifies a status in the task DB that was not - /// recognized. This supports forward-compatibility if a - /// new status is added. Tasks with unknown status should - /// be ignored (but not deleted). - Unknown(String), -} - -impl Status { - /// Get a Status from the string value in a TaskMap - pub(crate) fn from_taskmap(s: &str) -> Status { - match s { - "pending" => Status::Pending, - "completed" => Status::Completed, - "deleted" => Status::Deleted, - "recurring" => Status::Recurring, - v => Status::Unknown(v.to_string()), - } - } - - /// Get the 1-character value for this status to use in the TaskMap. - pub(crate) fn to_taskmap(&self) -> &str { - match self { - Status::Pending => "pending", - Status::Completed => "completed", - Status::Deleted => "deleted", - Status::Recurring => "recurring", - Status::Unknown(v) => v.as_ref(), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn to_taskmap() { - assert_eq!(Status::Pending.to_taskmap(), "pending"); - assert_eq!(Status::Completed.to_taskmap(), "completed"); - assert_eq!(Status::Deleted.to_taskmap(), "deleted"); - assert_eq!(Status::Recurring.to_taskmap(), "recurring"); - assert_eq!(Status::Unknown("wishful".into()).to_taskmap(), "wishful"); - } - - #[test] - fn from_taskmap() { - assert_eq!(Status::from_taskmap("pending"), Status::Pending); - assert_eq!(Status::from_taskmap("completed"), Status::Completed); - assert_eq!(Status::from_taskmap("deleted"), Status::Deleted); - assert_eq!(Status::from_taskmap("recurring"), Status::Recurring); - assert_eq!( - Status::from_taskmap("something-else"), - Status::Unknown("something-else".into()) - ); - } - - #[test] - fn display() { - assert_eq!(format!("{}", Status::Pending), "Pending"); - assert_eq!(format!("{}", Status::Completed), "Completed"); - assert_eq!(format!("{}", Status::Deleted), "Deleted"); - assert_eq!(format!("{}", Status::Recurring), "Recurring"); - assert_eq!(format!("{}", Status::Unknown("wishful".into())), "Unknown"); - } -} diff --git a/taskchampion/taskchampion/src/task/tag.rs b/taskchampion/taskchampion/src/task/tag.rs deleted file mode 100644 index a4f1e677c..000000000 --- a/taskchampion/taskchampion/src/task/tag.rs +++ /dev/null @@ -1,174 +0,0 @@ -use std::convert::TryFrom; -use std::fmt; -use std::str::FromStr; - -/// A Tag is a descriptor for a task, that is either present or absent, and can be used for -/// filtering. Tags composed of all uppercase letters are reserved for synthetic tags. -/// -/// Valid tags must not contain whitespace or any of the characters in `+-*/(<>^! %=~`. -/// The first characters additionally cannot be a digit, and subsequent characters cannot be `:`. -/// This definition is based on [that of -/// TaskWarrior](https://github.com/GothenburgBitFactory/taskwarrior/blob/663c6575ceca5bd0135ae884879339dac89d3142/src/Lexer.cpp#L146-L164). -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] -pub struct Tag(TagInner); - -/// Inner type to hide the implementation -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] -pub(super) enum TagInner { - User(String), - Synthetic(SyntheticTag), -} - -// see doc comment for Tag, above -pub const INVALID_TAG_CHARACTERS: &str = "+-*/(<>^! %=~"; - -impl Tag { - /// True if this tag is a synthetic tag - pub fn is_synthetic(&self) -> bool { - matches!(self.0, TagInner::Synthetic(_)) - } - - /// True if this tag is a user-provided tag (not synthetic) - pub fn is_user(&self) -> bool { - matches!(self.0, TagInner::User(_)) - } - - pub(super) fn inner(&self) -> &TagInner { - &self.0 - } - - pub(super) fn from_inner(inner: TagInner) -> Self { - Self(inner) - } -} - -impl FromStr for Tag { - type Err = anyhow::Error; - - fn from_str(value: &str) -> Result { - fn err(value: &str) -> Result { - anyhow::bail!("invalid tag {:?}", value) - } - - // first, look for synthetic tags - if value.chars().all(|c| c.is_ascii_uppercase()) { - if let Ok(st) = SyntheticTag::from_str(value) { - return Ok(Self(TagInner::Synthetic(st))); - } - // all uppercase, but not a valid synthetic tag - return err(value); - } - - if let Some(c) = value.chars().next() { - if c.is_whitespace() || c.is_ascii_digit() || INVALID_TAG_CHARACTERS.contains(c) { - return err(value); - } - } else { - return err(value); - } - if !value - .chars() - .skip(1) - .all(|c| !(c.is_whitespace() || c == ':' || INVALID_TAG_CHARACTERS.contains(c))) - { - return err(value); - } - Ok(Self(TagInner::User(String::from(value)))) - } -} - -impl TryFrom<&str> for Tag { - type Error = anyhow::Error; - - fn try_from(value: &str) -> Result { - Self::from_str(value) - } -} - -impl TryFrom<&String> for Tag { - type Error = anyhow::Error; - - fn try_from(value: &String) -> Result { - Self::from_str(&value[..]) - } -} - -impl fmt::Display for Tag { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match &self.0 { - TagInner::User(s) => s.fmt(f), - TagInner::Synthetic(st) => st.as_ref().fmt(f), - } - } -} - -impl AsRef for Tag { - fn as_ref(&self) -> &str { - match &self.0 { - TagInner::User(s) => s.as_ref(), - TagInner::Synthetic(st) => st.as_ref(), - } - } -} - -/// A synthetic tag, represented as an `enum`. This type is used directly by -/// [`taskchampion::task::task`] for efficiency. -#[derive( - Debug, - Clone, - Eq, - PartialEq, - Ord, - PartialOrd, - Hash, - strum_macros::EnumString, - strum_macros::AsRefStr, - strum_macros::EnumIter, -)] -#[strum(serialize_all = "SCREAMING_SNAKE_CASE")] -pub(super) enum SyntheticTag { - // When adding items here, also implement and test them in `task.rs` and document them in - // `docs/src/tags.md`. - Waiting, - Active, - Pending, - Completed, - Deleted, - Blocked, - Unblocked, - Blocking, -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - use rstest::rstest; - use std::convert::TryInto; - - #[rstest] - #[case::simple("abc")] - #[case::colon_prefix(":abc")] - #[case::letters_and_numbers("a123_456")] - #[case::synthetic("WAITING")] - fn test_tag_try_into_success(#[case] s: &'static str) { - let tag: Tag = s.try_into().unwrap(); - // check Display (via to_string) and AsRef while we're here - assert_eq!(tag.to_string(), s.to_owned()); - assert_eq!(tag.as_ref(), s); - } - - #[rstest] - #[case::empty("")] - #[case::colon_infix("a:b")] - #[case::digits("999")] - #[case::bangs("abc!!!")] - #[case::no_such_synthetic("NOSUCH")] - fn test_tag_try_into_err(#[case] s: &'static str) { - let tag: Result = s.try_into(); - assert_eq!( - tag.unwrap_err().to_string(), - format!("invalid tag \"{}\"", s) - ); - } -} diff --git a/taskchampion/taskchampion/src/task/task.rs b/taskchampion/taskchampion/src/task/task.rs deleted file mode 100644 index 3dda37d61..000000000 --- a/taskchampion/taskchampion/src/task/task.rs +++ /dev/null @@ -1,1270 +0,0 @@ -use super::tag::{SyntheticTag, TagInner}; -use super::{utc_timestamp, Annotation, Status, Tag, Timestamp}; -use crate::depmap::DependencyMap; -use crate::errors::{Error, Result}; -use crate::replica::Replica; -use crate::storage::TaskMap; -use chrono::prelude::*; -use log::trace; -use std::convert::AsRef; -use std::convert::TryInto; -use std::rc::Rc; -use std::str::FromStr; -use uuid::Uuid; - -/* The Task and TaskMut classes wrap the underlying [`TaskMap`], which is a simple key/value map. - * They provide semantic meaning to that TaskMap according to the TaskChampion data model. For - * example, [`get_status`](Task::get_status) and [`set_status`](TaskMut::set_status) translate from - * strings in the TaskMap to [`Status`]. - * - * The same approach applies for more complex data such as dependencies or annotations. Users of - * this API should only need the [`get_taskmap`](Task::get_taskmap) method for debugging purposes, - * and should never need to make changes to the TaskMap directly. - */ - -/// A task, as publicly exposed by this crate. -/// -/// Note that Task objects represent a snapshot of the task at a moment in time, and are not -/// protected by the atomicity of the backend storage. Concurrent modifications are safe, -/// but a Task that is cached for more than a few seconds may cause the user to see stale -/// data. Fetch, use, and drop Tasks quickly. -/// -/// This struct contains only getters for various values on the task. The -/// [`into_mut`](Task::into_mut) method -/// returns a TaskMut which can be used to modify the task. -#[derive(Debug, Clone)] -pub struct Task { - uuid: Uuid, - taskmap: TaskMap, - depmap: Rc, -} - -impl PartialEq for Task { - fn eq(&self, other: &Task) -> bool { - // compare only the taskmap and uuid; depmap is just present for reference - self.uuid == other.uuid && self.taskmap == other.taskmap - } -} - -/// A mutable task, with setter methods. -/// -/// Most methods are simple setters and not further described. Calling a setter will update the -/// referenced Replica, as well as the included Task, immediately. -/// -/// The [`Task`] methods are available on [`TaskMut`] via [`Deref`](std::ops::Deref). -pub struct TaskMut<'r> { - task: Task, - replica: &'r mut Replica, - updated_modified: bool, -} - -/// An enum containing all of the key names defined in the data model, with the exception -/// of the properties containing data (`tag_..`, etc.) -#[derive(strum_macros::AsRefStr, strum_macros::EnumString)] -#[strum(serialize_all = "kebab-case")] -enum Prop { - Description, - Due, - Modified, - Start, - Status, - Priority, - Wait, - End, - Entry, -} - -#[allow(clippy::ptr_arg)] -fn uda_string_to_tuple(key: &str) -> (&str, &str) { - let mut iter = key.splitn(2, '.'); - let first = iter.next().unwrap(); - let second = iter.next(); - if let Some(second) = second { - (first, second) - } else { - ("", first) - } -} - -fn uda_tuple_to_string(namespace: impl AsRef, key: impl AsRef) -> String { - let namespace = namespace.as_ref(); - let key = key.as_ref(); - if namespace.is_empty() { - key.into() - } else { - format!("{}.{}", namespace, key) - } -} - -impl Task { - pub(crate) fn new(uuid: Uuid, taskmap: TaskMap, depmap: Rc) -> Task { - Task { - uuid, - taskmap, - depmap, - } - } - - pub fn get_uuid(&self) -> Uuid { - self.uuid - } - - pub fn get_taskmap(&self) -> &TaskMap { - &self.taskmap - } - - /// Prepare to mutate this task, requiring a mutable Replica - /// in order to update the data it contains. - pub fn into_mut(self, replica: &mut Replica) -> TaskMut { - TaskMut { - task: self, - replica, - updated_modified: false, - } - } - - pub fn get_status(&self) -> Status { - self.taskmap - .get(Prop::Status.as_ref()) - .map(|s| Status::from_taskmap(s)) - .unwrap_or(Status::Pending) - } - - pub fn get_description(&self) -> &str { - self.taskmap - .get(Prop::Description.as_ref()) - .map(|s| s.as_ref()) - .unwrap_or("") - } - - pub fn get_entry(&self) -> Option { - self.get_timestamp(Prop::Entry.as_ref()) - } - - pub fn get_priority(&self) -> &str { - self.taskmap - .get(Prop::Priority.as_ref()) - .map(|s| s.as_ref()) - .unwrap_or("") - } - - /// Get the wait time. If this value is set, it will be returned, even - /// if it is in the past. - pub fn get_wait(&self) -> Option { - self.get_timestamp(Prop::Wait.as_ref()) - } - - /// Determine whether this task is waiting now. - pub fn is_waiting(&self) -> bool { - if let Some(ts) = self.get_wait() { - return ts > Utc::now(); - } - false - } - - /// Determine whether this task is active -- that is, that it has been started - /// and not stopped. - pub fn is_active(&self) -> bool { - self.taskmap.contains_key(Prop::Start.as_ref()) - } - - /// Determine whether this task is blocked -- that is, has at least one unresolved dependency. - pub fn is_blocked(&self) -> bool { - self.depmap.dependencies(self.uuid).next().is_some() - } - - /// Determine whether this task is blocking -- that is, has at least one unresolved dependent. - pub fn is_blocking(&self) -> bool { - self.depmap.dependents(self.uuid).next().is_some() - } - - /// Determine whether a given synthetic tag is present on this task. All other - /// synthetic tag calculations are based on this one. - fn has_synthetic_tag(&self, synth: &SyntheticTag) -> bool { - match synth { - SyntheticTag::Waiting => self.is_waiting(), - SyntheticTag::Active => self.is_active(), - SyntheticTag::Pending => self.get_status() == Status::Pending, - SyntheticTag::Completed => self.get_status() == Status::Completed, - SyntheticTag::Deleted => self.get_status() == Status::Deleted, - SyntheticTag::Blocked => self.is_blocked(), - SyntheticTag::Unblocked => !self.is_blocked(), - SyntheticTag::Blocking => self.is_blocking(), - } - } - - /// Check if this task has the given tag - pub fn has_tag(&self, tag: &Tag) -> bool { - match tag.inner() { - TagInner::User(s) => self.taskmap.contains_key(&format!("tag_{}", s)), - TagInner::Synthetic(st) => self.has_synthetic_tag(st), - } - } - - /// Iterate over the task's tags - pub fn get_tags(&self) -> impl Iterator + '_ { - use strum::IntoEnumIterator; - - self.taskmap - .iter() - .filter_map(|(k, _)| { - if let Some(tag) = k.strip_prefix("tag_") { - if let Ok(tag) = tag.try_into() { - return Some(tag); - } - // note that invalid "tag_*" are ignored - } - None - }) - .chain( - SyntheticTag::iter() - .filter(move |st| self.has_synthetic_tag(st)) - .map(|st| Tag::from_inner(TagInner::Synthetic(st))), - ) - } - - /// Iterate over the task's annotations, in arbitrary order. - pub fn get_annotations(&self) -> impl Iterator + '_ { - self.taskmap.iter().filter_map(|(k, v)| { - if let Some(ts) = k.strip_prefix("annotation_") { - if let Ok(ts) = ts.parse::() { - return Some(Annotation { - entry: utc_timestamp(ts), - description: v.to_owned(), - }); - } - // note that invalid "annotation_*" are ignored - } - None - }) - } - - /// Get the named user defined attributes (UDA). This will return None - /// for any key defined in the Task data model, regardless of whether - /// it is set or not. - pub fn get_uda(&self, namespace: &str, key: &str) -> Option<&str> { - self.get_legacy_uda(uda_tuple_to_string(namespace, key).as_ref()) - } - - /// Get the user defined attributes (UDAs) of this task, in arbitrary order. Each key is split - /// on the first `.` character. Legacy keys that do not contain `.` are represented as `("", - /// key)`. - pub fn get_udas(&self) -> impl Iterator + '_ { - self.taskmap - .iter() - .filter(|(k, _)| !Task::is_known_key(k)) - .map(|(k, v)| (uda_string_to_tuple(k), v.as_ref())) - } - - /// Get the named user defined attribute (UDA) in a legacy format. This will return None for - /// any key defined in the Task data model, regardless of whether it is set or not. - pub fn get_legacy_uda(&self, key: &str) -> Option<&str> { - if Task::is_known_key(key) { - return None; - } - self.taskmap.get(key).map(|s| s.as_ref()) - } - - /// Like `get_udas`, but returning each UDA key as a single string. - pub fn get_legacy_udas(&self) -> impl Iterator + '_ { - self.taskmap - .iter() - .filter(|(p, _)| !Task::is_known_key(p)) - .map(|(p, v)| (p.as_ref(), v.as_ref())) - } - - /// Get the modification time for this task. - pub fn get_modified(&self) -> Option { - self.get_timestamp(Prop::Modified.as_ref()) - } - - /// Get the due time for this task. - pub fn get_due(&self) -> Option { - self.get_timestamp(Prop::Due.as_ref()) - } - - /// Get the UUIDs of tasks on which this task depends. - /// - /// This includes all dependencies, regardless of their status. In fact, it may include - /// dependencies that do not exist. - pub fn get_dependencies(&self) -> impl Iterator + '_ { - self.taskmap.iter().filter_map(|(p, _)| { - if let Some(dep_str) = p.strip_prefix("dep_") { - if let Ok(u) = Uuid::parse_str(dep_str) { - return Some(u); - } - // (un-parseable dep_.. properties are ignored) - } - None - }) - } - - /// Get task's property value by name. - pub fn get_value>(&self, property: S) -> Option<&str> { - let property = property.into(); - self.taskmap.get(&property).map(|s| s.as_ref()) - } - - // -- utility functions - - fn is_known_key(key: &str) -> bool { - Prop::from_str(key).is_ok() - || key.starts_with("tag_") - || key.starts_with("annotation_") - || key.starts_with("dep_") - } - - fn get_timestamp(&self, property: &str) -> Option { - if let Some(ts) = self.taskmap.get(property) { - if let Ok(ts) = ts.parse() { - return Some(utc_timestamp(ts)); - } - // if the value does not parse as an integer, default to None - } - None - } -} - -impl<'r> TaskMut<'r> { - /// Get the immutable version of this object, ending the exclusive reference to the Replica. - pub fn into_immut(self) -> Task { - self.task - } - - /// Set the task's status. This also adds the task to the working set if the - /// new status puts it in that set. - pub fn set_status(&mut self, status: Status) -> Result<()> { - match status { - Status::Pending | Status::Recurring => { - // clear "end" when a task becomes "pending" or "recurring" - if self.taskmap.contains_key(Prop::End.as_ref()) { - self.set_timestamp(Prop::End.as_ref(), None)?; - } - // ..and add to working set - self.replica.add_to_working_set(self.uuid)?; - } - Status::Completed | Status::Deleted => { - // set "end" when a task is deleted or completed - if !self.taskmap.contains_key(Prop::End.as_ref()) { - self.set_timestamp(Prop::End.as_ref(), Some(Utc::now()))?; - } - } - _ => {} - } - self.set_string( - Prop::Status.as_ref(), - Some(String::from(status.to_taskmap())), - ) - } - - pub fn set_description(&mut self, description: String) -> Result<()> { - self.set_string(Prop::Description.as_ref(), Some(description)) - } - - pub fn set_priority(&mut self, priority: String) -> Result<()> { - self.set_string(Prop::Priority.as_ref(), Some(priority)) - } - - pub fn set_entry(&mut self, entry: Option) -> Result<()> { - self.set_timestamp(Prop::Entry.as_ref(), entry) - } - - pub fn set_wait(&mut self, wait: Option) -> Result<()> { - self.set_timestamp(Prop::Wait.as_ref(), wait) - } - - pub fn set_modified(&mut self, modified: Timestamp) -> Result<()> { - self.set_timestamp(Prop::Modified.as_ref(), Some(modified)) - } - - /// Set a tasks's property by name. - /// - /// This will not automatically update the `modified` timestamp or perform any other - /// "automatic" operations -- it simply sets the property. Howerver, if property is - /// "modified", then subsequent calls to other `set_..` methods will not update the - /// `modified` timestamp. - pub fn set_value>(&mut self, property: S, value: Option) -> Result<()> { - let property = property.into(); - - if &property == "modified" { - self.updated_modified = true; - } - - if let Some(ref v) = value { - trace!("task {}: set property {}={:?}", self.task.uuid, property, v); - } else { - trace!("task {}: remove property {}", self.task.uuid, property); - } - - self.task.taskmap = self - .replica - .update_task(self.task.uuid, &property, value.as_ref())?; - - Ok(()) - } - - /// Start the task by creating "start": "", if the task is not already - /// active. - pub fn start(&mut self) -> Result<()> { - if self.is_active() { - return Ok(()); - } - self.set_timestamp(Prop::Start.as_ref(), Some(Utc::now())) - } - - /// Stop the task by removing the `start` key - pub fn stop(&mut self) -> Result<()> { - self.set_timestamp(Prop::Start.as_ref(), None) - } - - /// Mark this task as complete - pub fn done(&mut self) -> Result<()> { - self.set_status(Status::Completed) - } - - /// Mark this task as deleted. - /// - /// Note that this does not delete the task. It merely marks the task as - /// deleted. - pub fn delete(&mut self) -> Result<()> { - self.set_status(Status::Deleted) - } - - /// Add a tag to this task. Does nothing if the tag is already present. - pub fn add_tag(&mut self, tag: &Tag) -> Result<()> { - if tag.is_synthetic() { - return Err(Error::Usage(String::from( - "Synthetic tags cannot be modified", - ))); - } - self.set_string(format!("tag_{}", tag), Some("".to_owned())) - } - - /// Remove a tag from this task. Does nothing if the tag is not present. - pub fn remove_tag(&mut self, tag: &Tag) -> Result<()> { - if tag.is_synthetic() { - return Err(Error::Usage(String::from( - "Synthetic tags cannot be modified", - ))); - } - self.set_string(format!("tag_{}", tag), None) - } - - /// Add a new annotation. Note that annotations with the same entry time - /// will overwrite one another. - pub fn add_annotation(&mut self, ann: Annotation) -> Result<()> { - self.set_string( - format!("annotation_{}", ann.entry.timestamp()), - Some(ann.description), - ) - } - - /// Remove an annotation, based on its entry time. - pub fn remove_annotation(&mut self, entry: Timestamp) -> Result<()> { - self.set_string(format!("annotation_{}", entry.timestamp()), None) - } - - pub fn set_due(&mut self, due: Option) -> Result<()> { - self.set_timestamp(Prop::Due.as_ref(), due) - } - - /// Set a user-defined attribute (UDA). This will fail if the key is defined by the data - /// model. - pub fn set_uda( - &mut self, - namespace: impl AsRef, - key: impl AsRef, - value: impl Into, - ) -> Result<()> { - let key = uda_tuple_to_string(namespace, key); - self.set_legacy_uda(key, value) - } - - /// Remove a user-defined attribute (UDA). This will fail if the key is defined by the data - /// model. - pub fn remove_uda(&mut self, namespace: impl AsRef, key: impl AsRef) -> Result<()> { - let key = uda_tuple_to_string(namespace, key); - self.remove_legacy_uda(key) - } - - /// Set a user-defined attribute (UDA), where the key is a legacy key. - pub fn set_legacy_uda( - &mut self, - key: impl Into, - value: impl Into, - ) -> Result<()> { - let key = key.into(); - if Task::is_known_key(&key) { - return Err(Error::Usage(format!( - "Property name {} as special meaning in a task and cannot be used as a UDA", - key - ))); - } - self.set_string(key, Some(value.into())) - } - - /// Remove a user-defined attribute (UDA), where the key is a legacy key. - pub fn remove_legacy_uda(&mut self, key: impl Into) -> Result<()> { - let key = key.into(); - if Task::is_known_key(&key) { - return Err(Error::Usage(format!( - "Property name {} as special meaning in a task and cannot be used as a UDA", - key - ))); - } - self.set_string(key, None) - } - - /// Add a dependency. - pub fn add_dependency(&mut self, dep: Uuid) -> Result<()> { - let key = format!("dep_{}", dep); - self.set_string(key, Some("".to_string())) - } - - /// Remove a dependency. - pub fn remove_dependency(&mut self, dep: Uuid) -> Result<()> { - let key = format!("dep_{}", dep); - self.set_string(key, None) - } - - // -- utility functions - - fn update_modified(&mut self) -> Result<()> { - if !self.updated_modified { - let now = format!("{}", Utc::now().timestamp()); - trace!("task {}: set property modified={:?}", self.task.uuid, now); - self.task.taskmap = - self.replica - .update_task(self.task.uuid, Prop::Modified.as_ref(), Some(now))?; - self.updated_modified = true; - } - Ok(()) - } - - fn set_string>(&mut self, property: S, value: Option) -> Result<()> { - let property = property.into(); - // update the modified timestamp unless we are setting it explicitly - if &property != "modified" { - self.update_modified()?; - } - - self.set_value(property, value) - } - - fn set_timestamp(&mut self, property: &str, value: Option) -> Result<()> { - self.set_string(property, value.map(|v| v.timestamp().to_string())) - } - - /// Used by tests to ensure that updates are properly written - #[cfg(test)] - fn reload(&mut self) -> Result<()> { - let uuid = self.uuid; - let task = self.replica.get_task(uuid)?.unwrap(); - self.task.taskmap = task.taskmap; - Ok(()) - } -} - -impl<'r> std::ops::Deref for TaskMut<'r> { - type Target = Task; - - fn deref(&self) -> &Self::Target { - &self.task - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - use std::collections::HashSet; - - fn dm() -> Rc { - Rc::new(DependencyMap::new()) - } - - fn with_mut_task(f: F) { - let mut replica = Replica::new_inmemory(); - let task = replica.new_task(Status::Pending, "test".into()).unwrap(); - let task = task.into_mut(&mut replica); - f(task) - } - - /// Create a user tag, without checking its validity - fn utag(name: &'static str) -> Tag { - Tag::from_inner(TagInner::User(name.into())) - } - - /// Create a synthetic tag - fn stag(synth: SyntheticTag) -> Tag { - Tag::from_inner(TagInner::Synthetic(synth)) - } - - #[test] - fn test_is_active_never_started() { - let task = Task::new(Uuid::new_v4(), TaskMap::new(), dm()); - assert!(!task.is_active()); - } - - #[test] - fn test_is_active_active() { - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("start"), String::from("1234"))] - .drain(..) - .collect(), - dm(), - ); - - assert!(task.is_active()); - } - - #[test] - fn test_is_active_inactive() { - let task = Task::new(Uuid::new_v4(), Default::default(), dm()); - assert!(!task.is_active()); - } - - #[test] - fn test_entry_not_set() { - let task = Task::new(Uuid::new_v4(), TaskMap::new(), dm()); - assert_eq!(task.get_entry(), None); - } - - #[test] - fn test_entry_set() { - let ts = Utc.ymd(1980, 1, 1).and_hms(0, 0, 0); - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("entry"), format!("{}", ts.timestamp()))] - .drain(..) - .collect(), - dm(), - ); - assert_eq!(task.get_entry(), Some(ts)); - } - - #[test] - fn test_wait_not_set() { - let task = Task::new(Uuid::new_v4(), TaskMap::new(), dm()); - - assert!(!task.is_waiting()); - assert_eq!(task.get_wait(), None); - } - - #[test] - fn test_wait_in_past() { - let ts = Utc.ymd(1970, 1, 1).and_hms(0, 0, 0); - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("wait"), format!("{}", ts.timestamp()))] - .drain(..) - .collect(), - dm(), - ); - - assert!(!task.is_waiting()); - assert_eq!(task.get_wait(), Some(ts)); - } - - #[test] - fn test_wait_in_future() { - let ts = Utc.ymd(3000, 1, 1).and_hms(0, 0, 0); - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("wait"), format!("{}", ts.timestamp()))] - .drain(..) - .collect(), - dm(), - ); - - assert!(task.is_waiting()); - assert_eq!(task.get_wait(), Some(ts)); - } - - #[test] - fn test_has_tag() { - let task = Task::new( - Uuid::new_v4(), - vec![ - (String::from("tag_abc"), String::from("")), - (String::from("start"), String::from("1234")), - ] - .drain(..) - .collect(), - dm(), - ); - - assert!(task.has_tag(&utag("abc"))); - assert!(!task.has_tag(&utag("def"))); - assert!(task.has_tag(&stag(SyntheticTag::Active))); - assert!(task.has_tag(&stag(SyntheticTag::Pending))); - assert!(!task.has_tag(&stag(SyntheticTag::Waiting))); - } - - #[test] - fn test_get_tags() { - let task = Task::new( - Uuid::new_v4(), - vec![ - (String::from("tag_abc"), String::from("")), - (String::from("tag_def"), String::from("")), - // set `wait` so the synthetic tag WAITING is present - (String::from("wait"), String::from("33158909732")), - ] - .drain(..) - .collect(), - dm(), - ); - - let tags: HashSet<_> = task.get_tags().collect(); - let exp = set![ - utag("abc"), - utag("def"), - stag(SyntheticTag::Pending), - stag(SyntheticTag::Waiting), - stag(SyntheticTag::Unblocked), - ]; - assert_eq!(tags, exp); - } - - #[test] - fn test_get_tags_invalid_tags() { - let task = Task::new( - Uuid::new_v4(), - vec![ - (String::from("tag_ok"), String::from("")), - (String::from("tag_"), String::from("")), - (String::from("tag_123"), String::from("")), - (String::from("tag_a!!"), String::from("")), - ] - .drain(..) - .collect(), - dm(), - ); - - // only "ok" is OK - let tags: HashSet<_> = task.get_tags().collect(); - assert_eq!( - tags, - set![ - utag("ok"), - stag(SyntheticTag::Pending), - stag(SyntheticTag::Unblocked) - ] - ); - } - - #[test] - fn test_get_due() { - let test_time = Utc.ymd(2033, 1, 1).and_hms(0, 0, 0); - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("due"), format!("{}", test_time.timestamp()))] - .drain(..) - .collect(), - dm(), - ); - assert_eq!(task.get_due(), Some(test_time)) - } - - #[test] - fn test_get_invalid_due() { - let task = Task::new( - Uuid::new_v4(), - vec![(String::from("due"), String::from("invalid"))] - .drain(..) - .collect(), - dm(), - ); - assert_eq!(task.get_due(), None); - } - - #[test] - fn test_add_due() { - let test_time = Utc.ymd(2033, 1, 1).and_hms(0, 0, 0); - with_mut_task(|mut task| { - assert_eq!(task.get_due(), None); - task.set_due(Some(test_time)).unwrap(); - assert_eq!(task.get_due(), Some(test_time)) - }); - } - - #[test] - fn test_remove_due() { - let test_time = Utc.ymd(2033, 1, 1).and_hms(0, 0, 0); - with_mut_task(|mut task| { - task.set_due(Some(test_time)).unwrap(); - task.reload().unwrap(); - assert!(task.taskmap.contains_key("due")); - task.set_due(None).unwrap(); - assert!(!task.taskmap.contains_key("due")); - }); - } - - #[test] - fn test_get_priority_default() { - let task = Task::new(Uuid::new_v4(), TaskMap::new(), dm()); - assert_eq!(task.get_priority(), ""); - } - - #[test] - fn test_get_annotations() { - let task = Task::new( - Uuid::new_v4(), - vec![ - ( - String::from("annotation_1635301873"), - String::from("left message"), - ), - ( - String::from("annotation_1635301883"), - String::from("left another message"), - ), - (String::from("annotation_"), String::from("invalid")), - (String::from("annotation_abcde"), String::from("invalid")), - ] - .drain(..) - .collect(), - dm(), - ); - - let mut anns: Vec<_> = task.get_annotations().collect(); - anns.sort(); - assert_eq!( - anns, - vec![ - Annotation { - entry: Utc.timestamp(1635301873, 0), - description: "left message".into() - }, - Annotation { - entry: Utc.timestamp(1635301883, 0), - description: "left another message".into() - } - ] - ); - } - - #[test] - fn test_add_annotation() { - with_mut_task(|mut task| { - task.add_annotation(Annotation { - entry: Utc.timestamp(1635301900, 0), - description: "right message".into(), - }) - .unwrap(); - let k = "annotation_1635301900"; - assert_eq!(task.taskmap[k], "right message".to_owned()); - task.reload().unwrap(); - assert_eq!(task.taskmap[k], "right message".to_owned()); - // adding with same time overwrites.. - task.add_annotation(Annotation { - entry: Utc.timestamp(1635301900, 0), - description: "right message 2".into(), - }) - .unwrap(); - assert_eq!(task.taskmap[k], "right message 2".to_owned()); - }); - } - - #[test] - fn test_remove_annotation() { - with_mut_task(|mut task| { - task.set_string("annotation_1635301873", Some("left message".into())) - .unwrap(); - task.set_string("annotation_1635301883", Some("left another message".into())) - .unwrap(); - - task.remove_annotation(Utc.timestamp(1635301873, 0)) - .unwrap(); - - task.reload().unwrap(); - - let mut anns: Vec<_> = task.get_annotations().collect(); - anns.sort(); - assert_eq!( - anns, - vec![Annotation { - entry: Utc.timestamp(1635301883, 0), - description: "left another message".into() - }] - ); - }); - } - - #[test] - fn test_set_get_priority() { - with_mut_task(|mut task| { - assert_eq!(task.get_priority(), ""); - task.set_priority("H".into()).unwrap(); - assert_eq!(task.get_priority(), "H"); - }); - } - - #[test] - fn test_set_status_pending() { - with_mut_task(|mut task| { - task.done().unwrap(); - - task.set_status(Status::Pending).unwrap(); - assert_eq!(task.get_status(), Status::Pending); - assert!(!task.taskmap.contains_key("end")); - assert!(task.has_tag(&stag(SyntheticTag::Pending))); - assert!(!task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_set_status_recurring() { - with_mut_task(|mut task| { - task.done().unwrap(); - - task.set_status(Status::Recurring).unwrap(); - assert_eq!(task.get_status(), Status::Recurring); - assert!(!task.taskmap.contains_key("end")); - assert!(!task.has_tag(&stag(SyntheticTag::Pending))); // recurring is not +PENDING - assert!(!task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_set_status_completed() { - with_mut_task(|mut task| { - task.set_status(Status::Completed).unwrap(); - assert_eq!(task.get_status(), Status::Completed); - assert!(task.taskmap.contains_key("end")); - assert!(!task.has_tag(&stag(SyntheticTag::Pending))); - assert!(task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_set_status_deleted() { - with_mut_task(|mut task| { - task.set_status(Status::Deleted).unwrap(); - assert_eq!(task.get_status(), Status::Deleted); - assert!(task.taskmap.contains_key("end")); - assert!(!task.has_tag(&stag(SyntheticTag::Pending))); - assert!(!task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_set_get_value() { - with_mut_task(|mut task| { - let property = "property-name"; - task.set_value(property, Some("value".into())).unwrap(); - assert_eq!(task.get_value(property), Some("value")); - task.set_value(property, None).unwrap(); - assert_eq!(task.get_value(property), None); - }); - } - - #[test] - fn test_start() { - with_mut_task(|mut task| { - task.start().unwrap(); - assert!(task.taskmap.contains_key("start")); - - task.reload().unwrap(); - assert!(task.taskmap.contains_key("start")); - - // second start doesn't change anything.. - task.start().unwrap(); - assert!(task.taskmap.contains_key("start")); - - task.reload().unwrap(); - assert!(task.taskmap.contains_key("start")); - }); - } - - #[test] - fn test_stop() { - with_mut_task(|mut task| { - task.start().unwrap(); - task.stop().unwrap(); - assert!(!task.taskmap.contains_key("start")); - - task.reload().unwrap(); - assert!(!task.taskmap.contains_key("start")); - - // redundant call does nothing.. - task.stop().unwrap(); - assert!(!task.taskmap.contains_key("start")); - - task.reload().unwrap(); - assert!(!task.taskmap.contains_key("start")); - }); - } - - #[test] - fn test_done() { - with_mut_task(|mut task| { - task.done().unwrap(); - assert_eq!(task.get_status(), Status::Completed); - assert!(task.taskmap.contains_key("end")); - assert!(task.has_tag(&stag(SyntheticTag::Completed))); - - // redundant call does nothing.. - task.done().unwrap(); - assert_eq!(task.get_status(), Status::Completed); - assert!(task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_delete() { - with_mut_task(|mut task| { - task.delete().unwrap(); - assert_eq!(task.get_status(), Status::Deleted); - assert!(task.taskmap.contains_key("end")); - assert!(!task.has_tag(&stag(SyntheticTag::Completed))); - - // redundant call does nothing.. - task.delete().unwrap(); - assert_eq!(task.get_status(), Status::Deleted); - assert!(!task.has_tag(&stag(SyntheticTag::Completed))); - }); - } - - #[test] - fn test_add_tags() { - with_mut_task(|mut task| { - task.add_tag(&utag("abc")).unwrap(); - assert!(task.taskmap.contains_key("tag_abc")); - task.reload().unwrap(); - assert!(task.taskmap.contains_key("tag_abc")); - // redundant add has no effect.. - task.add_tag(&utag("abc")).unwrap(); - assert!(task.taskmap.contains_key("tag_abc")); - }); - } - - #[test] - fn test_remove_tags() { - with_mut_task(|mut task| { - task.add_tag(&utag("abc")).unwrap(); - task.reload().unwrap(); - assert!(task.taskmap.contains_key("tag_abc")); - - task.remove_tag(&utag("abc")).unwrap(); - assert!(!task.taskmap.contains_key("tag_abc")); - // redundant remove has no effect.. - task.remove_tag(&utag("abc")).unwrap(); - assert!(!task.taskmap.contains_key("tag_abc")); - }); - } - - #[test] - fn test_get_udas() { - let task = Task::new( - Uuid::new_v4(), - vec![ - ("description".into(), "not a uda".into()), - ("modified".into(), "not a uda".into()), - ("start".into(), "not a uda".into()), - ("status".into(), "not a uda".into()), - ("wait".into(), "not a uda".into()), - ("start".into(), "not a uda".into()), - ("tag_abc".into(), "not a uda".into()), - ("dep_1234".into(), "not a uda".into()), - ("annotation_1234".into(), "not a uda".into()), - ("githubid".into(), "123".into()), - ("jira.url".into(), "h://x".into()), - ] - .drain(..) - .collect(), - dm(), - ); - - let mut udas: Vec<_> = task.get_udas().collect(); - udas.sort_unstable(); - assert_eq!( - udas, - vec![(("", "githubid"), "123"), (("jira", "url"), "h://x")] - ); - } - - #[test] - fn test_get_uda() { - let task = Task::new( - Uuid::new_v4(), - vec![ - ("description".into(), "not a uda".into()), - ("githubid".into(), "123".into()), - ("jira.url".into(), "h://x".into()), - ] - .drain(..) - .collect(), - dm(), - ); - - assert_eq!(task.get_uda("", "description"), None); // invalid UDA - assert_eq!(task.get_uda("", "githubid"), Some("123")); - assert_eq!(task.get_uda("jira", "url"), Some("h://x")); - assert_eq!(task.get_uda("bugzilla", "url"), None); - } - - #[test] - fn test_get_legacy_uda() { - let task = Task::new( - Uuid::new_v4(), - vec![ - ("description".into(), "not a uda".into()), - ("dep_1234".into(), "not a uda".into()), - ("githubid".into(), "123".into()), - ("jira.url".into(), "h://x".into()), - ] - .drain(..) - .collect(), - dm(), - ); - - assert_eq!(task.get_legacy_uda("description"), None); // invalid UDA - assert_eq!(task.get_legacy_uda("dep_1234"), None); // invalid UDA - assert_eq!(task.get_legacy_uda("githubid"), Some("123")); - assert_eq!(task.get_legacy_uda("jira.url"), Some("h://x")); - assert_eq!(task.get_legacy_uda("bugzilla.url"), None); - } - - #[test] - fn test_set_uda() { - with_mut_task(|mut task| { - task.set_uda("jira", "url", "h://y").unwrap(); - let udas: Vec<_> = task.get_udas().collect(); - assert_eq!(udas, vec![(("jira", "url"), "h://y")]); - - task.set_uda("", "jiraid", "TW-1234").unwrap(); - - let mut udas: Vec<_> = task.get_udas().collect(); - udas.sort_unstable(); - assert_eq!( - udas, - vec![(("", "jiraid"), "TW-1234"), (("jira", "url"), "h://y")] - ); - }) - } - - #[test] - fn test_set_legacy_uda() { - with_mut_task(|mut task| { - task.set_legacy_uda("jira.url", "h://y").unwrap(); - let udas: Vec<_> = task.get_udas().collect(); - assert_eq!(udas, vec![(("jira", "url"), "h://y")]); - - task.set_legacy_uda("jiraid", "TW-1234").unwrap(); - - let mut udas: Vec<_> = task.get_udas().collect(); - udas.sort_unstable(); - assert_eq!( - udas, - vec![(("", "jiraid"), "TW-1234"), (("jira", "url"), "h://y")] - ); - }) - } - - #[test] - fn test_set_uda_invalid() { - with_mut_task(|mut task| { - assert!(task.set_uda("", "modified", "123").is_err()); - assert!(task.set_uda("", "tag_abc", "123").is_err()); - assert!(task.set_legacy_uda("modified", "123").is_err()); - assert!(task.set_legacy_uda("tag_abc", "123").is_err()); - }) - } - - #[test] - fn test_remove_uda() { - with_mut_task(|mut task| { - task.set_string("github.id", Some("123".into())).unwrap(); - task.remove_uda("github", "id").unwrap(); - - let udas: Vec<_> = task.get_udas().collect(); - assert_eq!(udas, vec![]); - }) - } - - #[test] - fn test_remove_legacy_uda() { - with_mut_task(|mut task| { - task.set_string("githubid", Some("123".into())).unwrap(); - task.remove_legacy_uda("githubid").unwrap(); - - let udas: Vec<_> = task.get_udas().collect(); - assert_eq!(udas, vec![]); - }) - } - - #[test] - fn test_remove_uda_invalid() { - with_mut_task(|mut task| { - assert!(task.remove_uda("", "modified").is_err()); - assert!(task.remove_uda("", "tag_abc").is_err()); - assert!(task.remove_legacy_uda("modified").is_err()); - assert!(task.remove_legacy_uda("tag_abc").is_err()); - }) - } - - #[test] - fn test_dependencies() { - with_mut_task(|mut task| { - assert_eq!(task.get_dependencies().collect::>(), vec![]); - let dep1 = Uuid::new_v4(); - let dep2 = Uuid::new_v4(); - - task.add_dependency(dep1).unwrap(); - assert_eq!(task.get_dependencies().collect::>(), vec![dep1]); - - task.add_dependency(dep1).unwrap(); // add twice is ok - task.add_dependency(dep2).unwrap(); - let deps = task.get_dependencies().collect::>(); - assert!(deps.contains(&dep1)); - assert!(deps.contains(&dep2)); - - task.remove_dependency(dep1).unwrap(); - assert_eq!(task.get_dependencies().collect::>(), vec![dep2]); - }) - } - - #[test] - fn dependencies_tags() { - let mut rep = Replica::new_inmemory(); - let uuid1; - let uuid2; - { - let t1 = rep.new_task(Status::Pending, "1".into()).unwrap(); - uuid1 = t1.get_uuid(); - let t2 = rep.new_task(Status::Pending, "2".into()).unwrap(); - uuid2 = t2.get_uuid(); - - let mut t1 = t1.into_mut(&mut rep); - t1.add_dependency(t2.get_uuid()).unwrap(); - } - - // force-refresh depmap - rep.dependency_map(true).unwrap(); - - let t1 = rep.get_task(uuid1).unwrap().unwrap(); - let t2 = rep.get_task(uuid2).unwrap().unwrap(); - assert!(t1.has_tag(&stag(SyntheticTag::Blocked))); - assert!(!t1.has_tag(&stag(SyntheticTag::Unblocked))); - assert!(!t1.has_tag(&stag(SyntheticTag::Blocking))); - assert!(!t2.has_tag(&stag(SyntheticTag::Blocked))); - assert!(t2.has_tag(&stag(SyntheticTag::Unblocked))); - assert!(t2.has_tag(&stag(SyntheticTag::Blocking))); - } - - #[test] - fn set_value_modified() { - with_mut_task(|mut task| { - // set the modified property to something in the past.. - task.set_value("modified", Some("1671820000".into())) - .unwrap(); - // update another property - task.set_description("fun times".into()).unwrap(); - // verify the modified property was not updated - assert_eq!(task.get_value("modified").unwrap(), "1671820000") - }) - } -} diff --git a/taskchampion/taskchampion/src/task/time.rs b/taskchampion/taskchampion/src/task/time.rs deleted file mode 100644 index 928da2a6a..000000000 --- a/taskchampion/taskchampion/src/task/time.rs +++ /dev/null @@ -1,11 +0,0 @@ -use chrono::{offset::LocalResult, DateTime, TimeZone, Utc}; - -pub type Timestamp = DateTime; - -pub fn utc_timestamp(secs: i64) -> Timestamp { - match Utc.timestamp_opt(secs, 0) { - LocalResult::Single(tz) => tz, - // The other two variants are None and Ambiguous, which both are caused by DST. - _ => unreachable!("We're requesting UTC so daylight saving time isn't a factor."), - } -} diff --git a/taskchampion/taskchampion/src/taskdb/apply.rs b/taskchampion/taskchampion/src/taskdb/apply.rs deleted file mode 100644 index 0cea9f28c..000000000 --- a/taskchampion/taskchampion/src/taskdb/apply.rs +++ /dev/null @@ -1,406 +0,0 @@ -use crate::errors::{Error, Result}; -use crate::server::SyncOp; -use crate::storage::{ReplicaOp, StorageTxn, TaskMap}; - -/// Apply the given SyncOp to the replica, updating both the task data and adding a -/// ReplicaOp to the list of operations. Returns the TaskMap of the task after the -/// operation has been applied (or an empty TaskMap for Delete). It is not an error -/// to create an existing task, nor to delete a nonexistent task. -pub(super) fn apply_and_record(txn: &mut dyn StorageTxn, op: SyncOp) -> Result { - match op { - SyncOp::Create { uuid } => { - let created = txn.create_task(uuid)?; - if created { - txn.add_operation(ReplicaOp::Create { uuid })?; - txn.commit()?; - Ok(TaskMap::new()) - } else { - Ok(txn - .get_task(uuid)? - .expect("create_task failed but task does not exist")) - } - } - SyncOp::Delete { uuid } => { - let task = txn.get_task(uuid)?; - if let Some(task) = task { - txn.delete_task(uuid)?; - txn.add_operation(ReplicaOp::Delete { - uuid, - old_task: task, - })?; - txn.commit()?; - Ok(TaskMap::new()) - } else { - Ok(TaskMap::new()) - } - } - SyncOp::Update { - uuid, - property, - value, - timestamp, - } => { - let task = txn.get_task(uuid)?; - if let Some(mut task) = task { - let old_value = task.get(&property).cloned(); - if let Some(ref v) = value { - task.insert(property.clone(), v.clone()); - } else { - task.remove(&property); - } - txn.set_task(uuid, task.clone())?; - txn.add_operation(ReplicaOp::Update { - uuid, - property, - old_value, - value, - timestamp, - })?; - txn.commit()?; - Ok(task) - } else { - Err(Error::Database(format!("Task {} does not exist", uuid))) - } - } - } -} - -/// Apply an op to the TaskDb's set of tasks (without recording it in the list of operations) -pub(super) fn apply_op(txn: &mut dyn StorageTxn, op: &SyncOp) -> Result<()> { - // TODO: test - // TODO: it'd be nice if this was integrated into apply() somehow, but that clones TaskMaps - // unnecessariliy - match op { - SyncOp::Create { uuid } => { - // insert if the task does not already exist - if !txn.create_task(*uuid)? { - return Err(Error::Database(format!("Task {} already exists", uuid))); - } - } - SyncOp::Delete { ref uuid } => { - if !txn.delete_task(*uuid)? { - return Err(Error::Database(format!("Task {} does not exist", uuid))); - } - } - SyncOp::Update { - ref uuid, - ref property, - ref value, - timestamp: _, - } => { - // update if this task exists, otherwise ignore - if let Some(mut task) = txn.get_task(*uuid)? { - match value { - Some(ref val) => task.insert(property.to_string(), val.clone()), - None => task.remove(property), - }; - txn.set_task(*uuid, task)?; - } else { - return Err(Error::Database(format!("Task {} does not exist", uuid))); - } - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::storage::TaskMap; - use crate::taskdb::TaskDb; - use chrono::Utc; - use pretty_assertions::assert_eq; - use std::collections::HashMap; - use uuid::Uuid; - - #[test] - fn test_apply_create() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let op = SyncOp::Create { uuid }; - - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op)?; - assert_eq!(taskmap.len(), 0); - txn.commit()?; - } - - assert_eq!(db.sorted_tasks(), vec![(uuid, vec![]),]); - assert_eq!(db.operations(), vec![ReplicaOp::Create { uuid }]); - Ok(()) - } - - #[test] - fn test_apply_create_exists() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - { - let mut txn = db.storage.txn()?; - txn.create_task(uuid)?; - let mut taskmap = TaskMap::new(); - taskmap.insert("foo".into(), "bar".into()); - txn.set_task(uuid, taskmap)?; - txn.commit()?; - } - - let op = SyncOp::Create { uuid }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op)?; - - assert_eq!(taskmap.len(), 1); - assert_eq!(taskmap.get("foo").unwrap(), "bar"); - - txn.commit()?; - } - - // create did not delete the old task.. - assert_eq!( - db.sorted_tasks(), - vec![(uuid, vec![("foo".into(), "bar".into())])] - ); - // create was done "manually" above, and no new op was added - assert_eq!(db.operations(), vec![]); - Ok(()) - } - - #[test] - fn test_apply_create_update() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let now = Utc::now(); - let op1 = SyncOp::Create { uuid }; - - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op1)?; - assert_eq!(taskmap.len(), 0); - txn.commit()?; - } - - let op2 = SyncOp::Update { - uuid, - property: String::from("title"), - value: Some("my task".into()), - timestamp: now, - }; - { - let mut txn = db.storage.txn()?; - let mut taskmap = apply_and_record(txn.as_mut(), op2)?; - assert_eq!( - taskmap.drain().collect::>(), - vec![("title".into(), "my task".into())] - ); - txn.commit()?; - } - - assert_eq!( - db.sorted_tasks(), - vec![(uuid, vec![("title".into(), "my task".into())])] - ); - assert_eq!( - db.operations(), - vec![ - ReplicaOp::Create { uuid }, - ReplicaOp::Update { - uuid, - property: "title".into(), - old_value: None, - value: Some("my task".into()), - timestamp: now - } - ] - ); - - Ok(()) - } - - #[test] - fn test_apply_create_update_delete_prop() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let now = Utc::now(); - let op1 = SyncOp::Create { uuid }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op1)?; - assert_eq!(taskmap.len(), 0); - txn.commit()?; - } - - let op2 = SyncOp::Update { - uuid, - property: String::from("title"), - value: Some("my task".into()), - timestamp: now, - }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op2)?; - assert_eq!(taskmap.get("title"), Some(&"my task".to_owned())); - txn.commit()?; - } - - let op3 = SyncOp::Update { - uuid, - property: String::from("priority"), - value: Some("H".into()), - timestamp: now, - }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op3)?; - assert_eq!(taskmap.get("priority"), Some(&"H".to_owned())); - txn.commit()?; - } - - let op4 = SyncOp::Update { - uuid, - property: String::from("title"), - value: None, - timestamp: now, - }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op4)?; - assert_eq!(taskmap.get("title"), None); - assert_eq!(taskmap.get("priority"), Some(&"H".to_owned())); - txn.commit()?; - } - - let mut exp = HashMap::new(); - let mut task = HashMap::new(); - task.insert(String::from("priority"), String::from("H")); - exp.insert(uuid, task); - assert_eq!( - db.sorted_tasks(), - vec![(uuid, vec![("priority".into(), "H".into())])] - ); - assert_eq!( - db.operations(), - vec![ - ReplicaOp::Create { uuid }, - ReplicaOp::Update { - uuid, - property: "title".into(), - old_value: None, - value: Some("my task".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid, - property: "priority".into(), - old_value: None, - value: Some("H".into()), - timestamp: now, - }, - ReplicaOp::Update { - uuid, - property: "title".into(), - old_value: Some("my task".into()), - value: None, - timestamp: now, - } - ] - ); - - Ok(()) - } - - #[test] - fn test_apply_update_does_not_exist() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let op = SyncOp::Update { - uuid, - property: String::from("title"), - value: Some("my task".into()), - timestamp: Utc::now(), - }; - { - let mut txn = db.storage.txn()?; - assert_eq!( - apply_and_record(txn.as_mut(), op) - .err() - .unwrap() - .to_string(), - format!("Task Database Error: Task {} does not exist", uuid) - ); - txn.commit()?; - } - - Ok(()) - } - - #[test] - fn test_apply_create_delete() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let now = Utc::now(); - - let op1 = SyncOp::Create { uuid }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op1)?; - assert_eq!(taskmap.len(), 0); - } - - let op2 = SyncOp::Update { - uuid, - property: String::from("priority"), - value: Some("H".into()), - timestamp: now, - }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op2)?; - assert_eq!(taskmap.get("priority"), Some(&"H".to_owned())); - txn.commit()?; - } - - let op3 = SyncOp::Delete { uuid }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op3)?; - assert_eq!(taskmap.len(), 0); - txn.commit()?; - } - - assert_eq!(db.sorted_tasks(), vec![]); - let mut old_task = TaskMap::new(); - old_task.insert("priority".into(), "H".into()); - assert_eq!( - db.operations(), - vec![ - ReplicaOp::Create { uuid }, - ReplicaOp::Update { - uuid, - property: "priority".into(), - old_value: None, - value: Some("H".into()), - timestamp: now, - }, - ReplicaOp::Delete { uuid, old_task }, - ] - ); - - Ok(()) - } - - #[test] - fn test_apply_delete_not_present() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let op = SyncOp::Delete { uuid }; - { - let mut txn = db.storage.txn()?; - let taskmap = apply_and_record(txn.as_mut(), op)?; - assert_eq!(taskmap.len(), 0); - txn.commit()?; - } - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/taskdb/mod.rs b/taskchampion/taskchampion/src/taskdb/mod.rs deleted file mode 100644 index 6418f9279..000000000 --- a/taskchampion/taskchampion/src/taskdb/mod.rs +++ /dev/null @@ -1,297 +0,0 @@ -use crate::errors::Result; -use crate::server::{Server, SyncOp}; -use crate::storage::{ReplicaOp, Storage, TaskMap}; -use uuid::Uuid; - -mod apply; -mod snapshot; -mod sync; -pub mod undo; -mod working_set; - -/// A TaskDb is the backend for a replica. It manages the storage, operations, synchronization, -/// and so on, and all the invariants that come with it. It leaves the meaning of particular task -/// properties to the replica and task implementations. -pub struct TaskDb { - storage: Box, -} - -impl TaskDb { - /// Create a new TaskDb with the given backend storage - pub fn new(storage: Box) -> TaskDb { - TaskDb { storage } - } - - #[cfg(test)] - pub fn new_inmemory() -> TaskDb { - #[cfg(test)] - use crate::storage::InMemoryStorage; - - TaskDb::new(Box::new(InMemoryStorage::new())) - } - - /// Apply an operation to the TaskDb. This will update the set of tasks and add a ReplicaOp to - /// the set of operations in the TaskDb, and return the TaskMap containing the resulting task's - /// properties (or an empty TaskMap for deletion). - /// - /// Aside from synchronization operations, this is the only way to modify the TaskDb. In cases - /// where an operation does not make sense, this function will do nothing and return an error - /// (but leave the TaskDb in a consistent state). - pub fn apply(&mut self, op: SyncOp) -> Result { - let mut txn = self.storage.txn()?; - apply::apply_and_record(txn.as_mut(), op) - } - - /// Add an UndoPoint operation to the list of replica operations. - pub fn add_undo_point(&mut self) -> Result<()> { - let mut txn = self.storage.txn()?; - txn.add_operation(ReplicaOp::UndoPoint)?; - txn.commit() - } - - /// Get all tasks. - pub fn all_tasks(&mut self) -> Result> { - let mut txn = self.storage.txn()?; - txn.all_tasks() - } - - /// Get the UUIDs of all tasks - pub fn all_task_uuids(&mut self) -> Result> { - let mut txn = self.storage.txn()?; - txn.all_task_uuids() - } - - /// Get the working set - pub fn working_set(&mut self) -> Result>> { - let mut txn = self.storage.txn()?; - txn.get_working_set() - } - - /// Get a single task, by uuid. - pub fn get_task(&mut self, uuid: Uuid) -> Result> { - let mut txn = self.storage.txn()?; - txn.get_task(uuid) - } - - /// Rebuild the working set using a function to identify tasks that should be in the set. This - /// renumbers the existing working-set tasks to eliminate gaps, and also adds any tasks that - /// are not already in the working set but should be. The rebuild occurs in a single - /// trasnsaction against the storage backend. - pub fn rebuild_working_set(&mut self, in_working_set: F, renumber: bool) -> Result<()> - where - F: Fn(&TaskMap) -> bool, - { - working_set::rebuild(self.storage.txn()?.as_mut(), in_working_set, renumber) - } - - /// Add the given uuid to the working set and return its index; if it is already in the working - /// set, its index is returned. This does *not* renumber any existing tasks. - pub fn add_to_working_set(&mut self, uuid: Uuid) -> Result { - let mut txn = self.storage.txn()?; - // search for an existing entry for this task.. - for (i, elt) in txn.get_working_set()?.iter().enumerate() { - if *elt == Some(uuid) { - // (note that this drops the transaction with no changes made) - return Ok(i); - } - } - // and if not found, add one - let i = txn.add_to_working_set(uuid)?; - txn.commit()?; - Ok(i) - } - - /// Sync to the given server, pulling remote changes and pushing local changes. - /// - /// If `avoid_snapshots` is true, the sync operations produces a snapshot only when the server - /// indicate it is urgent (snapshot urgency "high"). This allows time for other replicas to - /// create a snapshot before this one does. - /// - /// Set this to true on systems more constrained in CPU, memory, or bandwidth than a typical desktop - /// system - pub fn sync(&mut self, server: &mut Box, avoid_snapshots: bool) -> Result<()> { - let mut txn = self.storage.txn()?; - sync::sync(server, txn.as_mut(), avoid_snapshots) - } - - /// Return undo local operations until the most recent UndoPoint, returning an empty Vec if there are no - /// local operations to undo. - pub fn get_undo_ops(&mut self) -> Result> { - let mut txn = self.storage.txn()?; - undo::get_undo_ops(txn.as_mut()) - } - - /// Undo local operations in storage, returning a boolean indicating success. - pub fn commit_undo_ops(&mut self, undo_ops: Vec) -> Result { - let mut txn = self.storage.txn()?; - undo::commit_undo_ops(txn.as_mut(), undo_ops) - } - - /// Get the number of un-synchronized operations in storage, excluding undo - /// operations. - pub fn num_operations(&mut self) -> Result { - let mut txn = self.storage.txn().unwrap(); - Ok(txn - .operations()? - .iter() - .filter(|o| !o.is_undo_point()) - .count()) - } - - /// Get the number of (un-synchronized) undo points in storage. - pub fn num_undo_points(&mut self) -> Result { - let mut txn = self.storage.txn().unwrap(); - Ok(txn - .operations()? - .iter() - .filter(|o| o.is_undo_point()) - .count()) - } - - // functions for supporting tests - - #[cfg(test)] - pub(crate) fn sorted_tasks(&mut self) -> Vec<(Uuid, Vec<(String, String)>)> { - let mut res: Vec<(Uuid, Vec<(String, String)>)> = self - .all_tasks() - .unwrap() - .iter() - .map(|(u, t)| { - let mut t = t - .iter() - .map(|(p, v)| (p.clone(), v.clone())) - .collect::>(); - t.sort(); - (*u, t) - }) - .collect(); - res.sort(); - res - } - - #[cfg(test)] - pub(crate) fn operations(&mut self) -> Vec { - let mut txn = self.storage.txn().unwrap(); - txn.operations().unwrap().to_vec() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::server::test::TestServer; - use crate::storage::{InMemoryStorage, ReplicaOp}; - use chrono::Utc; - use pretty_assertions::assert_eq; - use proptest::prelude::*; - use uuid::Uuid; - - #[test] - fn test_apply() { - // this verifies that the operation is both applied and included in the list of - // operations; more detailed tests are in the `apply` module. - let mut db = TaskDb::new_inmemory(); - let uuid = Uuid::new_v4(); - let op = SyncOp::Create { uuid }; - db.apply(op).unwrap(); - - assert_eq!(db.sorted_tasks(), vec![(uuid, vec![]),]); - assert_eq!(db.operations(), vec![ReplicaOp::Create { uuid }]); - } - - #[test] - fn test_add_undo_point() { - let mut db = TaskDb::new_inmemory(); - db.add_undo_point().unwrap(); - assert_eq!(db.operations(), vec![ReplicaOp::UndoPoint]); - } - - #[test] - fn test_num_operations() { - let mut db = TaskDb::new_inmemory(); - db.apply(SyncOp::Create { - uuid: Uuid::new_v4(), - }) - .unwrap(); - db.add_undo_point().unwrap(); - db.apply(SyncOp::Create { - uuid: Uuid::new_v4(), - }) - .unwrap(); - assert_eq!(db.num_operations().unwrap(), 2); - } - - #[test] - fn test_num_undo_points() { - let mut db = TaskDb::new_inmemory(); - db.add_undo_point().unwrap(); - assert_eq!(db.num_undo_points().unwrap(), 1); - db.add_undo_point().unwrap(); - assert_eq!(db.num_undo_points().unwrap(), 2); - } - - fn newdb() -> TaskDb { - TaskDb::new(Box::new(InMemoryStorage::new())) - } - - #[derive(Debug)] - enum Action { - Op(SyncOp), - Sync, - } - - fn action_sequence_strategy() -> impl Strategy> { - // Create, Update, Delete, or Sync on client 1, 2, .., followed by a round of syncs - "([CUDS][123])*S1S2S3S1S2".prop_map(|seq| { - let uuid = Uuid::parse_str("83a2f9ef-f455-4195-b92e-a54c161eebfc").unwrap(); - seq.as_bytes() - .chunks(2) - .map(|action_on| { - let action = match action_on[0] { - b'C' => Action::Op(SyncOp::Create { uuid }), - b'U' => Action::Op(SyncOp::Update { - uuid, - property: "title".into(), - value: Some("foo".into()), - timestamp: Utc::now(), - }), - b'D' => Action::Op(SyncOp::Delete { uuid }), - b'S' => Action::Sync, - _ => unreachable!(), - }; - let acton = action_on[1] - b'1'; - (action, acton) - }) - .collect::>() - }) - } - - proptest! { - #[test] - // check that various sequences of operations on mulitple db's do not get the db's into an - // incompatible state. The main concern here is that there might be a sequence of create - // and delete operations that results in a task existing in one TaskDb but not existing in - // another. So, the generated sequences focus on a single task UUID. - fn transform_sequences_of_operations(action_sequence in action_sequence_strategy()) { - let mut server: Box = Box::new(TestServer::new()); - let mut dbs = [newdb(), newdb(), newdb()]; - - for (action, db) in action_sequence { - println!("{:?} on db {}", action, db); - - let db = &mut dbs[db as usize]; - match action { - Action::Op(op) => { - if let Err(e) = db.apply(op) { - println!(" {:?} (ignored)", e); - } - }, - Action::Sync => db.sync(&mut server, false).unwrap(), - } - } - - assert_eq!(dbs[0].sorted_tasks(), dbs[0].sorted_tasks()); - assert_eq!(dbs[1].sorted_tasks(), dbs[2].sorted_tasks()); - } - } -} diff --git a/taskchampion/taskchampion/src/taskdb/snapshot.rs b/taskchampion/taskchampion/src/taskdb/snapshot.rs deleted file mode 100644 index 3bff2eb2a..000000000 --- a/taskchampion/taskchampion/src/taskdb/snapshot.rs +++ /dev/null @@ -1,181 +0,0 @@ -use crate::errors::{Error, Result}; -use crate::storage::{StorageTxn, TaskMap, VersionId}; -use flate2::{read::ZlibDecoder, write::ZlibEncoder, Compression}; -use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; -use serde::ser::{Serialize, SerializeMap, Serializer}; -use std::fmt; -use uuid::Uuid; - -/// A newtype to wrap the result of [`crate::storage::StorageTxn::all_tasks`] -pub(super) struct SnapshotTasks(Vec<(Uuid, TaskMap)>); - -impl Serialize for SnapshotTasks { - fn serialize(&self, serializer: S) -> std::result::Result - where - S: Serializer, - { - let mut map = serializer.serialize_map(Some(self.0.len()))?; - for (k, v) in &self.0 { - map.serialize_entry(k, v)?; - } - map.end() - } -} - -struct TaskDbVisitor; - -impl<'de> Visitor<'de> for TaskDbVisitor { - type Value = SnapshotTasks; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a map representing a task snapshot") - } - - fn visit_map(self, mut access: M) -> std::result::Result - where - M: MapAccess<'de>, - { - let mut map = SnapshotTasks(Vec::with_capacity(access.size_hint().unwrap_or(0))); - - while let Some((key, value)) = access.next_entry()? { - map.0.push((key, value)); - } - - Ok(map) - } -} - -impl<'de> Deserialize<'de> for SnapshotTasks { - fn deserialize(deserializer: D) -> std::result::Result - where - D: Deserializer<'de>, - { - deserializer.deserialize_map(TaskDbVisitor) - } -} - -impl SnapshotTasks { - pub(super) fn encode(&self) -> Result> { - let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); - serde_json::to_writer(&mut encoder, &self)?; - Ok(encoder.finish()?) - } - - pub(super) fn decode(snapshot: &[u8]) -> Result { - let decoder = ZlibDecoder::new(snapshot); - Ok(serde_json::from_reader(decoder)?) - } - - pub(super) fn into_inner(self) -> Vec<(Uuid, TaskMap)> { - self.0 - } -} - -/// Generate a snapshot (compressed, unencrypted) for the current state of the taskdb in the given -/// storage. -pub(super) fn make_snapshot(txn: &mut dyn StorageTxn) -> Result> { - let all_tasks = SnapshotTasks(txn.all_tasks()?); - all_tasks.encode() -} - -/// Apply the given snapshot (compressed, unencrypted) to the taskdb's storage. -pub(super) fn apply_snapshot( - txn: &mut dyn StorageTxn, - version: VersionId, - snapshot: &[u8], -) -> Result<()> { - let all_tasks = SnapshotTasks::decode(snapshot)?; - - // double-check emptiness - if !txn.is_empty()? { - return Err(Error::Database(String::from( - "Cannot apply snapshot to a non-empty task database", - ))); - } - - for (uuid, task) in all_tasks.into_inner().drain(..) { - txn.set_task(uuid, task)?; - } - txn.set_base_version(version)?; - - Ok(()) -} - -#[cfg(test)] -mod test { - use super::*; - use crate::storage::{InMemoryStorage, Storage, TaskMap}; - use pretty_assertions::assert_eq; - - #[test] - fn test_serialize_empty() -> Result<()> { - let empty = SnapshotTasks(vec![]); - assert_eq!(serde_json::to_vec(&empty)?, b"{}".to_owned()); - Ok(()) - } - - #[test] - fn test_serialize_tasks() -> Result<()> { - let u = Uuid::new_v4(); - let m: TaskMap = vec![("description".to_owned(), "my task".to_owned())] - .drain(..) - .collect(); - let all_tasks = SnapshotTasks(vec![(u, m)]); - assert_eq!( - serde_json::to_vec(&all_tasks)?, - format!("{{\"{}\":{{\"description\":\"my task\"}}}}", u).into_bytes(), - ); - Ok(()) - } - - #[test] - fn test_round_trip() -> Result<()> { - let mut storage = InMemoryStorage::new(); - let version = Uuid::new_v4(); - - let task1 = ( - Uuid::new_v4(), - vec![("description".to_owned(), "one".to_owned())] - .drain(..) - .collect::(), - ); - let task2 = ( - Uuid::new_v4(), - vec![("description".to_owned(), "two".to_owned())] - .drain(..) - .collect::(), - ); - - { - let mut txn = storage.txn()?; - txn.set_task(task1.0, task1.1.clone())?; - txn.set_task(task2.0, task2.1.clone())?; - txn.commit()?; - } - - let snap = { - let mut txn = storage.txn()?; - make_snapshot(txn.as_mut())? - }; - - // apply that snapshot to a fresh bit of fake - let mut storage = InMemoryStorage::new(); - { - let mut txn = storage.txn()?; - apply_snapshot(txn.as_mut(), version, &snap)?; - txn.commit()? - } - - { - let mut txn = storage.txn()?; - assert_eq!(txn.get_task(task1.0)?, Some(task1.1)); - assert_eq!(txn.get_task(task2.0)?, Some(task2.1)); - assert_eq!(txn.all_tasks()?.len(), 2); - assert_eq!(txn.base_version()?, version); - assert_eq!(txn.operations()?.len(), 0); - assert_eq!(txn.get_working_set()?.len(), 1); - } - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/taskdb/sync.rs b/taskchampion/taskchampion/src/taskdb/sync.rs deleted file mode 100644 index 95e2938c4..000000000 --- a/taskchampion/taskchampion/src/taskdb/sync.rs +++ /dev/null @@ -1,386 +0,0 @@ -use super::{apply, snapshot}; -use crate::errors::Result; -use crate::server::{AddVersionResult, GetVersionResult, Server, SnapshotUrgency, SyncOp}; -use crate::storage::StorageTxn; -use crate::Error; -use log::{info, trace, warn}; -use serde::{Deserialize, Serialize}; -use std::str; - -#[derive(Serialize, Deserialize, Debug)] -struct Version { - operations: Vec, -} - -/// Sync to the given server, pulling remote changes and pushing local changes. -pub(super) fn sync( - server: &mut Box, - txn: &mut dyn StorageTxn, - avoid_snapshots: bool, -) -> Result<()> { - // if this taskdb is entirely empty, then start by getting and applying a snapshot - if txn.is_empty()? { - trace!("storage is empty; attempting to apply a snapshot"); - if let Some((version, snap)) = server.get_snapshot()? { - snapshot::apply_snapshot(txn, version, snap.as_ref())?; - trace!("applied snapshot for version {}", version); - } - } - - // retry synchronizing until the server accepts our version (this allows for races between - // replicas trying to sync to the same server). If the server insists on the same base - // version twice, then we have diverged. - let mut requested_parent_version_id = None; - loop { - trace!("beginning sync outer loop"); - let mut base_version_id = txn.base_version()?; - - let mut local_ops: Vec = txn - .operations()? - .drain(..) - .filter_map(|op| op.into_sync()) - .collect(); - - // first pull changes and "rebase" on top of them - loop { - trace!("beginning sync inner loop"); - if let GetVersionResult::Version { - version_id, - history_segment, - .. - } = server.get_child_version(base_version_id)? - { - let version_str = str::from_utf8(&history_segment).unwrap(); - let version: Version = serde_json::from_str(version_str).unwrap(); - - // apply this verison and update base_version in storage - info!("applying version {:?} from server", version_id); - apply_version(txn, &mut local_ops, version)?; - txn.set_base_version(version_id)?; - base_version_id = version_id; - } else { - info!("no child versions of {:?}", base_version_id); - // at the moment, no more child versions, so we can try adding our own - break; - } - } - - if local_ops.is_empty() { - info!("no changes to push to server"); - // nothing to sync back to the server.. - break; - } - - trace!("sending {} operations to the server", local_ops.len()); - - // now make a version of our local changes and push those - let new_version = Version { - operations: local_ops, - }; - let history_segment = serde_json::to_string(&new_version).unwrap().into(); - info!("sending new version to server"); - let (res, snapshot_urgency) = server.add_version(base_version_id, history_segment)?; - match res { - AddVersionResult::Ok(new_version_id) => { - info!("version {:?} received by server", new_version_id); - txn.set_base_version(new_version_id)?; - - // make a snapshot if the server indicates it is urgent enough - let base_urgency = if avoid_snapshots { - SnapshotUrgency::High - } else { - SnapshotUrgency::Low - }; - if snapshot_urgency >= base_urgency { - let snapshot = snapshot::make_snapshot(txn)?; - server.add_snapshot(new_version_id, snapshot)?; - } - - break; - } - AddVersionResult::ExpectedParentVersion(parent_version_id) => { - info!( - "new version rejected; must be based on {:?}", - parent_version_id - ); - if let Some(requested) = requested_parent_version_id { - if parent_version_id == requested { - return Err(Error::OutOfSync); - } - } - requested_parent_version_id = Some(parent_version_id); - } - } - } - - txn.set_operations(vec![])?; - txn.commit()?; - Ok(()) -} - -fn apply_version( - txn: &mut dyn StorageTxn, - local_ops: &mut Vec, - mut version: Version, -) -> Result<()> { - // The situation here is that the server has already applied all server operations, and we - // have already applied all local operations, so states have diverged by several - // operations. We need to figure out what operations to apply locally and on the server in - // order to return to the same state. - // - // Operational transforms provide this on an operation-by-operation basis. To break this - // down, we treat each server operation individually, in order. For each such operation, - // we start in this state: - // - // - // base state-* - // / \-server op - // * * - // local / \ / - // ops * * - // / \ / new - // * * local - // local / \ / ops - // state-* * - // new-\ / - // server op *-new local state - // - // This is slightly complicated by the fact that the transform function can return None, - // indicating no operation is required. If this happens for a local op, we can just omit - // it. If it happens for server op, then we must copy the remaining local ops. - for server_op in version.operations.drain(..) { - trace!( - "rebasing local operations onto server operation {:?}", - server_op - ); - let mut new_local_ops = Vec::with_capacity(local_ops.len()); - let mut svr_op = Some(server_op); - for local_op in local_ops.drain(..) { - if let Some(o) = svr_op { - let (new_server_op, new_local_op) = SyncOp::transform(o, local_op.clone()); - trace!("local operation {:?} -> {:?}", local_op, new_local_op); - svr_op = new_server_op; - if let Some(o) = new_local_op { - new_local_ops.push(o); - } - } else { - trace!( - "local operation {:?} unchanged (server operation consumed)", - local_op - ); - new_local_ops.push(local_op); - } - } - if let Some(o) = svr_op { - if let Err(e) = apply::apply_op(txn, &o) { - warn!("Invalid operation when syncing: {} (ignored)", e); - } - } - *local_ops = new_local_ops; - } - Ok(()) -} - -#[cfg(test)] -mod test { - use super::*; - use crate::server::{test::TestServer, SyncOp}; - use crate::storage::InMemoryStorage; - use crate::taskdb::{snapshot::SnapshotTasks, TaskDb}; - use chrono::Utc; - use pretty_assertions::assert_eq; - use uuid::Uuid; - - fn newdb() -> TaskDb { - TaskDb::new(Box::new(InMemoryStorage::new())) - } - - #[test] - fn test_sync() -> Result<()> { - let mut server: Box = TestServer::new().server(); - - let mut db1 = newdb(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - - let mut db2 = newdb(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - - // make some changes in parallel to db1 and db2.. - let uuid1 = Uuid::new_v4(); - db1.apply(SyncOp::Create { uuid: uuid1 }).unwrap(); - db1.apply(SyncOp::Update { - uuid: uuid1, - property: "title".into(), - value: Some("my first task".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - let uuid2 = Uuid::new_v4(); - db2.apply(SyncOp::Create { uuid: uuid2 }).unwrap(); - db2.apply(SyncOp::Update { - uuid: uuid2, - property: "title".into(), - value: Some("my second task".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - // and synchronize those around - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - - // now make updates to the same task on both sides - db1.apply(SyncOp::Update { - uuid: uuid2, - property: "priority".into(), - value: Some("H".into()), - timestamp: Utc::now(), - }) - .unwrap(); - db2.apply(SyncOp::Update { - uuid: uuid2, - property: "project".into(), - value: Some("personal".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - // and synchronize those around - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - - Ok(()) - } - - #[test] - fn test_sync_create_delete() -> Result<()> { - let mut server: Box = TestServer::new().server(); - - let mut db1 = newdb(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - - let mut db2 = newdb(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - - // create and update a task.. - let uuid = Uuid::new_v4(); - db1.apply(SyncOp::Create { uuid }).unwrap(); - db1.apply(SyncOp::Update { - uuid, - property: "title".into(), - value: Some("my first task".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - // and synchronize those around - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - - // delete and re-create the task on db1 - db1.apply(SyncOp::Delete { uuid }).unwrap(); - db1.apply(SyncOp::Create { uuid }).unwrap(); - db1.apply(SyncOp::Update { - uuid, - property: "title".into(), - value: Some("my second task".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - // and on db2, update a property of the task - db2.apply(SyncOp::Update { - uuid, - property: "project".into(), - value: Some("personal".into()), - timestamp: Utc::now(), - }) - .unwrap(); - - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db2.storage.txn()?.as_mut(), false).unwrap(); - sync(&mut server, db1.storage.txn()?.as_mut(), false).unwrap(); - assert_eq!(db1.sorted_tasks(), db2.sorted_tasks()); - - Ok(()) - } - - #[test] - fn test_sync_add_snapshot_start_with_snapshot() -> Result<()> { - let mut test_server = TestServer::new(); - - let mut server: Box = test_server.server(); - let mut db1 = newdb(); - - let uuid = Uuid::new_v4(); - db1.apply(SyncOp::Create { uuid })?; - db1.apply(SyncOp::Update { - uuid, - property: "title".into(), - value: Some("my first task".into()), - timestamp: Utc::now(), - })?; - - test_server.set_snapshot_urgency(SnapshotUrgency::High); - sync(&mut server, db1.storage.txn()?.as_mut(), false)?; - - // assert that a snapshot was added - let base_version = db1.storage.txn()?.base_version()?; - let (v, s) = test_server - .snapshot() - .ok_or_else(|| anyhow::anyhow!("no snapshot"))?; - assert_eq!(v, base_version); - - let tasks = SnapshotTasks::decode(&s)?.into_inner(); - assert_eq!(tasks[0].0, uuid); - - // update the taskdb and sync again - db1.apply(SyncOp::Update { - uuid, - property: "title".into(), - value: Some("my first task, updated".into()), - timestamp: Utc::now(), - })?; - sync(&mut server, db1.storage.txn()?.as_mut(), false)?; - - // delete the first version, so that db2 *must* initialize from - // the snapshot - test_server.delete_version(Uuid::nil()); - - // sync to a new DB and check that we got the expected results - let mut db2 = newdb(); - sync(&mut server, db2.storage.txn()?.as_mut(), false)?; - - let task = db2.get_task(uuid)?.unwrap(); - assert_eq!(task.get("title").unwrap(), "my first task, updated"); - - Ok(()) - } - - #[test] - fn test_sync_avoids_snapshot() -> Result<()> { - let test_server = TestServer::new(); - - let mut server: Box = test_server.server(); - let mut db1 = newdb(); - - let uuid = Uuid::new_v4(); - db1.apply(SyncOp::Create { uuid }).unwrap(); - - test_server.set_snapshot_urgency(SnapshotUrgency::Low); - sync(&mut server, db1.storage.txn()?.as_mut(), true).unwrap(); - - // assert that a snapshot was not added, because we indicated - // we wanted to avoid snapshots and it was only low urgency - assert_eq!(test_server.snapshot(), None); - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/taskdb/undo.rs b/taskchampion/taskchampion/src/taskdb/undo.rs deleted file mode 100644 index c193d96bb..000000000 --- a/taskchampion/taskchampion/src/taskdb/undo.rs +++ /dev/null @@ -1,154 +0,0 @@ -use super::apply; -use crate::errors::Result; -use crate::storage::{ReplicaOp, StorageTxn}; -use log::{debug, info, trace}; - -/// Local operations until the most recent UndoPoint. -pub fn get_undo_ops(txn: &mut dyn StorageTxn) -> Result> { - let mut local_ops = txn.operations().unwrap(); - let mut undo_ops: Vec = Vec::new(); - - while let Some(op) = local_ops.pop() { - if op == ReplicaOp::UndoPoint { - break; - } - undo_ops.push(op); - } - - Ok(undo_ops) -} - -/// Commit operations to storage, returning a boolean indicating success. -pub fn commit_undo_ops(txn: &mut dyn StorageTxn, mut undo_ops: Vec) -> Result { - let mut applied = false; - let mut local_ops = txn.operations().unwrap(); - - // Add UndoPoint to undo_ops unless this undo will empty the operations database, in which case - // there is no UndoPoint. - if local_ops.len() > undo_ops.len() { - undo_ops.push(ReplicaOp::UndoPoint); - } - - // Drop undo_ops iff they're the latest operations. - // TODO Support concurrent undo by adding the reverse of undo_ops rather than popping from operations. - let old_len = local_ops.len(); - let undo_len = undo_ops.len(); - let new_len = old_len - undo_len; - let local_undo_ops = &local_ops[new_len..old_len]; - undo_ops.reverse(); - if local_undo_ops != undo_ops { - info!("Undo failed: concurrent changes to the database occurred."); - debug!( - "local_undo_ops={:#?}\nundo_ops={:#?}", - local_undo_ops, undo_ops - ); - return Ok(applied); - } - undo_ops.reverse(); - local_ops.truncate(new_len); - - for op in undo_ops { - debug!("Reversing operation {:?}", op); - let rev_ops = op.reverse_ops(); - for op in rev_ops { - trace!("Applying reversed operation {:?}", op); - apply::apply_op(txn, &op)?; - applied = true; - } - } - - if undo_len != 0 { - txn.set_operations(local_ops)?; - txn.commit()?; - } - - Ok(applied) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::server::SyncOp; - use crate::taskdb::TaskDb; - use chrono::Utc; - use pretty_assertions::assert_eq; - use uuid::Uuid; - - #[test] - fn test_apply_create() -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - let timestamp = Utc::now(); - - // apply a few ops, capture the DB state, make an undo point, and then apply a few more - // ops. - db.apply(SyncOp::Create { uuid: uuid1 })?; - db.apply(SyncOp::Update { - uuid: uuid1, - property: "prop".into(), - value: Some("v1".into()), - timestamp, - })?; - db.apply(SyncOp::Create { uuid: uuid2 })?; - db.apply(SyncOp::Update { - uuid: uuid2, - property: "prop".into(), - value: Some("v2".into()), - timestamp, - })?; - db.apply(SyncOp::Update { - uuid: uuid2, - property: "prop2".into(), - value: Some("v3".into()), - timestamp, - })?; - - let db_state = db.sorted_tasks(); - - db.add_undo_point()?; - db.apply(SyncOp::Delete { uuid: uuid1 })?; - db.apply(SyncOp::Update { - uuid: uuid2, - property: "prop".into(), - value: None, - timestamp, - })?; - db.apply(SyncOp::Update { - uuid: uuid2, - property: "prop2".into(), - value: Some("new-value".into()), - timestamp, - })?; - - assert_eq!(db.operations().len(), 9, "{:#?}", db.operations()); - - let undo_ops = get_undo_ops(db.storage.txn()?.as_mut())?; - assert_eq!(undo_ops.len(), 3, "{:#?}", undo_ops); - - assert!(commit_undo_ops(db.storage.txn()?.as_mut(), undo_ops)?); - - // Note that we've subtracted the length of undo_ops plus one for the UndoPoint. - assert_eq!(db.operations().len(), 5, "{:#?}", db.operations()); - assert_eq!(db.sorted_tasks(), db_state, "{:#?}", db.sorted_tasks()); - - // Note that the number of undo operations is equal to the number of operations in the - // database here because there are no UndoPoints. - let undo_ops = get_undo_ops(db.storage.txn()?.as_mut())?; - assert_eq!(undo_ops.len(), 5, "{:#?}", undo_ops); - - assert!(commit_undo_ops(db.storage.txn()?.as_mut(), undo_ops)?); - - // empty db - assert_eq!(db.operations().len(), 0, "{:#?}", db.operations()); - assert_eq!(db.sorted_tasks(), vec![], "{:#?}", db.sorted_tasks()); - - let undo_ops = get_undo_ops(db.storage.txn()?.as_mut())?; - assert_eq!(undo_ops.len(), 0, "{:#?}", undo_ops); - - // nothing left to undo, so commit_undo_ops() returns false - assert!(!commit_undo_ops(db.storage.txn()?.as_mut(), undo_ops)?); - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/taskdb/working_set.rs b/taskchampion/taskchampion/src/taskdb/working_set.rs deleted file mode 100644 index c79e488e9..000000000 --- a/taskchampion/taskchampion/src/taskdb/working_set.rs +++ /dev/null @@ -1,152 +0,0 @@ -use crate::errors::Result; -use crate::storage::{StorageTxn, TaskMap}; -use std::collections::HashSet; - -/// Rebuild the working set using a function to identify tasks that should be in the set. This -/// renumbers the existing working-set tasks to eliminate gaps, and also adds any tasks that -/// are not already in the working set but should be. The rebuild occurs in a single -/// trasnsaction against the storage backend. -pub fn rebuild(txn: &mut dyn StorageTxn, in_working_set: F, renumber: bool) -> Result<()> -where - F: Fn(&TaskMap) -> bool, -{ - let mut new_ws = vec![None]; // index 0 is always None - let mut seen = HashSet::new(); - - // The goal here is for existing working-set items to be "compressed' down to index 1, so - // we begin by scanning the current working set and inserting any tasks that should still - // be in the set into new_ws, implicitly dropping any tasks that are no longer in the - // working set. - for elt in txn.get_working_set()?.drain(1..) { - if let Some(uuid) = elt { - if let Some(task) = txn.get_task(uuid)? { - if in_working_set(&task) { - new_ws.push(Some(uuid)); - seen.insert(uuid); - continue; - } - } - } - - // if we are not renumbering, then insert a blank working-set entry here - if !renumber { - new_ws.push(None); - } - } - - // if renumbering, clear the working set and re-add - if renumber { - txn.clear_working_set()?; - for elt in new_ws.drain(1..new_ws.len()).flatten() { - txn.add_to_working_set(elt)?; - } - } else { - // ..otherwise, just clear the None items determined above from the working set - for (i, elt) in new_ws.iter().enumerate().skip(1) { - if elt.is_none() { - txn.set_working_set_item(i, None)?; - } - } - } - - // Now go hunting for tasks that should be in this list but are not, adding them at the - // end of the list, whether renumbering or not - for (uuid, task) in txn.all_tasks()? { - if !seen.contains(&uuid) && in_working_set(&task) { - txn.add_to_working_set(uuid)?; - } - } - - txn.commit()?; - Ok(()) -} - -#[cfg(test)] -mod test { - use super::*; - use crate::server::SyncOp; - use crate::taskdb::TaskDb; - use chrono::Utc; - use uuid::Uuid; - - #[test] - fn rebuild_working_set_renumber() -> Result<()> { - rebuild_working_set(true) - } - - #[test] - fn rebuild_working_set_no_renumber() -> Result<()> { - rebuild_working_set(false) - } - - fn rebuild_working_set(renumber: bool) -> Result<()> { - let mut db = TaskDb::new_inmemory(); - let mut uuids = vec![]; - uuids.push(Uuid::new_v4()); - println!("uuids[0]: {:?} - pending, not in working set", uuids[0]); - uuids.push(Uuid::new_v4()); - println!("uuids[1]: {:?} - pending, in working set", uuids[1]); - uuids.push(Uuid::new_v4()); - println!("uuids[2]: {:?} - not pending, not in working set", uuids[2]); - uuids.push(Uuid::new_v4()); - println!("uuids[3]: {:?} - not pending, in working set", uuids[3]); - uuids.push(Uuid::new_v4()); - println!("uuids[4]: {:?} - pending, in working set", uuids[4]); - - // add everything to the TaskDb - for uuid in &uuids { - db.apply(SyncOp::Create { uuid: *uuid })?; - } - for i in &[0usize, 1, 4] { - db.apply(SyncOp::Update { - uuid: uuids[*i], - property: String::from("status"), - value: Some("pending".into()), - timestamp: Utc::now(), - })?; - } - - // set the existing working_set as we want it - { - let mut txn = db.storage.txn()?; - txn.clear_working_set()?; - - for i in &[1usize, 3, 4] { - txn.add_to_working_set(uuids[*i])?; - } - - txn.commit()?; - } - - assert_eq!( - db.working_set()?, - vec![None, Some(uuids[1]), Some(uuids[3]), Some(uuids[4])] - ); - - rebuild( - db.storage.txn()?.as_mut(), - |t| { - if let Some(status) = t.get("status") { - status == "pending" - } else { - false - } - }, - renumber, - )?; - - let exp = if renumber { - // uuids[1] and uuids[4] are already in the working set, so are compressed - // to the top, and then uuids[0] is added. - vec![None, Some(uuids[1]), Some(uuids[4]), Some(uuids[0])] - } else { - // uuids[1] and uuids[4] are already in the working set, at indexes 1 and 3, - // and then uuids[0] is added. - vec![None, Some(uuids[1]), None, Some(uuids[4]), Some(uuids[0])] - }; - - assert_eq!(db.working_set()?, exp); - - Ok(()) - } -} diff --git a/taskchampion/taskchampion/src/utils.rs b/taskchampion/taskchampion/src/utils.rs deleted file mode 100644 index 7eb0885dc..000000000 --- a/taskchampion/taskchampion/src/utils.rs +++ /dev/null @@ -1,61 +0,0 @@ -use std::convert::TryInto; -use uuid::Uuid; - -/// A representation of a UUID as a key. This is just a newtype wrapping the 128-bit packed form -/// of a UUID. -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] -pub(crate) struct Key(uuid::Bytes); - -impl From<&[u8]> for Key { - fn from(bytes: &[u8]) -> Key { - Key(bytes.try_into().expect("expected 16 bytes")) - } -} - -impl From<&Uuid> for Key { - fn from(uuid: &Uuid) -> Key { - let key = Key(*uuid.as_bytes()); - key - } -} - -impl From for Key { - fn from(uuid: Uuid) -> Key { - let key = Key(*uuid.as_bytes()); - key - } -} - -impl From for Uuid { - fn from(key: Key) -> Uuid { - Uuid::from_bytes(key.0) - } -} - -impl AsRef<[u8]> for Key { - fn as_ref(&self) -> &[u8] { - &self.0[..] - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn test_from_bytes() { - let k: Key = (&[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16][..]).into(); - let u: Uuid = k.into(); - assert_eq!( - u, - Uuid::parse_str("01020304-0506-0708-090a-0b0c0d0e0f10").unwrap() - ); - } - - #[test] - #[should_panic] - fn test_from_bytes_bad_len() { - let _: Key = (&[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11][..]).into(); - } -} diff --git a/taskchampion/taskchampion/src/workingset.rs b/taskchampion/taskchampion/src/workingset.rs deleted file mode 100644 index 15a509753..000000000 --- a/taskchampion/taskchampion/src/workingset.rs +++ /dev/null @@ -1,154 +0,0 @@ -use std::collections::HashMap; -use uuid::Uuid; - -/// A WorkingSet represents a snapshot of the working set from a replica. -/// -/// A replica's working set is a mapping from small integers to task uuids for all pending tasks. -/// The small integers are meant to be stable, easily-typed identifiers for users to interact with -/// important tasks. -/// -/// IMPORTANT: the content of the working set may change at any time that a DB transaction is not -/// in progress, and the data in this type will not be updated automatically. It is up to the -/// caller to decide how long to keep this value, and how much to trust the accuracy of its -/// contents. In practice, the answers are usually "a few milliseconds" and treating unexpected -/// results as non-fatal. -pub struct WorkingSet { - by_index: Vec>, - by_uuid: HashMap, -} - -impl WorkingSet { - /// Create a new WorkingSet. Typically this is acquired via `replica.working_set()` - pub(crate) fn new(by_index: Vec>) -> Self { - let mut by_uuid = HashMap::new(); - - // working sets are 1-indexed, so element 0 should always be None - assert!(by_index.is_empty() || by_index[0].is_none()); - - for (index, uuid) in by_index.iter().enumerate() { - if let Some(uuid) = uuid { - by_uuid.insert(*uuid, index); - } - } - Self { by_index, by_uuid } - } - - /// Get the "length" of the working set: the total number of uuids in the set. - pub fn len(&self) -> usize { - self.by_index.iter().filter(|e| e.is_some()).count() - } - - /// Get the largest index in the working set, or zero if the set is empty. - pub fn largest_index(&self) -> usize { - self.by_index.len().saturating_sub(1) - } - - /// True if the length is zero - pub fn is_empty(&self) -> bool { - self.by_index.iter().all(|e| e.is_none()) - } - - /// Get the uuid with the given index, if any exists. - pub fn by_index(&self, index: usize) -> Option { - if let Some(Some(uuid)) = self.by_index.get(index) { - Some(*uuid) - } else { - None - } - } - - /// Get the index for the given uuid, if any - pub fn by_uuid(&self, uuid: Uuid) -> Option { - self.by_uuid.get(&uuid).copied() - } - - /// Iterate over pairs (index, uuid), in order by index. - pub fn iter(&self) -> impl Iterator + '_ { - self.by_index - .iter() - .enumerate() - .filter_map(|(index, uuid)| uuid.as_ref().map(|uuid| (index, *uuid))) - } -} - -#[cfg(test)] -mod test { - use super::*; - use pretty_assertions::assert_eq; - - fn make() -> (Uuid, Uuid, WorkingSet) { - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - ( - uuid1, - uuid2, - WorkingSet::new(vec![None, Some(uuid1), None, Some(uuid2), None]), - ) - } - - #[test] - fn test_new() { - let (_, uuid2, ws) = make(); - assert_eq!(ws.by_index[3], Some(uuid2)); - assert_eq!(ws.by_uuid.get(&uuid2), Some(&3)); - } - - #[test] - fn test_len_and_is_empty() { - let (_, _, ws) = make(); - assert_eq!(ws.len(), 2); - assert_eq!(ws.is_empty(), false); - - let ws = WorkingSet::new(vec![]); - assert_eq!(ws.len(), 0); - assert_eq!(ws.is_empty(), true); - - let ws = WorkingSet::new(vec![None, None, None]); - assert_eq!(ws.len(), 0); - assert_eq!(ws.is_empty(), true); - } - - #[test] - fn test_largest_index() { - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - let ws = WorkingSet::new(vec![]); - assert_eq!(ws.largest_index(), 0); - - let ws = WorkingSet::new(vec![None, Some(uuid1)]); - assert_eq!(ws.largest_index(), 1); - - let ws = WorkingSet::new(vec![None, Some(uuid1), None, Some(uuid2)]); - assert_eq!(ws.largest_index(), 3); - - let ws = WorkingSet::new(vec![None, Some(uuid1), None, Some(uuid2), None]); - assert_eq!(ws.largest_index(), 4); - } - - #[test] - fn test_by_index() { - let (uuid1, uuid2, ws) = make(); - assert_eq!(ws.by_index(0), None); - assert_eq!(ws.by_index(1), Some(uuid1)); - assert_eq!(ws.by_index(2), None); - assert_eq!(ws.by_index(3), Some(uuid2)); - assert_eq!(ws.by_index(4), None); - assert_eq!(ws.by_index(100), None); // past the end of the vector - } - - #[test] - fn test_by_uuid() { - let (uuid1, uuid2, ws) = make(); - let nosuch = Uuid::new_v4(); - assert_eq!(ws.by_uuid(uuid1), Some(1)); - assert_eq!(ws.by_uuid(uuid2), Some(3)); - assert_eq!(ws.by_uuid(nosuch), None); - } - - #[test] - fn test_iter() { - let (uuid1, uuid2, ws) = make(); - assert_eq!(ws.iter().collect::>(), vec![(1, uuid1), (3, uuid2),]); - } -} diff --git a/taskchampion/xtask/src/main.rs b/taskchampion/xtask/src/main.rs deleted file mode 100644 index 446787db6..000000000 --- a/taskchampion/xtask/src/main.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! This executable defines the `cargo xtask` subcommands. -//! -//! At the moment it is very simple, but if this grows more subcommands then -//! it will be sensible to use `clap` or another similar library. - -use regex::Regex; -use std::env; -use std::fs::File; -use std::io::{BufRead, BufReader, Seek, Write}; -use std::path::{Path, PathBuf}; - -/// Tuples of the form (PATH, REGEX) where PATH and REGEX are literals where PATH is a file that -/// conains the Minimum Supported Rust Version and REGEX is the pattern to find the appropriate -/// line in the file. PATH is relative to the `taskchampion/` directory in the repo. -const MSRV_PATH_REGEX: &[(&str, &str)] = &[ - ( - "../.github/workflows/checks.yml", - r#"toolchain: "[0-9.]+*" # MSRV"#, - ), - ("../.github/workflows/rust-tests.yml", r#""[0-9.]+" # MSRV"#), - ( - "taskchampion/src/lib.rs", - r#"Rust version [0-9.]* and higher"#, - ), - ("taskchampion/Cargo.toml", r#"^rust-version = "[0-9.]"#), -]; - -pub fn main() -> anyhow::Result<()> { - let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); - let workspace_dir = manifest_dir.parent().unwrap(); - let arguments: Vec = env::args().collect(); - - if arguments.len() < 2 { - anyhow::bail!("xtask: Valid arguments are: `codegen`, `msrv `"); - } - - match arguments[1].as_str() { - "codegen" => codegen(workspace_dir), - "msrv" => msrv(arguments, workspace_dir), - _ => anyhow::bail!("xtask: unknown xtask"), - } -} - -/// `cargo xtask codegen` -/// -/// This uses ffizz-header to generate `lib/taskchampion.h`. -fn codegen(workspace_dir: &Path) -> anyhow::Result<()> { - let lib_crate_dir = workspace_dir.join("lib"); - let mut file = File::create(lib_crate_dir.join("taskchampion.h")).unwrap(); - write!(&mut file, "{}", ::taskchampion_lib::generate_header()).unwrap(); - - Ok(()) -} - -/// `cargo xtask msrv (X.Y)` -/// -/// This checks and updates the Minimum Supported Rust Version for all files specified in MSRV_PATH_REGEX`. -/// Each line where the regex matches will have all values of the form `#.##` replaced with the given MSRV. -fn msrv(args: Vec, workspace_dir: &Path) -> anyhow::Result<()> { - // check that (X.Y) argument is (mostly) valid: - if args.len() < 3 || !args[2].chars().all(|c| c.is_numeric() || c == '.') { - anyhow::bail!("xtask: Invalid argument format. Xtask msrv argument takes the form \"X.Y(y)\", where XYy are numbers. eg: `cargo run xtask msrv 1.68`"); - } - let version_replacement_string = &args[2]; - - // set regex for replacing version number only within the pattern found within a line - let re_msrv_version = Regex::new(r"([0-9]+(\.|[0-9]+|))+")?; - - // for each file in const paths tuple - for msrv_file in MSRV_PATH_REGEX { - let mut is_pattern_in_file = false; - - let path = workspace_dir.join(msrv_file.0); - let path = Path::new(&path); - if !path.exists() { - anyhow::bail!("xtask: path does not exist {}", &path.display()); - }; - - let mut file = File::options().read(true).write(true).open(path)?; - let reader = BufReader::new(&file); - - // set search string and the replacement string for version number content - let re_msrv_pattern = Regex::new(msrv_file.1)?; - - // for each line in file - let mut file_string = String::new(); - for line in reader.lines() { - let line = &line?; - - // if rust version pattern is found and is different, update it - if let Some(pattern_offset) = re_msrv_pattern.find(line) { - if !pattern_offset.as_str().contains(version_replacement_string) { - file_string += &re_msrv_version.replace(line, version_replacement_string); - - file_string += "\n"; - - is_pattern_in_file = true; - continue; - } - } - - file_string += line; - file_string += "\n"; - } - - // if pattern was found and updated, write to disk - if is_pattern_in_file { - // Set the file length to the file_string length - file.set_len(file_string.len() as u64)?; - - // set the cursor to the beginning of the file and write - file.seek(std::io::SeekFrom::Start(0))?; - file.write_all(file_string.as_bytes())?; - - // notify user this file was updated - println!( - "xtask: Updated MSRV in {}", - re_msrv_version.replace(msrv_file.0, version_replacement_string) - ); - } - } - - Ok(()) -} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 7f7d9d6db..dadca6bc8 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -10,12 +10,11 @@ endif() include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src + ${CMAKE_SOURCE_DIR}/src/tc/lib ${CMAKE_SOURCE_DIR}/src/commands ${CMAKE_SOURCE_DIR}/src/columns ${CMAKE_SOURCE_DIR}/src/libshared/src - ${CMAKE_SOURCE_DIR}/src/taskchampion/lib ${CMAKE_SOURCE_DIR}/test - ${CMAKE_SOURCE_DIR}/taskchampion/lib ${TASK_INCLUDE_DIRS}) set (test_SRCS @@ -203,4 +202,4 @@ endforeach(python_Test) #SET(CMAKE_BUILD_TYPE gcov) #SET(CMAKE_CXX_FLAGS_GCOV "--coverage") #SET(CMAKE_C_FLAGS_GCOV "--coverage") -#SET(CMAKE_EXE_LINKER_FLAGS_GCOV "--coverage") \ No newline at end of file +#SET(CMAKE_EXE_LINKER_FLAGS_GCOV "--coverage") diff --git a/taskchampion/xtask/Cargo.toml b/xtask/Cargo.toml similarity index 60% rename from taskchampion/xtask/Cargo.toml rename to xtask/Cargo.toml index ad3d76837..e21069966 100644 --- a/taskchampion/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -4,6 +4,6 @@ version = "0.4.1" edition = "2021" [dependencies] -anyhow.workspace = true -taskchampion-lib = { path = "../lib" } +anyhow = "1.0" +taskchampion-lib = { path = "../src/tc/lib" } regex = "^1.10.2" diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 000000000..003844ea2 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,35 @@ +//! This executable defines the `cargo xtask` subcommands. +//! +//! At the moment it is very simple, but if this grows more subcommands then +//! it will be sensible to use `clap` or another similar library. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub fn main() -> anyhow::Result<()> { + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); + let workspace_dir = manifest_dir.parent().unwrap(); + let arguments: Vec = env::args().collect(); + + if arguments.len() < 2 { + anyhow::bail!("xtask: Valid arguments are: `codegen`"); + } + + match arguments[1].as_str() { + "codegen" => codegen(workspace_dir), + _ => anyhow::bail!("xtask: unknown xtask"), + } +} + +/// `cargo xtask codegen` +/// +/// This uses ffizz-header to generate `lib/taskchampion.h`. +fn codegen(workspace_dir: &Path) -> anyhow::Result<()> { + let lib_crate_dir = workspace_dir.join("src/tc/lib"); + let mut file = File::create(lib_crate_dir.join("taskchampion.h")).unwrap(); + write!(&mut file, "{}", ::taskchampion_lib::generate_header()).unwrap(); + + Ok(()) +}