diskus-0.9.0/.cargo_vcs_info.json0000644000000001360000000000100123440ustar { "git": { "sha1": "d8a77db0f693ec32007cf337572b559cbbff50fe" }, "path_in_vcs": "" }diskus-0.9.0/.github/workflows/CICD.yml000064400000000000000000000307121046102023000157610ustar 00000000000000name: CICD env: MIN_SUPPORTED_RUST_VERSION: "1.80.0" CICD_INTERMEDIATES_DIR: "_cicd-intermediates" on: workflow_dispatch: pull_request: push: branches: - master tags: - '*' jobs: min_version: name: Minimum supported rust version runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }}) uses: actions-rs/toolchain@v1 with: toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }} default: true profile: minimal # minimal component installation (ie, no documentation) components: clippy, rustfmt - name: Ensure `cargo fmt` has been run uses: actions-rs/cargo@v1 with: command: fmt args: -- --check - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix) uses: actions-rs/cargo@v1 with: command: clippy args: --locked --all-targets --all-features - name: Run tests uses: actions-rs/cargo@v1 with: command: test args: --locked - name: Build library without CLI dependencies uses: actions-rs/cargo@v1 with: command: build args: --locked --lib --no-default-features build: name: ${{ matrix.job.os }} (${{ matrix.job.target }}) runs-on: ${{ matrix.job.os }} strategy: fail-fast: false matrix: job: - { target: aarch64-unknown-linux-gnu , os: ubuntu-latest, use-cross: true } - { target: arm-unknown-linux-gnueabihf , os: ubuntu-latest, use-cross: true } - { target: arm-unknown-linux-musleabihf, os: ubuntu-latest, use-cross: true } - { target: i686-pc-windows-msvc , os: windows-latest } - { target: i686-unknown-linux-gnu , os: ubuntu-latest, use-cross: true } - { target: i686-unknown-linux-musl , os: ubuntu-latest, use-cross: true } - { target: x86_64-apple-darwin , os: macos-latest } - { target: aarch64-apple-darwin , os: macos-latest } - { target: x86_64-pc-windows-gnu , os: windows-latest } - { target: x86_64-pc-windows-msvc , os: windows-latest } - { target: x86_64-unknown-linux-gnu , os: ubuntu-latest, use-cross: true } - { target: x86_64-unknown-linux-musl , os: ubuntu-latest, use-cross: true } steps: - name: Checkout source code uses: actions/checkout@v2 - name: Install prerequisites shell: bash run: | case ${{ matrix.job.target }} in arm-unknown-linux-*) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;; aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install gcc-aarch64-linux-gnu ;; esac - name: Extract crate information shell: bash run: | echo "PROJECT_NAME=diskus" >> $GITHUB_ENV echo "PROJECT_VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)" >> $GITHUB_ENV echo "PROJECT_MAINTAINER=$(sed -n 's/^authors = \["\(.*\)"\]/\1/p' Cargo.toml)" >> $GITHUB_ENV echo "PROJECT_HOMEPAGE=$(sed -n 's/^homepage = "\(.*\)"/\1/p' Cargo.toml)" >> $GITHUB_ENV - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable target: ${{ matrix.job.target }} override: true profile: minimal # minimal component installation (ie, no documentation) - name: Show version information (Rust, cargo, GCC) shell: bash run: | gcc --version || true rustup -V rustup toolchain list rustup default cargo -V rustc -V - name: Build uses: actions-rs/cargo@v1 with: use-cross: ${{ matrix.job.use-cross }} command: build args: --locked --release --target=${{ matrix.job.target }} - name: Strip debug information from executable id: strip shell: bash run: | # Figure out suffix of binary EXE_suffix="" case ${{ matrix.job.target }} in *-pc-windows-*) EXE_suffix=".exe" ;; esac; # Figure out what strip tool to use if any STRIP="strip" case ${{ matrix.job.target }} in arm-unknown-linux-*) STRIP="arm-linux-gnueabihf-strip" ;; aarch64-unknown-linux-gnu) STRIP="aarch64-linux-gnu-strip" ;; *-pc-windows-msvc) STRIP="" ;; esac; # Setup paths BIN_DIR="${{ env.CICD_INTERMEDIATES_DIR }}/stripped-release-bin/" mkdir -p "${BIN_DIR}" BIN_NAME="${{ env.PROJECT_NAME }}${EXE_suffix}" BIN_PATH="${BIN_DIR}/${BIN_NAME}" # Copy the release build binary to the result location cp "target/${{ matrix.job.target }}/release/${BIN_NAME}" "${BIN_DIR}" # Also strip if possible if [ -n "${STRIP}" ]; then "${STRIP}" "${BIN_PATH}" fi # Let subsequent steps know where to find the (stripped) bin echo "BIN_PATH=${BIN_PATH}" >> $GITHUB_OUTPUT echo "BIN_NAME=${BIN_NAME}" >> $GITHUB_OUTPUT - name: Set testing options id: test-options shell: bash run: | # test only library unit tests and binary for arm-type targets unset CARGO_TEST_OPTIONS unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-* | aarch64-*) CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}" ;; esac; echo "CARGO_TEST_OPTIONS=${CARGO_TEST_OPTIONS}" >> $GITHUB_OUTPUT - name: Run tests uses: actions-rs/cargo@v1 with: use-cross: ${{ matrix.job.use-cross }} command: test args: --locked --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}} - name: Create tarball id: package shell: bash run: | PKG_suffix=".tar.gz" ; case ${{ matrix.job.target }} in *-pc-windows-*) PKG_suffix=".zip" ;; esac; PKG_BASENAME=${PROJECT_NAME}-v${PROJECT_VERSION}-${{ matrix.job.target }} PKG_NAME=${PKG_BASENAME}${PKG_suffix} echo "PKG_NAME=${PKG_NAME}" >> $GITHUB_OUTPUT PKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/package" ARCHIVE_DIR="${PKG_STAGING}/${PKG_BASENAME}/" mkdir -p "${ARCHIVE_DIR}" # Binary cp "${{ steps.strip.outputs.BIN_PATH }}" "$ARCHIVE_DIR" # Man page cp 'doc/${{ env.PROJECT_NAME }}.1' "$ARCHIVE_DIR" # README, LICENSE and CHANGELOG files cp "README.md" "LICENSE-MIT" "LICENSE-APACHE" "CHANGELOG.md" "$ARCHIVE_DIR" # base compressed package pushd "${PKG_STAGING}/" >/dev/null case ${{ matrix.job.target }} in *-pc-windows-*) 7z -y a "${PKG_NAME}" "${PKG_BASENAME}"/* | tail -2 ;; *) tar czf "${PKG_NAME}" "${PKG_BASENAME}"/* ;; esac; popd >/dev/null # Let subsequent steps know where to find the compressed package echo "PKG_PATH="${PKG_STAGING}/${PKG_NAME}"" >> $GITHUB_OUTPUT - name: Create Debian package id: debian-package shell: bash if: startsWith(matrix.job.os, 'ubuntu') run: | COPYRIGHT_YEARS="2018 - "$(date "+%Y") DPKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/debian-package" DPKG_DIR="${DPKG_STAGING}/dpkg" mkdir -p "${DPKG_DIR}" DPKG_BASENAME=${PROJECT_NAME} DPKG_CONFLICTS=${PROJECT_NAME}-musl case ${{ matrix.job.target }} in *-musl*) DPKG_BASENAME=${PROJECT_NAME}-musl ; DPKG_CONFLICTS=${PROJECT_NAME} ;; esac; DPKG_VERSION=${PROJECT_VERSION} unset DPKG_ARCH case ${{ matrix.job.target }} in aarch64-*-linux-*) DPKG_ARCH=arm64 ;; arm-*-linux-*hf) DPKG_ARCH=armhf ;; i686-*-linux-*) DPKG_ARCH=i686 ;; x86_64-*-linux-*) DPKG_ARCH=amd64 ;; *) DPKG_ARCH=notset ;; esac; DPKG_NAME="${DPKG_BASENAME}_${DPKG_VERSION}_${DPKG_ARCH}.deb" echo "DPKG_NAME=${DPKG_NAME}" >> $GITHUB_OUTPUT # Binary install -Dm755 "${{ steps.strip.outputs.BIN_PATH }}" "${DPKG_DIR}/usr/bin/${{ steps.strip.outputs.BIN_NAME }}" # Man page install -Dm644 'doc/${{ env.PROJECT_NAME }}.1' "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1" gzip -n --best "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1" # README and LICENSE install -Dm644 "README.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/README.md" install -Dm644 "LICENSE-MIT" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-MIT" install -Dm644 "LICENSE-APACHE" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-APACHE" install -Dm644 "CHANGELOG.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog" gzip -n --best "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog" cat > "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright" < "${DPKG_DIR}/DEBIAN/control" <> $GITHUB_OUTPUT # build dpkg fakeroot dpkg-deb --build "${DPKG_DIR}" "${DPKG_PATH}" - name: "Artifact upload: tarball" uses: actions/upload-artifact@master with: name: ${{ steps.package.outputs.PKG_NAME }} path: ${{ steps.package.outputs.PKG_PATH }} - name: "Artifact upload: Debian package" uses: actions/upload-artifact@master if: steps.debian-package.outputs.DPKG_NAME with: name: ${{ steps.debian-package.outputs.DPKG_NAME }} path: ${{ steps.debian-package.outputs.DPKG_PATH }} - name: Check for release id: is-release shell: bash run: | unset IS_RELEASE ; if [[ $GITHUB_REF =~ ^refs/tags/v[0-9].* ]]; then IS_RELEASE='true' ; fi echo "IS_RELEASE=${IS_RELEASE}" >> $GITHUB_OUTPUT - name: Publish archives and packages uses: softprops/action-gh-release@v1 if: steps.is-release.outputs.IS_RELEASE with: files: | ${{ steps.package.outputs.PKG_PATH }} ${{ steps.debian-package.outputs.DPKG_PATH }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diskus-0.9.0/.gitignore000064400000000000000000000000231046102023000131170ustar 00000000000000/target **/*.rs.bk diskus-0.9.0/CHANGELOG.md000064400000000000000000000050161046102023000127470ustar 00000000000000# v0.9.0 ## Features - Added `--directories` option with values `auto`/`included`/`excluded` to control whether directory sizes are counted - Added `apparent_size()` builder method as shorthand for `.count_type(CountType::ApparentSize)` ## Bugfixes - Fixed directory counting to match `du` behavior: - Disk usage mode: directories are included (matches `du -s`) - Apparent size mode: directories are excluded (matches `du -sb`) ## Library - **Breaking**: Complete redesign of the API - Renamed `Walk` to `DiskUsage` - Renamed `FilesizeType` to `CountType` - Changed to a builder pattern: `DiskUsage::new(&paths).apparent_size().count()` - `count()` now returns a `DiskUsageResult` struct instead of a tuple - `new()` now accepts `impl IntoIterator` where `P: AsRef` - Default number of workers (3× CPU cores) is now set in the library, not the CLI # v0.8.0 ## Changes - Updated Rust edition from 2018 to 2021 - Updated dependencies - CI fixes # v0.7.0 ## Changes - Migrated CI from Travis to GitHub Actions - Added CHANGELOG file - Updated dependencies # v0.6.0 ## Changes There is an important change in default behavior: `diskus` will now report "disk usage" instead of "apparent file size", in analogy to what `du -sh` does. At the same time however, we introduce a new `-b`/`--apparent-size` option which can be used to switch back to apparent file size (in analogy to what `du -sbh` does). see #25 ## Features - `diskus` is now available for Windows, see #32 (@fawick) - Error messages are now hidden by default and can be re-enabled via `--verbose`, see #34 (@wngr) - Added a new `--size-format ` option which can be used to switch from decimal to binary exponents (MiB instead of MB). - `diskus` changes its output format when the output is piped to a file or to another program. It will simply print the number of bytes, see #35 - Added a new `-b`/`--apparent-size` option which can be used to switch from "disk usage" to "apparent size" (not available on Windows) ## Other - diskus is now in the official Arch repositories, see #24 (@polyzen) - diskus is now available on NixOS, see #26 (@fuerbringer) - diskus is now available on Homebrew and MacPorts, see #33 (@heimskr) - Added a man page # v0.5.0 - Expose diskus internals as a library, see #21 (@amilajack) # v0.4.0 - More performance improvements by using a custom parallel directory-walker, see #15 # v0.3.1 # v0.3.0 - Renamed the project to diskus # v0.2.0 - Fine-tuned number of threads (makes is even faster) # v0.1.0 Initial release diskus-0.9.0/Cargo.lock0000644000000306330000000000100103240ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "anstream" version = "0.6.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" [[package]] name = "anstyle-parse" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ "windows-sys 0.61.2", ] [[package]] name = "anstyle-wincon" version = "3.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", "windows-sys 0.61.2", ] [[package]] name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[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 = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" [[package]] name = "clap" version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" dependencies = [ "anstream", "anstyle", "clap_lex", "strsim", "terminal_size", ] [[package]] name = "clap_lex" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" [[package]] name = "colorchoice" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "crossbeam-channel" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "diskus" version = "0.9.0" dependencies = [ "atty", "clap", "crossbeam-channel", "humansize", "num-format", "rayon", "tempdir", ] [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys 0.61.2", ] [[package]] name = "fuchsia-cprng" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" [[package]] name = "hermit-abi" version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" dependencies = [ "libc", ] [[package]] name = "humansize" version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" dependencies = [ "libm", ] [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" version = "0.2.178" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" [[package]] name = "libm" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "linux-raw-sys" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "num-format" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" dependencies = [ "arrayvec", "itoa", ] [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "rand" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.3.1", "rdrand", "winapi", ] [[package]] name = "rand_core" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" dependencies = [ "rand_core 0.4.2", ] [[package]] name = "rand_core" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" [[package]] name = "rayon" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-core" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] [[package]] name = "rdrand" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "remove_dir_all" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ "winapi", ] [[package]] name = "rustix" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.61.2", ] [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "tempdir" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" dependencies = [ "rand", "remove_dir_all", ] [[package]] name = "terminal_size" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" dependencies = [ "rustix", "windows-sys 0.60.2", ] [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[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" [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "windows-targets" version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ "windows-link", "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" [[package]] name = "windows_aarch64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" [[package]] name = "windows_i686_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" [[package]] name = "windows_i686_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" [[package]] name = "windows_i686_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" [[package]] name = "windows_x86_64_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" [[package]] name = "windows_x86_64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" [[package]] name = "windows_x86_64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" diskus-0.9.0/Cargo.toml0000644000000032340000000000100103440ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.80" name = "diskus" version = "0.9.0" authors = ["David Peter "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A minimal, fast alternative to 'du -sh'." homepage = "https://github.com/sharkdp/diskus" readme = "README.md" categories = ["command-line-utilities"] license = "MIT/Apache-2.0" repository = "https://github.com/sharkdp/diskus" [features] cli = [ "dep:clap", "dep:humansize", "dep:num-format", "dep:atty", ] default = ["cli"] [lib] name = "diskus" path = "src/lib.rs" [[bin]] name = "diskus" path = "src/main.rs" required-features = ["cli"] [[test]] name = "walk" path = "tests/walk.rs" [dependencies.atty] version = "0.2" optional = true [dependencies.clap] version = "4.5" features = [ "suggestions", "color", "wrap_help", ] optional = true [dependencies.crossbeam-channel] version = "0.5" [dependencies.humansize] version = "2.1" optional = true [dependencies.num-format] version = "0.4" optional = true [dependencies.rayon] version = "1.11" [dev-dependencies.tempdir] version = "0.3" [profile.release] lto = true codegen-units = 1 diskus-0.9.0/Cargo.toml.orig000064400000000000000000000017601046102023000140270ustar 00000000000000[package] authors = ["David Peter "] categories = ["command-line-utilities"] description = "A minimal, fast alternative to 'du -sh'." homepage = "https://github.com/sharkdp/diskus" license = "MIT/Apache-2.0" name = "diskus" readme = "README.md" repository = "https://github.com/sharkdp/diskus" version = "0.9.0" edition = "2021" rust-version = "1.80" [features] default = ["cli"] cli = [ "dep:clap", "dep:humansize", "dep:num-format", "dep:atty", ] [dependencies] # Library dependencies rayon = "1.11" crossbeam-channel = "0.5" # CLI dependencies (optional) humansize = { version = "2.1", optional = true } num-format = { version = "0.4", optional = true } atty = { version = "0.2", optional = true } clap = { version = "4.5", features = [ "suggestions", "color", "wrap_help", ], optional = true } [dev-dependencies] tempdir = "0.3" [[bin]] name = "diskus" path = "src/main.rs" required-features = ["cli"] [profile.release] lto = true codegen-units = 1 diskus-0.9.0/LICENSE-APACHE000064400000000000000000000261351046102023000130670ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diskus-0.9.0/LICENSE-MIT000064400000000000000000000017771046102023000126040ustar 00000000000000Permission 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. diskus-0.9.0/README.md000064400000000000000000000104601046102023000124140ustar 00000000000000# diskus [![CICD](https://github.com/sharkdp/diskus/actions/workflows/CICD.yml/badge.svg)](https://github.com/sharkdp/diskus/actions/workflows/CICD.yml) *A minimal, fast alternative to `du -sh`.* `diskus` is a very simple program that computes the total size of the current directory. It is a parallelized version of `du -sh`. On my 8-core laptop, it is about ten times faster than `du` with a cold disk cache and more than three times faster with a warm disk cache. ``` bash > diskus 9.59 GB (9,587,408,896 bytes) ``` ## Benchmark The following benchmarks have been performed with [hyperfine](https://github.com/sharkdp/hyperfine) on a moderately large folder (15GB, 100k directories, 400k files). Smaller folders are not really of any interest since all programs would finish in a reasonable time that would not interrupt your workflow. In addition to `du` and `diskus`, we also add [tin-summer](https://github.com/vmchale/tin-summer) (`sn`) and [`dust`](https://github.com/bootandy/dust) in our comparison. Both are also written in Rust and provide much more features than `diskus` (check them out!). The optimal number of threads for `sn` (`-j` option) was determined via `hyperfine --parameter-scan`. ### Cold disk cache ```bash sudo -v hyperfine --prepare 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches' \ 'diskus' 'du -sh' 'sn p -d0 -j8' 'dust -d0' ``` (the `sudo`/`sync`/`drop_caches` commands are a way to [clear the filesystem caches between benchmarking runs](https://github.com/sharkdp/hyperfine#io-heavy-programs)) | Command | Mean [s] | Min [s] | Max [s] | Relative | |:---|---:|---:|---:|---:| | `diskus` | 1.746 ± 0.017 | 1.728 | 1.770 | 1.00 | | `du -sh` | 17.776 ± 0.549 | 17.139 | 18.413 | 10.18 | | `sn p -d0 -j8` | 18.094 ± 0.566 | 17.482 | 18.579 | 10.36 | | `dust -d0` | 21.357 ± 0.328 | 20.974 | 21.759 | 12.23 | ### Warm disk cache On a warm disk cache, the differences are smaller: ```bash hyperfine --warmup 5 'diskus' 'du -sh' 'sn p -d0 -j8' 'dust -d0' ``` | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `diskus` | 500.3 ± 17.3 | 472.9 | 530.6 | 1.00 | | `du -sh` | 1098.3 ± 10.0 | 1087.8 | 1122.4 | 2.20 | | `sn p -d0 -j8` | 1122.2 ± 18.2 | 1107.3 | 1170.1 | 2.24 | | `dust -d0` | 3532.1 ± 26.4 | 3490.0 | 3563.1 | 7.06 | ## Installation ### On Debian-based systems You can download the latest Debian package from the [release page](https://github.com/sharkdp/diskus/releases) and install it via `dpkg`: ``` bash wget "https://github.com/sharkdp/diskus/releases/download/v0.9.0/diskus_0.9.0_amd64.deb" sudo dpkg -i diskus_0.9.0_amd64.deb ``` ### On Arch-based systems ``` bash pacman -S diskus ``` Or download [diskus-bin](https://aur.archlinux.org/packages/diskus-bin/) from the AUR. ### On Void-based systems ``` bash xbps-install diskus ``` ### On macOS You can install `diskus` with [Homebrew](https://formulae.brew.sh/formula/diskus): ``` brew install diskus ``` Or with [MacPorts](https://ports.macports.org/port/diskus/summary): ``` sudo port install diskus ``` ### On Haiku ``` bash pkgman install diskus ``` ### On NixOS ``` nix-env -iA nixos.diskus ``` Or add it to `environment.systemPackages` in your `configuration.nix`. ### On other systems Check out the [release page](https://github.com/sharkdp/diskus/releases) for binary builds. ### Via cargo If you have Rust 1.76 or higher, you can install `diskus` from source via `cargo`: ``` cargo install diskus ``` ## Directory counting `diskus` matches the behavior of `du` regarding directory entries: - **Disk usage mode** (default): Directories are included in the total size, matching `du -s`. - **Apparent size mode** (`-b`): Only files are counted, matching `du -sb`. You can override this with `--directories=included` or `--directories=excluded`. ## Windows caveats Windows-internal tools such as Powershell, Explorer or `dir` are not respecting hardlinks or junction points when determining the size of a directory. `diskus` does the same and counts such entries multiple times (on Unix systems, multiple hardlinks to a single file are counted just once). ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. diskus-0.9.0/ci/.gitattributes000064400000000000000000000000311046102023000144140ustar 00000000000000*.bash linguist-vendored diskus-0.9.0/doc/diskus.1000064400000000000000000000012661046102023000132720ustar 00000000000000.TH DISKUS "1" .SH NAME diskus - Compute disk usage for the given filesystem entries .SH SYNOPSIS .B diskus .RB [OPTIONS] .RB [path...] .SH OPTIONS .TP \fB\-j\fR, \fB\-\-threads\fR Set the number of threads (default: 3 x num cores) .TP \fB\-\-size\-format\fR Output format for file sizes (decimal: MB, binary: MiB) [default: decimal] [possible values: decimal, binary] .TP \fB\-v\fR, \fB\-\-verbose\fR Do not hide filesystem errors .TP \fB\-b\fR, \fB\-\-apparent\-size\fR Compute apparent size instead of disk usage .TP \fB\-h\fR, \fB\-\-help\fR Prints help information .TP \fB\-V\fR, \fB\-\-version\fR Prints version information .SH ARGUMENTS .TP ... List of filesystem paths diskus-0.9.0/src/filesize.rs000064400000000000000000000013701046102023000141040ustar 00000000000000#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum CountType { /// Count the disk usage of files (the actual space used on disk). #[default] DiskUsage, /// Count the apparent size of files (the number of bytes reported by `stat`). ApparentSize, } impl CountType { #[cfg(not(windows))] pub fn size(self, metadata: &std::fs::Metadata) -> u64 { use std::os::unix::fs::MetadataExt; match self { CountType::ApparentSize => metadata.len(), // block size is always 512 byte, see stat(2) manpage CountType::DiskUsage => metadata.blocks() * 512, } } #[cfg(windows)] pub fn size(self, metadata: &std::fs::Metadata) -> u64 { metadata.len() } } diskus-0.9.0/src/lib.rs000064400000000000000000000005161046102023000130410ustar 00000000000000//! # Basic usage //! //! ``` //! use diskus::DiskUsage; //! //! let result = DiskUsage::new(&["."]).count(); //! let size_in_bytes = result.ignore_errors().size_in_bytes(); //! ``` mod filesize; mod unique_id; pub mod walk; pub use crate::filesize::CountType; pub use crate::walk::{Directories, DiskUsage, DiskUsageResult, Error}; diskus-0.9.0/src/main.rs000064400000000000000000000105731046102023000132230ustar 00000000000000use std::path::PathBuf; use clap::{builder::PossibleValuesParser, Arg, ArgAction, Command}; use humansize::{format_size, FormatSizeOptions, BINARY, DECIMAL}; use num_format::{Locale, ToFormattedString}; use diskus::{CountType, Directories, DiskUsage, DiskUsageResult, Error}; fn print_result(result: &DiskUsageResult, size_format: FormatSizeOptions, verbose: bool) { if verbose { for err in result.errors() { match err { Error::NoMetadataForPath(path) => { eprintln!( "diskus: could not retrieve metadata for path '{}'", path.to_string_lossy() ); } Error::CouldNotReadDir(path) => { eprintln!( "diskus: could not read contents of directory '{}'", path.to_string_lossy() ); } } } } else if !result.is_ok() { eprintln!( "[diskus warning] the results may be tainted. Re-run with -v/--verbose to print all errors." ); } let size = result.ignore_errors().size_in_bytes(); if atty::is(atty::Stream::Stdout) { println!( "{} ({:} bytes)", format_size(size, size_format), size.to_formatted_string(&Locale::en) ); } else { println!("{}", size); } } fn main() { let cmd = Command::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .about("Compute disk usage for the given filesystem entries") .arg( Arg::new("path") .action(ArgAction::Append) .help("List of filesystem paths"), ) .arg( Arg::new("threads") .long("threads") .short('j') .value_name("N") .help("Set the number of threads (default: 3 x num cores)"), ) .arg( Arg::new("size-format") .long("size-format") .value_name("type") .value_parser(PossibleValuesParser::new(["decimal", "binary"])) .default_value("decimal") .help("Output format for file sizes (decimal: MB, binary: MiB)"), ) .arg( Arg::new("verbose") .long("verbose") .short('v') .action(ArgAction::SetTrue) .help("Do not hide filesystem errors"), ) .arg( Arg::new("directories") .long("directories") .value_name("mode") .value_parser(PossibleValuesParser::new(["auto", "included", "excluded"])) .default_value("auto") .help("Whether to count directory sizes (auto: included for disk usage, excluded for apparent size)"), ); #[cfg(not(windows))] let cmd = cmd.arg( Arg::new("apparent-size") .long("apparent-size") .short('b') .action(ArgAction::SetTrue) .help("Compute apparent size instead of disk usage"), ); let matches = cmd.get_matches(); let num_workers = matches .get_one::("threads") .and_then(|t| t.parse().ok()); let paths: Vec = matches .get_many::("path") .map(|paths| paths.map(PathBuf::from).collect()) .unwrap_or_else(|| vec![PathBuf::from(".")]); #[cfg(not(windows))] let count_type = if matches.get_flag("apparent-size") { CountType::ApparentSize } else { CountType::DiskUsage }; #[cfg(windows)] let count_type = CountType::DiskUsage; let size_format = match matches.get_one::("size-format").map(|s| s.as_str()) { Some("decimal") => DECIMAL, _ => BINARY, }; let verbose = matches.get_flag("verbose"); let directories = match matches.get_one::("directories").map(|s| s.as_str()) { Some("included") => Directories::Included, Some("excluded") => Directories::Excluded, _ => Directories::Auto, }; let mut disk_usage = DiskUsage::new(paths) .count_type(count_type) .directories(directories); if let Some(n) = num_workers { disk_usage = disk_usage.num_workers(n); } let result = disk_usage.count(); print_result(&result, size_format, verbose); } diskus-0.9.0/src/unique_id.rs000064400000000000000000000020501046102023000142500ustar 00000000000000#[derive(Eq, PartialEq, Hash)] pub struct UniqueID { device: u64, inode: u64, } #[cfg(not(windows))] pub fn generate_unique_id(metadata: &std::fs::Metadata) -> Option { use std::os::unix::fs::MetadataExt; // If the entry has more than one hard link, generate // a unique ID consisting of device and inode in order // not to count this entry twice. if metadata.is_file() && metadata.nlink() > 1 { Some(UniqueID { device: metadata.dev(), inode: metadata.ino(), }) } else { None } } #[cfg(windows)] pub fn generate_unique_id(_metadata: &std::fs::Metadata) -> Option { // Windows-internal tools such as Powershell, Explorer or `dir` are not respecting hardlinks // or junction points when determining the size of a directory. `diskus` does the same and // counts such entries multiple times (on Unix systems, multiple hardlinks to a single file are // counted just once). // // See: https://github.com/sharkdp/diskus/issues/32 None } diskus-0.9.0/src/walk.rs000064400000000000000000000177551046102023000132460ustar 00000000000000use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use std::thread; use crossbeam_channel as channel; use rayon::{self, prelude::*}; use crate::filesize::CountType; use crate::unique_id::{generate_unique_id, UniqueID}; /// Specifies whether directory sizes should be counted. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Directories { /// Automatically match `du` behavior based on the type of the size being counted: /// directories are included for disk usage, but excluded for apparent size. #[default] Auto, /// Count both files and directories (matches `du -s` behavior). Included, /// Count only files, not directories (matches `du -sb` behavior). Excluded, } #[derive(Debug)] pub enum Error { NoMetadataForPath(PathBuf), CouldNotReadDir(PathBuf), } /// The result of a disk usage computation. #[derive(Debug)] pub struct DiskUsageResult { size_in_bytes: u64, errors: Vec, } impl DiskUsageResult { /// Returns the total size in bytes, or the errors if any occurred. pub fn size_in_bytes(&self) -> Result { if self.errors.is_empty() { Ok(self.size_in_bytes) } else { Err(&self.errors) } } /// Ignore any errors and return a result that provides direct access to the size. pub fn ignore_errors(&self) -> UncheckedDiskUsageResult { UncheckedDiskUsageResult { size_in_bytes: self.size_in_bytes, } } /// Returns any errors encountered during traversal. pub fn errors(&self) -> &[Error] { &self.errors } /// Returns `true` if no errors occurred during traversal. pub fn is_ok(&self) -> bool { self.errors.is_empty() } } /// A disk usage result where errors have been explicitly ignored. #[derive(Debug)] pub struct UncheckedDiskUsageResult { size_in_bytes: u64, } impl UncheckedDiskUsageResult { /// Returns the total size in bytes. pub fn size_in_bytes(&self) -> u64 { self.size_in_bytes } } enum Message { SizeEntry(Option, u64), Error { error: Error }, } fn walk( tx: channel::Sender, entries: &[PathBuf], filesize_type: CountType, directories: Directories, ) { entries.into_par_iter().for_each_with(tx, |tx_ref, entry| { if let Ok(metadata) = entry.symlink_metadata() { let is_dir = metadata.is_dir(); let should_count = match directories { Directories::Included => true, Directories::Excluded => !is_dir, Directories::Auto => { // Auto mode matches `du` behavior: directories are included for // disk usage but excluded for apparent size. !is_dir || filesize_type == CountType::DiskUsage } }; if should_count { let unique_id = generate_unique_id(&metadata); let size = filesize_type.size(&metadata); tx_ref.send(Message::SizeEntry(unique_id, size)).unwrap(); } if is_dir { let mut children = vec![]; match fs::read_dir(entry) { Ok(child_entries) => { for child_entry in child_entries.flatten() { children.push(child_entry.path()); } } Err(_) => { tx_ref .send(Message::Error { error: Error::CouldNotReadDir(entry.clone()), }) .unwrap(); } } walk(tx_ref.clone(), &children[..], filesize_type, directories); }; } else { tx_ref .send(Message::Error { error: Error::NoMetadataForPath(entry.clone()), }) .unwrap(); }; }); } /// Configure and run a parallel directory walk to compute file system usage. pub struct DiskUsage { root_directories: Vec, num_workers: usize, count_type: CountType, directories: Directories, } impl DiskUsage { /// Create a new DiskUsage builder for the given root directories. pub fn new>(root_directories: impl IntoIterator) -> DiskUsage { DiskUsage { root_directories: root_directories .into_iter() .map(|p| p.as_ref().to_path_buf()) .collect(), num_workers: Self::default_num_workers(), count_type: CountType::default(), directories: Directories::default(), } } /// Returns the default number of workers (3 × number of CPU cores). /// /// This is a good tradeoff between cold-cache and warm-cache performance. /// For cold disk caches, more threads help the IO scheduler plan ahead. /// For warm caches, too many threads add synchronization overhead. /// /// fn default_num_workers() -> usize { 3 * std::thread::available_parallelism() .map(|n| n.get()) .unwrap_or(1) // To limit startup overhead on massively parallel machines, don't use more than 64 threads .min(64) } /// Set the number of workers to use for parallel traversal. /// /// By default, this is set to three times the number of CPU cores, which /// results in a good performance tradeoff for both cold and warm disk caches. pub fn num_workers(mut self, num_workers: usize) -> Self { self.num_workers = num_workers; self } /// Specify the type of the count (disk usage or apparent size). pub fn count_type(mut self, count_type: CountType) -> Self { self.count_type = count_type; self } /// Configure the count to use apparent size instead of disk usage. pub fn apparent_size(mut self) -> Self { self.count_type = CountType::ApparentSize; self } /// Set whether to count directory sizes. pub fn directories(mut self, directories: Directories) -> Self { self.directories = directories; self } /// Run the count and return the result. pub fn count(&self) -> DiskUsageResult { let (size_in_bytes, errors) = self.count_inner(); DiskUsageResult { size_in_bytes, errors, } } /// Run the count and return only the size, ignoring any errors. pub fn count_ignoring_errors(&self) -> u64 { self.count_inner().0 } fn count_inner(&self) -> (u64, Vec) { let (tx, rx) = channel::unbounded(); let receiver_thread = thread::spawn(move || { let mut total = 0; let mut ids = HashSet::new(); let mut errors: Vec = Vec::new(); for msg in rx { match msg { Message::SizeEntry(unique_id, size) => { if let Some(unique_id) = unique_id { // Only count this entry if the ID has not been seen if ids.insert(unique_id) { total += size; } } else { total += size; } } Message::Error { error } => { errors.push(error); } } } (total, errors) }); let pool = rayon::ThreadPoolBuilder::new() .num_threads(self.num_workers) .build() .unwrap(); pool.install(|| { walk( tx, &self.root_directories, self.count_type, self.directories, ) }); receiver_thread.join().unwrap() } } diskus-0.9.0/tests/walk.rs000064400000000000000000000015011046102023000135770ustar 00000000000000use std::error::Error; use std::fs::{self, File}; use std::io::Write; use tempdir::TempDir; use diskus::DiskUsage; #[test] fn size_of_files_in_nested_directories() -> Result<(), Box> { let tmp_dir = TempDir::new("diskus-tests")?; // Create a 100-byte file at the root let file1_path = tmp_dir.path().join("file-100-byte"); File::create(&file1_path)?.write_all(&[0u8; 100])?; // Create two nested directories and a 200-byte file inside let nested_dir = tmp_dir.path().join("dir1").join("dir2"); fs::create_dir_all(&nested_dir)?; let file2_path = nested_dir.join("file-200-byte"); File::create(&file2_path)?.write_all(&[0u8; 200])?; let result = DiskUsage::new(&[tmp_dir]).apparent_size().count(); assert_eq!(result.size_in_bytes().expect("no errors"), 300); Ok(()) }