From 9fac224219676f1a82a12f2495be80ee2c08ac96 Mon Sep 17 00:00:00 2001 From: Sunshine Date: Sun, 17 Oct 2021 20:03:07 -1000 Subject: [PATCH] rewrite in Rust --- .github/workflows/build_gnu_linux.yml | 22 ++ .github/workflows/build_macos.yml | 22 ++ .github/workflows/build_windows.yml | 22 ++ .github/workflows/cd.yml | 97 ++++++++ .github/workflows/ci.yml | 34 +++ .gitignore | 6 + Cargo.lock | 326 ++++++++++++++++++++++++++ Cargo.toml | 28 +++ Dockerfile | 22 ++ LICENSE | 121 ++++++++++ Makefile | 29 +++ README.md | 101 +++++++- dataurl.sh | 91 ------- dist/run-in-container.sh | 10 + src/lib.rs | 266 +++++++++++++++++++++ src/main.rs | 104 ++++++++ tests/_data_/text-file.txt | 1 + tests/lib/charset.rs | 46 ++++ tests/lib/charset_no_default.rs | 46 ++++ tests/lib/fragment.rs | 61 +++++ tests/lib/media_type.rs | 54 +++++ tests/lib/media_type_no_default.rs | 57 +++++ tests/lib/mod.rs | 8 + tests/lib/new.rs | 18 ++ tests/lib/parse.rs | 134 +++++++++++ tests/lib/to_string.rs | 94 ++++++++ tests/mod.rs | 2 + 27 files changed, 1724 insertions(+), 98 deletions(-) create mode 100644 .github/workflows/build_gnu_linux.yml create mode 100644 .github/workflows/build_macos.yml create mode 100644 .github/workflows/build_windows.yml create mode 100644 .github/workflows/cd.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile delete mode 100755 dataurl.sh create mode 100644 dist/run-in-container.sh create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 tests/_data_/text-file.txt create mode 100644 tests/lib/charset.rs create mode 100644 tests/lib/charset_no_default.rs create mode 100644 tests/lib/fragment.rs create mode 100644 tests/lib/media_type.rs create mode 100644 tests/lib/media_type_no_default.rs create mode 100644 tests/lib/mod.rs create mode 100644 tests/lib/new.rs create mode 100644 tests/lib/parse.rs create mode 100644 tests/lib/to_string.rs create mode 100644 tests/mod.rs diff --git a/.github/workflows/build_gnu_linux.yml b/.github/workflows/build_gnu_linux.yml new file mode 100644 index 0000000..932816a --- /dev/null +++ b/.github/workflows/build_gnu_linux.yml @@ -0,0 +1,22 @@ +name: GNU/Linux + +on: + push: + branches: [ master ] + +jobs: + build: + + strategy: + matrix: + os: + - ubuntu-latest + rust: + - stable + runs-on: ${{ matrix.os }} + + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@v2 + - name: Build + run: cargo build --all --locked --verbose diff --git a/.github/workflows/build_macos.yml b/.github/workflows/build_macos.yml new file mode 100644 index 0000000..aebd501 --- /dev/null +++ b/.github/workflows/build_macos.yml @@ -0,0 +1,22 @@ +name: macOS + +on: + push: + branches: [ master ] + +jobs: + build: + + strategy: + matrix: + os: + - macos-latest + rust: + - stable + runs-on: ${{ matrix.os }} + + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@v2 + - name: Build + run: cargo build --all --locked --verbose diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml new file mode 100644 index 0000000..3515af6 --- /dev/null +++ b/.github/workflows/build_windows.yml @@ -0,0 +1,22 @@ +name: Windows + +on: + push: + branches: [ master ] + +jobs: + build: + + strategy: + matrix: + os: + - windows-latest + rust: + - stable + runs-on: ${{ matrix.os }} + + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@v2 + - name: Build + run: cargo build --all --locked --verbose diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 0000000..3588ab7 --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,97 @@ +# CD GitHub Actions workflow for dataurl + +name: CD + +on: + release: + types: + - created + +jobs: + + windows: + runs-on: windows-2019 + steps: + - run: git config --global core.autocrlf false + - name: Checkout the repository + uses: actions/checkout@v2 + - name: Build the executable + run: cargo build --release + - uses: Shopify/upload-to-release@1.0.0 + with: + name: dataurl.exe + path: target\release\dataurl.exe + repo-token: ${{ secrets.GITHUB_TOKEN }} + + gnu_linux_armhf: + runs-on: ubuntu-18.04 + steps: + - name: Checkout the repository + uses: actions/checkout@v2 + - name: Prepare cross-platform environment + run: | + sudo mkdir /cross-build + sudo touch /etc/apt/sources.list.d/armhf.list + echo "deb [arch=armhf] http://ports.ubuntu.com/ubuntu-ports/ bionic main" | sudo tee -a /etc/apt/sources.list.d/armhf.list + sudo apt-get update + sudo apt-get install -y gcc-arm-linux-gnueabihf libc6-armhf-cross libc6-dev-armhf-cross + sudo apt-get download libssl1.1:armhf libssl-dev:armhf + sudo dpkg -x libssl1.1*.deb /cross-build + sudo dpkg -x libssl-dev*.deb /cross-build + rustup target add arm-unknown-linux-gnueabihf + echo "C_INCLUDE_PATH=/cross-build/usr/include" >> $GITHUB_ENV + echo "OPENSSL_INCLUDE_DIR=/cross-build/usr/include/arm-linux-gnueabihf" >> $GITHUB_ENV + echo "OPENSSL_LIB_DIR=/cross-build/usr/lib/arm-linux-gnueabihf" >> $GITHUB_ENV + echo "PKG_CONFIG_ALLOW_CROSS=1" >> $GITHUB_ENV + echo "RUSTFLAGS=-C linker=arm-linux-gnueabihf-gcc -L/usr/arm-linux-gnueabihf/lib -L/cross-build/usr/lib/arm-linux-gnueabihf -L/cross-build/lib/arm-linux-gnueabihf" >> $GITHUB_ENV + - name: Build the executable + run: cargo build --release --target=arm-unknown-linux-gnueabihf + - name: Attach artifact to the release + uses: Shopify/upload-to-release@1.0.0 + with: + name: dataurl-gnu-linux-armhf + path: target/arm-unknown-linux-gnueabihf/release/dataurl + repo-token: ${{ secrets.GITHUB_TOKEN }} + + gnu_linux_aarch64: + runs-on: ubuntu-18.04 + steps: + - name: Checkout the repository + uses: actions/checkout@v2 + - name: Prepare cross-platform environment + run: | + sudo mkdir /cross-build + sudo touch /etc/apt/sources.list.d/arm64.list + echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports/ bionic main" | sudo tee -a /etc/apt/sources.list.d/arm64.list + sudo apt-get update + sudo apt-get install -y gcc-aarch64-linux-gnu libc6-arm64-cross libc6-dev-arm64-cross + sudo apt-get download libssl1.1:arm64 libssl-dev:arm64 + sudo dpkg -x libssl1.1*.deb /cross-build + sudo dpkg -x libssl-dev*.deb /cross-build + rustup target add aarch64-unknown-linux-gnu + echo "C_INCLUDE_PATH=/cross-build/usr/include" >> $GITHUB_ENV + echo "OPENSSL_INCLUDE_DIR=/cross-build/usr/include/aarch64-linux-gnu" >> $GITHUB_ENV + echo "OPENSSL_LIB_DIR=/cross-build/usr/lib/aarch64-linux-gnu" >> $GITHUB_ENV + echo "PKG_CONFIG_ALLOW_CROSS=1" >> $GITHUB_ENV + echo "RUSTFLAGS=-C linker=aarch64-linux-gnu-gcc -L/usr/aarch64-linux-gnu/lib -L/cross-build/usr/lib/aarch64-linux-gnu" >> $GITHUB_ENV + - name: Build the executable + run: cargo build --release --target=aarch64-unknown-linux-gnu + - name: Attach artifact to the release + uses: Shopify/upload-to-release@1.0.0 + with: + name: dataurl-gnu-linux-aarch64 + path: target/aarch64-unknown-linux-gnu/release/dataurl + repo-token: ${{ secrets.GITHUB_TOKEN }} + + gnu_linux_x86_64: + runs-on: ubuntu-18.04 + steps: + - name: Checkout the repository + uses: actions/checkout@v2 + - name: Build the executable + run: cargo build --release + - uses: Shopify/upload-to-release@1.0.0 + with: + name: dataurl-gnu-linux-x86_64 + path: target/release/dataurl + repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..693612a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +# CI GitHub Actions workflow for dataurl + +name: CI + +on: + pull_request: + branches: [ master ] + +jobs: + build_and_test: + + strategy: + matrix: + os: + - ubuntu-latest + - macos-latest + - windows-latest + rust: + - stable + - beta + - nightly + runs-on: ${{ matrix.os }} + + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@v2 + - name: Build + run: cargo build --all --locked --verbose + - name: Run tests + run: cargo test --all --locked --verbose + - name: Check code formatting + run: | + rustup component add rustfmt + cargo fmt --all -- --check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2e972d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ed25b95 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,326 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "ansi_term" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" +dependencies = [ + "winapi", +] + +[[package]] +name = "assert_cmd" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e996dc7940838b7ef1096b882e29ec30a3149a3a443cdc8dba19ed382eca1fe2" +dependencies = [ + "bstr", + "doc-comment", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "lazy_static", + "memchr", + "regex-automata", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "2.33.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" +dependencies = [ + "ansi_term", + "atty", + "bitflags", + "strsim", + "textwrap", + "unicode-width", + "vec_map", +] + +[[package]] +name = "dataurl" +version = "0.0.1" +dependencies = [ + "assert_cmd", + "base64", + "clap", + "encoding_rs", + "percent-encoding", + "url", +] + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "doc-comment" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" + +[[package]] +name = "either" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" + +[[package]] +name = "encoding_rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a74ea89a0a1b98f6332de42c95baff457ada66d1cb4030f9ff151b2041a1c746" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "form_urlencoded" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" +dependencies = [ + "matches", + "percent-encoding", +] + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "idna" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "itertools" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" +dependencies = [ + "either", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2f96d100e1cf1929e7719b7edb3b90ab5298072638fccd77be9ce942ecdfce" + +[[package]] +name = "matches" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" + +[[package]] +name = "memchr" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" + +[[package]] +name = "predicates" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6ce811d0b2e103743eec01db1c50612221f173084ce2f7941053e94b6bb474" +dependencies = [ + "difflib", + "itertools", + "predicates-core", +] + +[[package]] +name = "predicates-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57e35a3326b75e49aa85f5dc6ec15b41108cf5aee58eabb1f274dd18b73c2451" + +[[package]] +name = "predicates-tree" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338c7be2905b732ae3984a2f40032b5e94fd8f52505b186c7d4d68d193445df7" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" + +[[package]] +name = "strsim" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" + +[[package]] +name = "termtree" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78fbf2dd23e79c28ccfa2472d3e6b3b189866ffef1aeb91f17c2d968b6586378" + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "tinyvec" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83b2a3d4d9091d0abd7eba4dc2710b1718583bd4d8992e2190720ea38f391f7" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "unicode-bidi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a01404663e3db436ed2746d9fefef640d868edae3cceb81c3b8d5732fda678f" + +[[package]] +name = "unicode-normalization" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "url" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" +dependencies = [ + "form_urlencoded", + "idna", + "matches", + "percent-encoding", +] + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b7ac88a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "dataurl" +version = "0.0.1" +authors = [ + "Sunshine ", +] +edition = "2018" +description = "CLI tool and Rust crate for parsing and generating data URLs" +homepage = "https://github.com/Y2Z/dataurl" +repository = "https://github.com/Y2Z/dataurl" +readme = "README.md" +keywords = ["web", "command-line"] +categories = ["base64", "command-line-utilities", "data-url", "web-programming"] +include = [ + "src/*.rs", + "Cargo.toml", +] +license = "CC0-1.0" + +[dependencies] +base64 = "0.13.0" +clap = "2.33.3" +encoding_rs = "0.8.29" +percent-encoding = "2.1.0" +url = "2.2.2" + +[dev-dependencies] +assert_cmd = "2.0.2" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..90dc638 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM ekidd/rust-musl-builder as builder + +RUN curl -L -o dataurl.tar.gz $(curl -s https://api.github.com/repos/y2z/dataurl/releases/latest \ + | grep "tarball_url.*\"," \ + | cut -d '"' -f 4) +RUN tar xfz dataurl.tar.gz \ + && mv Y2Z-dataurl-* dataurl \ + && rm dataurl.tar.gz + +WORKDIR dataurl/ +RUN make install + + +FROM alpine + +RUN apk update && \ + apk add --no-cache openssl && \ + rm -rf "/var/cache/apk/*" + +COPY --from=builder /home/rust/.cargo/bin/dataurl /usr/bin/dataurl +WORKDIR /tmp +ENTRYPOINT ["/usr/bin/dataurl"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5f1caae --- /dev/null +++ b/Makefile @@ -0,0 +1,29 @@ +# Makefile for dataurl + +all: build +.PHONY: all + +build: + @cargo build --locked +.PHONY: build + +test: build + @cargo test --locked + @cargo fmt --all -- --check +.PHONY: test + +lint: + @cargo fmt --all -- +.PHONY: lint + +install: + @cargo install --force --locked --path . +.PHONY: install + +uninstall: + @cargo uninstall +.PHONY: uninstall + +clean: + @cargo clean +.PHONY: clean diff --git a/README.md b/README.md index dc823b7..8e95486 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,100 @@ -# dataurl.sh -CLI tool for converting files to data URLs +[![dataurl build status on GNU/Linux](https://github.com/Y2Z/dataurl/workflows/GNU%2FLinux/badge.svg)](https://github.com/Y2Z/dataurl/actions?query=workflow%3AGNU%2FLinux) +[![dataurl build status on macOS](https://github.com/Y2Z/dataurl/workflows/macOS/badge.svg)](https://github.com/Y2Z/dataurl/actions?query=workflow%3AmacOS) +[![dataurl build status on Windows](https://github.com/Y2Z/dataurl/workflows/Windows/badge.svg)](https://github.com/Y2Z/dataurl/actions?query=workflow%3AWindows) + +# dataurl + +CLI tool and Rust crate for converting files into data URLs and back + + +--------------------------------------------------- -![file transfer](https://imgs.xkcd.com/comics/file_transfer.png) ## Installation - sudo cp -n dataurl.sh /usr/bin/dataurl -## Usage - dataurl -n picture1.jpg picture2.jpg +#### Using [Cargo](https://crates.io/crates/dataurl) +```console +cargo install dataurl +``` + +#### Using [containers](https://www.docker.com/) +```console +docker build -t Y2Z/dataurl . +sudo install -b dist/run-in-container.sh /usr/local/bin/dataurl +``` + +#### From source + +```console +git clone https://github.com/Y2Z/dataurl.git +cd dataurl +make install +``` + +#### Using [pre-built binaries](https://github.com/Y2Z/dataurl/releases) (Windows, ARM-based devices, etc) +Every release contains pre-built binaries for Windows, GNU/Linux, as well as platforms with non-standart CPU architecture. + + +--------------------------------------------------- + + +## Usage (crate) +```rust +use dataurl::DataUrl; + +let data_url: DataUrl = DataUrl::parse("data:,Hello,%20World!")?; + +assert_eq!(data_url.media_type(), "text/plain".to_string()); +assert_eq!(data_url.charset(), "US-ASCII".to_string()); +assert!(!data_url.encoded()); +assert_eq!(String::from_utf8_lossy(data_url.data()), "Hello, World!"); +assert_eq!(data_url.fragment(), None); +assert_eq!(data_url.to_string(), "data:,Hello,%20World!"); +``` + + +--------------------------------------------------- + + +## Usage (CLI) +```console + dataurl -i picture.png +``` +or +```console + dataurl data:text/html,base64;Bz...== > index.html +``` +or +```console + cat file.txt | dataurl -i - + +``` + + +--------------------------------------------------- + + +## Options + - `-b`: Prefer encoding into base64 even when not necessary + - `-c`: Use custom `charset` (automatically sets `-b`) + - `-d`: Decode input, save/output resulting blob + - `-f`: Specify custom `fragment` to append + - `-i`: Specify custom `file` to obtain input from (use `-` for STDIN) + - `-t`: Specify media type for the data URL to be generated with + + +--------------------------------------------------- + + +## References + + - https://datatracker.ietf.org/doc/html/rfc2397 + + +--------------------------------------------------- + ## License -Released into public domain + +To the extent possible under law, the author(s) have dedicated all copyright related and neighboring rights to this software to the public domain worldwide. +This software is distributed without any warranty. diff --git a/dataurl.sh b/dataurl.sh deleted file mode 100755 index cd83dad..0000000 --- a/dataurl.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/bin/sh - -# constants -LIMIT=500000 # 500 KB - -# options -NAMES=false # print filenames -FULL=false # print full paths for filenames -NOBIG=false # abide the file limit - -# counters -COUNT=0 -I=0 - -# process option flags -for ARG in "$@" -do - if [ "$ARG" = "-n" ] || [ "$ARG" = "--names" ]; then - NAMES=true - elif [ "$ARG" = "-f" ] || [ "$ARG" = "--full-paths" ]; then - FULL=true - elif [ "$ARG" = "-l" ] || [ "$ARG" = "--limit" ]; then - NOBIG=true - fi -done - -# count total amount of files to process -for ARG in "$@" -do - # skip non-regular files and option flags - if [ ! -f "$ARG" ]; then - continue - fi - - # increase the total count of files to process - COUNT=$((COUNT+1)) -done - -# main loop -for ARG in "$@" -do - # skip non-regular files and option flags - if [ ! -f "$ARG" ]; then - if [ "$ARG" != "-n" ] && [ "$ARG" != "--names" ] \ - && [ "$ARG" != "-f" ] && [ "$ARG" != "--full-paths" ] \ - && [ "$ARG" != "-l" ] && [ "$ARG" != "--limit" ]; then - (>&2 echo "skipping $ARG: not a regular file.") - # put an extra newline between multiple data URIs - if [ $I -gt 0 ] && [ $I -lt $COUNT ]; then - (>&2 echo "") - fi - fi - continue - fi - - # check the file size - if $NOBIG; then - FILESIZE=$(stat -c%s "$ARG") - if [ $FILESIZE -gt $LIMIT ]; then - (>&2 echo "skipping $ARG: the file is too big.") - # put an extra newline between multiple data URIs - if [ $I -gt 0 ] && [ $I -lt $COUNT ]; then - (>&2 echo "") - fi - continue - fi - fi - - # detect the mime-type - MIMETYPE=$(file -b --mime-type "$ARG") - - # printf the file name/path - if $NAMES; then - if $FULL; then - echo "$ARG:" - else - echo $(basename "$ARG")":" - fi - fi - - # output the data URI for this file - echo "data:$MIMETYPE;base64,$(base64 -w0 "$ARG")" - - # increase the counter - I=$((I+1)) - - # put an extra newline between multiple data URIs - if [ $I -gt 0 ] && [ $I -lt $COUNT ]; then - echo "" - fi -done diff --git a/dist/run-in-container.sh b/dist/run-in-container.sh new file mode 100644 index 0000000..5d660dd --- /dev/null +++ b/dist/run-in-container.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +DOCKER=docker +PROG_NAME=dataurl + +if which podman 2>&1 > /dev/null; then + DOCKER=podman +fi + +$DOCKER run --rm Y2Z/$PROG_NAME "$@" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..f61a9cd --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,266 @@ +use encoding_rs::Encoding; +use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC}; +use std::fmt; +use url::Url; + +pub const DEFAULT_MEDIA_TYPE: &'static str = "text/plain"; +pub const DEFAULT_CHARSET: &'static str = "US-ASCII"; + +pub struct DataUrl { + media_type: Option, // Mime type + charset: Option, // US-ASCII is default, according to the spec + encoded: bool, // Indicates if it's a base64-encoded data URL + data: Vec, // Data, bytes + fragment: Option, // #something-at-the-end, None by default +} + +pub enum DataUrlParseError { + UrlParseError, + MalformedDataUrlError, + Base64DecodeError, +} + +impl fmt::Debug for DataUrlParseError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("DataUrlParseError").finish() + } +} + +pub fn parse_data_url_meta_data( + meta_data_string: String, +) -> (Option, Option, bool) { + let mut media_type: Option = None; + let mut charset: Option = None; + let mut encoded: bool = false; + + // Parse meta data + let content_type_items: Vec<&str> = meta_data_string.split(';').collect(); + let mut i: i8 = 0; + for item in &content_type_items { + if i == 0 { + if item.trim().len() > 0 && item.contains("/") { + media_type = Some(item.trim().to_string()); + } + } else { + if item.trim().eq_ignore_ascii_case("base64") { + encoded = true; + } else if item.trim().starts_with("charset=") { + if let Some(e) = Encoding::for_label_no_replacement((&item[8..]).as_bytes()) { + charset = Some(e.name().to_string()); + } + } + } + + i += 1; + } + + (media_type, charset, encoded) +} + +impl DataUrl { + pub fn new() -> DataUrl { + DataUrl { + media_type: None, + charset: None, + encoded: false, + data: [].to_vec(), + fragment: None, + } + } + + pub fn parse(input_str: &str) -> Result { + match Url::parse(input_str) { + Ok(url) => { + let path: String = url.path().to_string(); + if let Some(comma_offset) = path.find(',') { + let fragment: Option<&str> = url.fragment(); + + // Parse meta data + let meta_data_string = String::from(&path[..comma_offset]); + let (media_type, charset, encoded) = parse_data_url_meta_data(meta_data_string); + + // Parse raw data into vector of bytes + let mut data_string: String = percent_decode_str(&path[comma_offset + 1..]) + .decode_utf8_lossy() + .to_string(); + if let Some(query) = url.query() { + data_string += "?"; + data_string += &percent_decode_str(&query).decode_utf8_lossy().to_string(); + } + let mut unable_to_decode_base64: bool = false; + let blob: Vec = if encoded { + match base64::decode(&data_string) { + Ok(decoded) => decoded, + Err(_) => { + unable_to_decode_base64 = true; + [].to_vec() + } + } + } else { + data_string.as_bytes().to_vec() + }; + + if unable_to_decode_base64 { + return Err(DataUrlParseError::Base64DecodeError); + } + + Ok(DataUrl { + media_type: media_type, + charset: charset, + encoded: encoded, + data: blob, + fragment: if let Some(f) = fragment { + Some(f.to_string()) + } else { + None + }, + }) + } else { + Err(DataUrlParseError::MalformedDataUrlError) + } + } + Err(_) => Err(DataUrlParseError::UrlParseError), + } + } + + pub fn to_string(&self) -> String { + let mut result: String = "data:".to_string(); + + if let Some(mt) = &self.media_type { + result += &mt; + } + + if let Some(c) = &self.charset { + // windows-1252 is same US-ASCII, the default one + if c != "windows-1252" { + result += ";charset="; + result += &c; + } + } + + if self.encoded { + result += ";base64,"; + if self.data.len() > 0 { + // This can never fail + if let Some(encoding) = Encoding::for_label( + self.charset + .as_ref() + .unwrap_or(&DEFAULT_CHARSET.to_string()) + .as_bytes(), + ) { + let (decoded, _, _) = encoding.decode(&self.data); + result += &base64::encode(&decoded.as_bytes()); + } + } + } else { + result += ","; + if self.data.len() > 0 { + result += + &utf8_percent_encode(&String::from_utf8_lossy(&self.data), NON_ALPHANUMERIC) + .to_string(); + } + } + + if let Some(f) = &self.fragment { + result += "#"; + result += &utf8_percent_encode(f, NON_ALPHANUMERIC).to_string(); + } + + result + } + + pub fn media_type(&self) -> &str { + if let Some(mt) = &self.media_type { + mt + } else { + DEFAULT_MEDIA_TYPE + } + } + + pub fn media_type_no_default(&self) -> Option { + if let Some(mt) = &self.media_type { + Some(mt.to_string()) + } else { + None + } + } + + pub fn set_media_type(&mut self, new_media_type: Option) { + if let Some(mt) = new_media_type { + if mt.trim().len() > 0 { + self.media_type = Some(mt.to_string()); + } else { + // Empty media type makes it fall back to default (text/plain) + self.media_type = None; + } + } else { + self.media_type = None; + } + } + + pub fn charset(&self) -> &str { + if let Some(c) = &self.charset { + c + } else { + DEFAULT_CHARSET + } + } + + pub fn charset_no_default(&self) -> Option { + if let Some(c) = &self.charset { + Some(c.to_string()) + } else { + None + } + } + + pub fn set_charset(&mut self, new_charset: Option) { + if let Some(c) = new_charset { + // Validate the input + if let Some(e) = Encoding::for_label_no_replacement(c.as_bytes()) { + self.charset = Some(e.name().to_string()); + } else { + // Since browsers fall back to US-ASCII, so do we + self.charset = None; + } + } else { + self.charset = None; + } + } + + pub fn encoded(&self) -> bool { + self.encoded + } + + pub fn set_encoded(&mut self, new_encoded: bool) { + self.encoded = new_encoded; + } + + pub fn data(&self) -> &[u8] { + &self.data + } + + // TODO + // pub fn text(&self) -> String { + // } + + // TODO + // pub fn set_text(&self, Option) { + // } + + pub fn set_data(&mut self, new_data: &[u8]) { + self.data = new_data.to_vec(); + } + + pub fn fragment(&self) -> Option { + if let Some(f) = &self.fragment { + Some(f.to_string()) + } else { + None + } + } + + pub fn set_fragment(&mut self, new_fragment: Option) { + self.fragment = new_fragment; + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..1afed64 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,104 @@ +extern crate clap; + +use clap::{crate_authors, crate_description, crate_version, App, Arg}; +use dataurl::DataUrl; +use std::env; +use std::fs; + +fn main() { + let app = App::new(env!("CARGO_PKG_NAME")) + .version(crate_version!()) + .author(format!("\n{}", crate_authors!("\n")).as_str()) + .about(crate_description!()) + .arg( + Arg::with_name("base64") + .short("b") + .long("base64") + .multiple(false) + .help("Enforce base64 encoding"), + ) + .arg( + Arg::with_name("charset") + .short("c") + .long("charset") + .multiple(false) + .takes_value(true) + .help("Enforce custom charset"), + ) + .arg( + Arg::with_name("decode") + .short("d") + .long("decode") + .multiple(false) + .help("Toggles decode mode on"), + ) + .arg( + Arg::with_name("fragment") + .short("f") + .long("fragment") + .multiple(false) + .takes_value(true) + .help("Append URL fragment"), + ) + .arg( + Arg::with_name("input-file") + .short("i") + .long("input-file") + .multiple(false) + .takes_value(true) + .help("Append URL fragment"), + ) + .arg( + Arg::with_name("media_type") + .short("t") + .long("media-type") + .multiple(false) + .takes_value(true) + .help("Sets custom media type for encode mode"), + ) + .arg( + Arg::with_name("INPUT") + .help("Sets the input file to use") + .required(false) + .index(1), + ) + .get_matches(); + + let is_in_decode_mode: bool = app.is_present("decode"); + let input = if app.is_present("INPUT") { + app.value_of("INPUT").unwrap().to_string() + } else if app.is_present("input-file") { + fs::read_to_string(app.value_of("input-file").unwrap()) + .expect("Something went wrong reading the file") + } else { + eprintln!("no input provided"); + "".to_string() + }; + + if is_in_decode_mode { + match DataUrl::parse(&input) { + Ok(data_url) => { + println!("{}", String::from_utf8_lossy(data_url.data())); + } + Err(_data_url_parse_err) => { + eprintln!("parsing error"); + } + } + } else { + let mut data_url = DataUrl::new(); + data_url.set_data(input.as_bytes()); + if app.is_present("base64") { + data_url.set_encoded(true); + } + if app.is_present("charset") { + data_url.set_charset(Some(app.value_of("charset").unwrap().to_string())); + } + if app.is_present("media_type") { + data_url.set_media_type(Some(app.value_of("media_type").unwrap().to_string())); + } + if app.is_present("fragment") { + data_url.set_fragment(Some(app.value_of("fragment").unwrap().to_string())); + } + println!("{}", data_url.to_string()); + } +} diff --git a/tests/_data_/text-file.txt b/tests/_data_/text-file.txt new file mode 100644 index 0000000..2ef267e --- /dev/null +++ b/tests/_data_/text-file.txt @@ -0,0 +1 @@ +some content diff --git a/tests/lib/charset.rs b/tests/lib/charset.rs new file mode 100644 index 0000000..2ca7346 --- /dev/null +++ b/tests/lib/charset.rs @@ -0,0 +1,46 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn default() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.charset(), "US-ASCII"); + Ok(()) + } + + #[test] + fn utf8() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_charset(Some("utf8".to_string())); + assert_eq!(data_url.charset(), "UTF-8"); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn fallback_to_default_if_bad() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_charset(Some("BAD-CHARSET".to_string())); // This bad input must make it fall back to US-ASCII + assert_eq!(data_url.charset(), "US-ASCII"); + Ok(()) + } +} diff --git a/tests/lib/charset_no_default.rs b/tests/lib/charset_no_default.rs new file mode 100644 index 0000000..46aef97 --- /dev/null +++ b/tests/lib/charset_no_default.rs @@ -0,0 +1,46 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn default() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.charset_no_default(), None); + Ok(()) + } + + #[test] + fn utf8() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_charset(Some("utf8".to_string())); + assert_eq!(data_url.charset_no_default(), Some("UTF-8".to_string())); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn fallback_to_default_if_bad() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_charset(Some("BAD-CHARSET".to_string())); // This bad input must make it fall back to US-ASCII + assert_eq!(data_url.charset_no_default(), None); + Ok(()) + } +} diff --git a/tests/lib/fragment.rs b/tests/lib/fragment.rs new file mode 100644 index 0000000..5636b17 --- /dev/null +++ b/tests/lib/fragment.rs @@ -0,0 +1,61 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn default_and_set_fragment() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + + // Should be none by default + assert_eq!(data_url.fragment(), None); + assert_eq!(data_url.to_string(), "data:,"); + + // Shown as defined but empty is set to an empty string + data_url.set_fragment(Some("".to_string())); + assert_eq!(data_url.fragment(), Some("".to_string())); + assert_eq!(data_url.to_string(), "data:,#"); + + // Should be possible te unset it + data_url.set_fragment(None); + assert_eq!(data_url.fragment(), None); + + // Should be possible to set it to a string + data_url.set_fragment(Some("something".to_string())); + assert_eq!(data_url.fragment(), Some("something".to_string())); + assert_eq!(data_url.to_string(), "data:,#something"); + + // Should be possible to set it to a whitespace + data_url.set_fragment(Some(" ".to_string())); + assert_eq!(data_url.fragment(), Some(" ".to_string())); + assert_eq!(data_url.to_string(), "data:,#%20"); + + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn fallback_to_default_if_bad() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_charset(Some("BAD-CHARSET".to_string())); // This bad input must make it fall back to US-ASCII + assert_eq!(data_url.charset(), "US-ASCII"); + Ok(()) + } +} diff --git a/tests/lib/media_type.rs b/tests/lib/media_type.rs new file mode 100644 index 0000000..c993fc2 --- /dev/null +++ b/tests/lib/media_type.rs @@ -0,0 +1,54 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn default() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.media_type(), "text/plain"); + Ok(()) + } + + #[test] + fn utf8() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some("image/png".to_string())); + assert_eq!(data_url.media_type(), "image/png"); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn fallback_to_default_if_empty() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some("".to_string())); + assert_eq!(data_url.media_type(), "text/plain"); + Ok(()) + } + + #[test] + fn fallback_to_default_if_whitespace() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some(" ".to_string())); + assert_eq!(data_url.media_type(), "text/plain"); + Ok(()) + } +} diff --git a/tests/lib/media_type_no_default.rs b/tests/lib/media_type_no_default.rs new file mode 100644 index 0000000..29598e6 --- /dev/null +++ b/tests/lib/media_type_no_default.rs @@ -0,0 +1,57 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn default() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.media_type_no_default(), None); + Ok(()) + } + + #[test] + fn utf8() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some("image/png".to_string())); + assert_eq!( + data_url.media_type_no_default(), + Some("image/png".to_string()) + ); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn fallback_to_default_if_empty() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some("".to_string())); + assert_eq!(data_url.media_type_no_default(), None); + Ok(()) + } + + #[test] + fn fallback_to_default_if_whitespace() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_media_type(Some(" ".to_string())); + assert_eq!(data_url.media_type_no_default(), None); + Ok(()) + } +} diff --git a/tests/lib/mod.rs b/tests/lib/mod.rs new file mode 100644 index 0000000..fc2c0e8 --- /dev/null +++ b/tests/lib/mod.rs @@ -0,0 +1,8 @@ +mod charset; +mod charset_no_default; +mod fragment; +mod media_type; +mod media_type_no_default; +mod new; +mod parse; +mod to_string; diff --git a/tests/lib/new.rs b/tests/lib/new.rs new file mode 100644 index 0000000..c968703 --- /dev/null +++ b/tests/lib/new.rs @@ -0,0 +1,18 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn create() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.to_string(), "data:,"); + Ok(()) + } +} diff --git a/tests/lib/parse.rs b/tests/lib/parse.rs new file mode 100644 index 0000000..911501e --- /dev/null +++ b/tests/lib/parse.rs @@ -0,0 +1,134 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn spaces_around_url() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse(" data:, a b ")?; + assert_eq!(data_url.data(), " a b".as_bytes()); + Ok(()) + } + + #[test] + fn no_media_type() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:,Hello,%20World!")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "US-ASCII".to_string()); + assert!(!data_url.encoded()); + assert_eq!(String::from_utf8_lossy(data_url.data()), "Hello, World!"); + assert_eq!(data_url.fragment(), None); + Ok(()) + } + + #[test] + fn query_and_empty_fragment() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:;,Hello?World#")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "US-ASCII".to_string()); + assert!(!data_url.encoded()); + assert_eq!(String::from_utf8_lossy(data_url.data()), "Hello?World"); + assert_eq!(data_url.fragment(), Some("".to_string())); + Ok(()) + } + + #[test] + fn empty_query_empty_fragment() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:;,Hello?#")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "US-ASCII".to_string()); + assert!(!data_url.encoded()); + assert_eq!(String::from_utf8_lossy(data_url.data()), "Hello?"); + assert_eq!(data_url.fragment(), Some("".to_string())); + Ok(()) + } + + #[test] + fn utf8_charset_no_data() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:;charset=utf8;base64,")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "UTF-8".to_string()); + assert!(data_url.encoded()); + assert_eq!(String::from_utf8_lossy(data_url.data()), ""); + assert_eq!(data_url.fragment(), None); + Ok(()) + } + + #[test] + fn utf8_charset_emoji() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:;charset=utf8;base64,4piA77iP")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "UTF-8".to_string()); + assert!(data_url.encoded()); + assert_eq!(data_url.data(), [226, 152, 128, 239, 184, 143]); + assert_eq!(data_url.fragment(), None); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn empty_str_input() -> Result<(), DataUrlParseError> { + match DataUrl::parse("") { + Ok(_data_url) => { + assert!(false); + } + Err(_data_url_parse_err) => { + assert!(true); + } + } + Ok(()) + } + + #[test] + fn missing_media_type() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:base64,SGVsbG8sIHdvcmxkIQo=")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "US-ASCII".to_string()); + assert!(!data_url.encoded()); + assert_eq!( + String::from_utf8_lossy(data_url.data()), + "SGVsbG8sIHdvcmxkIQo=" + ); + assert_eq!(data_url.fragment(), None); + Ok(()) + } + + #[test] + fn bad_charset() -> Result<(), DataUrlParseError> { + let data_url: DataUrl = DataUrl::parse("data:;charset=BAD-CHARSET;base64,")?; + assert_eq!(data_url.media_type(), "text/plain".to_string()); + assert_eq!(data_url.charset(), "US-ASCII".to_string()); + assert!(data_url.encoded()); + assert_eq!(data_url.data(), []); + assert_eq!(data_url.fragment(), None); + Ok(()) + } + + // #[test] + // fn bad_media_type() -> Result<(), DataUrlParseError> { + // let data_url: DataUrl = DataUrl::parse("data:bad;,")?; + // assert_eq!(data_url.media_type(), "text/plain".to_string()); + // assert_eq!(data_url.charset(), "US-ASCII".to_string()); + // assert!(data_url.encoded()); + // assert_eq!(data_url.data(), []); + // assert_eq!(data_url.fragment(), None); + // Ok(()) + // } +} diff --git a/tests/lib/to_string.rs b/tests/lib/to_string.rs new file mode 100644 index 0000000..5ca04c9 --- /dev/null +++ b/tests/lib/to_string.rs @@ -0,0 +1,94 @@ +// ██████╗ █████╗ ███████╗███████╗██╗███╗ ██╗ ██████╗ +// ██╔══██╗██╔══██╗██╔════╝██╔════╝██║████╗ ██║██╔════╝ +// ██████╔╝███████║███████╗███████╗██║██╔██╗ ██║██║ ███╗ +// ██╔═══╝ ██╔══██║╚════██║╚════██║██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║███████║███████║██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod passing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn empty() -> Result<(), DataUrlParseError> { + let data_url = DataUrl::new(); + assert_eq!(data_url.to_string(), "data:,"); + Ok(()) + } + + #[test] + fn empty_encoded() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + assert_eq!(data_url.to_string(), "data:;base64,"); + Ok(()) + } + + #[test] + fn empty_encoded_with_media_type() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + data_url.set_media_type(Some("text/plain".to_string())); + assert_eq!(data_url.to_string(), "data:text/plain;base64,"); + Ok(()) + } + + #[test] + fn empty_encoded_with_media_type_and_ascii_charset() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + data_url.set_media_type(Some("text/plain".to_string())); + data_url.set_charset(Some("US-ASCII".to_string())); + assert_eq!(data_url.to_string(), "data:text/plain;base64,"); + Ok(()) + } + + #[test] + fn empty_encoded_with_media_type_and_utf8_charset() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + data_url.set_media_type(Some("text/plain".to_string())); + data_url.set_charset(Some("utf8".to_string())); + assert_eq!( + data_url.to_string(), + "data:text/plain;charset=UTF-8;base64," + ); + Ok(()) + } + + #[test] + fn full_encoded_with_media_type_and_utf8_charset() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + data_url.set_media_type(Some("text/plain".to_string())); + data_url.set_charset(Some("utf8".to_string())); + data_url.set_data(&[0xe2, 0x98, 0x80, 0xef, 0xb8, 0x8f]); // Sun emoji in UTF-8 bytes + assert_eq!( + data_url.to_string(), + "data:text/plain;charset=UTF-8;base64,4piA77iP" + ); + Ok(()) + } +} + +// ███████╗ █████╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ +// ██╔════╝██╔══██╗██║██║ ██║████╗ ██║██╔════╝ +// █████╗ ███████║██║██║ ██║██╔██╗ ██║██║ ███╗ +// ██╔══╝ ██╔══██║██║██║ ██║██║╚██╗██║██║ ██║ +// ██║ ██║ ██║██║███████╗██║██║ ╚████║╚██████╔╝ +// ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ + +#[cfg(test)] +mod failing { + use dataurl::{DataUrl, DataUrlParseError}; + + #[test] + fn empty_encoded_with_media_type_and_bad_charset() -> Result<(), DataUrlParseError> { + let mut data_url = DataUrl::new(); + data_url.set_encoded(true); + data_url.set_media_type(Some("text/plain".to_string())); + data_url.set_charset(Some("BAD-CHARSET".to_string())); // This bad input must make it fall back to US-ASCII + assert_eq!(data_url.to_string(), "data:text/plain;base64,"); + Ok(()) + } +} diff --git a/tests/mod.rs b/tests/mod.rs new file mode 100644 index 0000000..e281422 --- /dev/null +++ b/tests/mod.rs @@ -0,0 +1,2 @@ +// mod cli; +mod lib;