[
  {
    "path": ".github/workflows/CICD.yml",
    "content": "name: CICD\n\n# spell-checker:ignore CICD CODECOV MSVC MacOS Peltoche SHAs buildable clippy esac fakeroot gnueabihf halium libssl mkdir musl popd printf pushd rustfmt softprops toolchain\n\nenv:\n  PROJECT_NAME: dust\n  PROJECT_DESC: \"du + rust = dust\"\n  PROJECT_AUTH: \"bootandy\"\n  RUST_MIN_SRV: \"1.31.0\"\n\non: [push, pull_request]\n\njobs:\n  style:\n    name: Style\n    runs-on: ${{ matrix.job.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        job:\n          - { os: ubuntu-latest }\n          - { os: macos-latest }\n          - { os: windows-latest }\n    steps:\n      - uses: actions/checkout@v1\n      - name: Initialize workflow variables\n        id: vars\n        shell: bash\n        run: |\n          # 'windows-latest' `cargo fmt` is bugged for this project (see reasons @ GH:rust-lang/rustfmt #3324, #3590, #3688 ; waiting for repair)\n          JOB_DO_FORMAT_TESTING=\"true\"\n          case ${{ matrix.job.os }} in windows-latest) unset JOB_DO_FORMAT_TESTING ;; esac;\n          echo set-output name=JOB_DO_FORMAT_TESTING::${JOB_DO_FORMAT_TESTING:-<empty>/false}\n          echo ::set-output name=JOB_DO_FORMAT_TESTING::${JOB_DO_FORMAT_TESTING}\n          # target-specific options\n          # * CARGO_FEATURES_OPTION\n          CARGO_FEATURES_OPTION='' ;\n          if [ -n \"${{ matrix.job.features }}\" ]; then CARGO_FEATURES_OPTION='--features \"${{ matrix.job.features }}\"' ; fi\n          echo set-output name=CARGO_FEATURES_OPTION::${CARGO_FEATURES_OPTION}\n          echo ::set-output name=CARGO_FEATURES_OPTION::${CARGO_FEATURES_OPTION}\n      - name: Install `rust` toolchain\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: stable\n          override: true\n          profile: minimal # minimal component installation (ie, no documentation)\n          components: rustfmt, clippy\n      - name: Install wget for Windows\n        if: matrix.job.os == 'windows-latest'\n        run: choco install wget --no-progress\n      - name: typos-action\n        uses: crate-ci/typos@v1.28.4\n      - name: \"`fmt` testing\"\n        if: steps.vars.outputs.JOB_DO_FORMAT_TESTING\n        uses: actions-rs/cargo@v1\n        with:\n          command: fmt\n          args: --all -- --check\n      - name: \"`clippy` testing\"\n        if: success() || failure() # run regardless of prior step (\"`fmt` testing\") success/failure\n        uses: actions-rs/cargo@v1\n        with:\n          command: clippy\n          args: ${{ matrix.job.cargo-options }} ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} -- -D warnings\n\n  min_version:\n    name: MinSRV # Minimum supported rust version\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v1\n      - name: Install `rust` toolchain (v${{ env.RUST_MIN_SRV }})\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: ${{ env.RUST_MIN_SRV }}\n          profile: minimal # minimal component installation (ie, no documentation)\n      - name: Test\n        uses: actions-rs/cargo@v1\n        with:\n          command: test\n\n  build:\n    name: Build\n    runs-on: ${{ matrix.job.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        job:\n          # { os, target, cargo-options, features, use-cross, toolchain }\n          - {\n              os: ubuntu-latest,\n              target: aarch64-unknown-linux-gnu,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: aarch64-unknown-linux-musl,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: arm-unknown-linux-gnueabihf,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: arm-unknown-linux-musleabi,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: i686-unknown-linux-gnu,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: i686-unknown-linux-musl,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: x86_64-unknown-linux-gnu,\n              use-cross: use-cross,\n            }\n          - {\n              os: ubuntu-latest,\n              target: x86_64-unknown-linux-musl,\n              use-cross: use-cross,\n            }\n          - { os: macos-latest, target: x86_64-apple-darwin }\n          - { os: windows-latest, target: i686-pc-windows-gnu }\n          - { os: windows-latest, target: i686-pc-windows-msvc }\n          - { os: windows-latest, target: x86_64-pc-windows-gnu } ## !maint: [rivy; 2020-01-21] may break due to rust bug; follow possible solution from GH:rust-lang/rust#47048 (refs: GH:rust-lang/rust#47048 , GH:rust-lang/rust#53454 , GH:bike-barn/hermit#172 )\n          - { os: windows-latest, target: x86_64-pc-windows-msvc }\n    steps:\n      - uses: actions/checkout@v1\n      - name: Install any prerequisites\n        shell: bash\n        run: |\n          case ${{ matrix.job.target }} in\n            arm-unknown-linux-gnueabihf) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;;\n            aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install binutils-aarch64-linux-gnu ;;\n          esac\n      - name: Initialize workflow variables\n        id: vars\n        shell: bash\n        run: |\n          # toolchain\n          TOOLCHAIN=\"stable\" ## default to \"stable\" toolchain\n          # * specify alternate TOOLCHAIN for *-pc-windows-gnu targets; gnu targets on Windows are broken for the standard *-pc-windows-msvc toolchain (refs: <https://github.com/rust-lang/rust/issues/47048>, <https://github.com/rust-lang/rust/issues/53454>, <https://github.com/rust-lang/cargo/issues/6754>)\n          case ${{ matrix.job.target }} in *-pc-windows-gnu) TOOLCHAIN=\"stable-${{ matrix.job.target }}\" ;; esac;\n          # * use requested TOOLCHAIN if specified\n          if [ -n \"${{ matrix.job.toolchain }}\" ]; then TOOLCHAIN=\"${{ matrix.job.toolchain }}\" ; fi\n          echo set-output name=TOOLCHAIN::${TOOLCHAIN}\n          echo ::set-output name=TOOLCHAIN::${TOOLCHAIN}\n          # staging directory\n          STAGING='_staging'\n          echo set-output name=STAGING::${STAGING}\n          echo ::set-output name=STAGING::${STAGING}\n          # determine EXE suffix\n          EXE_suffix=\"\" ; case ${{ matrix.job.target }} in *-pc-windows-*) EXE_suffix=\".exe\" ;; esac;\n          echo set-output name=EXE_suffix::${EXE_suffix}\n          echo ::set-output name=EXE_suffix::${EXE_suffix}\n          # parse commit reference info\n          REF_NAME=${GITHUB_REF#refs/*/}\n          unset REF_BRANCH ; case ${GITHUB_REF} in refs/heads/*) REF_BRANCH=${GITHUB_REF#refs/heads/} ;; esac;\n          unset REF_TAG ; case ${GITHUB_REF} in refs/tags/*) REF_TAG=${GITHUB_REF#refs/tags/} ;; esac;\n          REF_SHAS=${GITHUB_SHA:0:8}\n          echo set-output name=REF_NAME::${REF_NAME}\n          echo set-output name=REF_BRANCH::${REF_BRANCH}\n          echo set-output name=REF_TAG::${REF_TAG}\n          echo set-output name=REF_SHAS::${REF_SHAS}\n          echo ::set-output name=REF_NAME::${REF_NAME}\n          echo ::set-output name=REF_BRANCH::${REF_BRANCH}\n          echo ::set-output name=REF_TAG::${REF_TAG}\n          echo ::set-output name=REF_SHAS::${REF_SHAS}\n          # parse target\n          unset TARGET_ARCH ; case ${{ matrix.job.target }} in arm-unknown-linux-gnueabihf) TARGET_ARCH=arm ;; aarch-*) TARGET_ARCH=aarch64 ;; i686-*) TARGET_ARCH=i686 ;; x86_64-*) TARGET_ARCH=x86_64 ;; esac;\n          echo set-output name=TARGET_ARCH::${TARGET_ARCH}\n          echo ::set-output name=TARGET_ARCH::${TARGET_ARCH}\n          unset TARGET_OS ; case ${{ matrix.job.target }} in *-linux-*) TARGET_OS=linux ;; *-apple-*) TARGET_OS=macos ;; *-windows-*) TARGET_OS=windows ;; esac;\n          echo set-output name=TARGET_OS::${TARGET_OS}\n          echo ::set-output name=TARGET_OS::${TARGET_OS}\n          # package name\n          PKG_suffix=\".tar.gz\" ; case ${{ matrix.job.target }} in *-pc-windows-*) PKG_suffix=\".zip\" ;; esac;\n          PKG_BASENAME=${PROJECT_NAME}-${REF_TAG:-$REF_SHAS}-${{ matrix.job.target }}\n          PKG_NAME=${PKG_BASENAME}${PKG_suffix}\n          echo set-output name=PKG_suffix::${PKG_suffix}\n          echo set-output name=PKG_BASENAME::${PKG_BASENAME}\n          echo set-output name=PKG_NAME::${PKG_NAME}\n          echo ::set-output name=PKG_suffix::${PKG_suffix}\n          echo ::set-output name=PKG_BASENAME::${PKG_BASENAME}\n          echo ::set-output name=PKG_NAME::${PKG_NAME}\n          # deployable tag? (ie, leading \"vM\" or \"M\"; M == version number)\n          unset DEPLOY ; if [[ $REF_TAG =~ ^[vV]?[0-9].* ]]; then DEPLOY='true' ; fi\n          echo set-output name=DEPLOY::${DEPLOY:-<empty>/false}\n          echo ::set-output name=DEPLOY::${DEPLOY}\n          # target-specific options\n          # * CARGO_FEATURES_OPTION\n          CARGO_FEATURES_OPTION='' ;\n          if [ -n \"${{ matrix.job.features }}\" ]; then CARGO_FEATURES_OPTION='--features \"${{ matrix.job.features }}\"' ; fi\n          echo set-output name=CARGO_FEATURES_OPTION::${CARGO_FEATURES_OPTION}\n          echo ::set-output name=CARGO_FEATURES_OPTION::${CARGO_FEATURES_OPTION}\n          # * CARGO_USE_CROSS (truthy)\n          CARGO_USE_CROSS='true' ; case '${{ matrix.job.use-cross }}' in ''|0|f|false|n|no) unset CARGO_USE_CROSS ;; esac;\n          echo set-output name=CARGO_USE_CROSS::${CARGO_USE_CROSS:-<empty>/false}\n          echo ::set-output name=CARGO_USE_CROSS::${CARGO_USE_CROSS}\n          # # * `arm` cannot be tested on ubuntu-* hosts (b/c testing is currently primarily done via comparison of target outputs with built-in outputs and the `arm` target is not executable on the host)\n          JOB_DO_TESTING=\"true\"\n          case ${{ matrix.job.target }} in arm-*|aarch64-*) unset JOB_DO_TESTING ;; esac;\n          echo set-output name=JOB_DO_TESTING::${JOB_DO_TESTING:-<empty>/false}\n          echo ::set-output name=JOB_DO_TESTING::${JOB_DO_TESTING}\n          # # * test only binary for arm-type targets\n          unset CARGO_TEST_OPTIONS\n          unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-*|aarch64-*) CARGO_TEST_OPTIONS=\"--bin ${PROJECT_NAME}\" ;; esac;\n          echo set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS}\n          echo ::set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS}\n          # * strip executable?\n          STRIP=\"strip\" ; case ${{ matrix.job.target }} in arm-unknown-linux-gnueabihf) STRIP=\"arm-linux-gnueabihf-strip\" ;; *-pc-windows-msvc) STRIP=\"\" ;; aarch64-unknown-linux-gnu) STRIP=\"aarch64-linux-gnu-strip\" ;; aarch64-unknown-linux-musl) STRIP=\"\" ;; armv7-unknown-linux-musleabi) STRIP=\"\" ;; arm-unknown-linux-musleabi) STRIP=\"\" ;; esac;\n\n\n          echo set-output name=STRIP::${STRIP}\n          echo ::set-output name=STRIP::${STRIP}\n      - name: Create all needed build/work directories\n        shell: bash\n        run: |\n          mkdir -p '${{ steps.vars.outputs.STAGING }}'\n          mkdir -p '${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_BASENAME }}'\n      - name: rust toolchain ~ install\n        uses: actions-rs/toolchain@v1\n        with:\n          toolchain: ${{ steps.vars.outputs.TOOLCHAIN }}\n          target: ${{ matrix.job.target }}\n          override: true\n          profile: minimal # minimal component installation (ie, no documentation)\n      - name: Info\n        shell: bash\n        run: |\n          gcc --version || true\n          rustup -V\n          rustup toolchain list\n          rustup default\n          cargo -V\n          rustc -V\n      - name: Build\n        uses: actions-rs/cargo@v1\n        with:\n          use-cross: ${{ steps.vars.outputs.CARGO_USE_CROSS }}\n          command: build\n          args: --release --target=${{ matrix.job.target }} ${{ matrix.job.cargo-options }} ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }}\n      - name: Install cargo-deb\n        uses: actions-rs/cargo@v1\n        with:\n          command: install\n          args: cargo-deb\n        if: matrix.job.target == 'i686-unknown-linux-musl' || matrix.job.target == 'x86_64-unknown-linux-musl'\n      - name: Build deb\n        uses: actions-rs/cargo@v1\n        with:\n          command: deb\n          args: --no-build --target=${{ matrix.job.target }}\n        if: matrix.job.target == 'i686-unknown-linux-musl' || matrix.job.target == 'x86_64-unknown-linux-musl'\n      - name: Test\n        uses: actions-rs/cargo@v1\n        with:\n          use-cross: ${{ steps.vars.outputs.CARGO_USE_CROSS }}\n          command: test\n          args: --target=${{ matrix.job.target }} ${{ steps.vars.outputs.CARGO_TEST_OPTIONS}} ${{ matrix.job.cargo-options }} ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }}\n      - name: Archive executable artifacts\n        uses: actions/upload-artifact@master\n        with:\n          name: ${{ env.PROJECT_NAME }}-${{ matrix.job.target }}\n          path: target/${{ matrix.job.target }}/release/${{ env.PROJECT_NAME }}${{ steps.vars.outputs.EXE_suffix }}\n      - name: Archive deb artifacts\n        uses: actions/upload-artifact@master\n        with:\n          name: ${{ env.PROJECT_NAME }}-${{ matrix.job.target }}.deb\n          path: target/${{ matrix.job.target }}/debian\n        if: matrix.job.target == 'i686-unknown-linux-musl' || matrix.job.target == 'x86_64-unknown-linux-musl'\n      - name: Package\n        shell: bash\n        run: |\n          # binary\n          cp 'target/${{ matrix.job.target }}/release/${{ env.PROJECT_NAME }}${{ steps.vars.outputs.EXE_suffix }}' '${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_BASENAME }}/'\n          # `strip` binary (if needed)\n          if [ -n \"${{ steps.vars.outputs.STRIP }}\" ]; then \"${{ steps.vars.outputs.STRIP }}\" '${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_BASENAME }}/${{ env.PROJECT_NAME }}${{ steps.vars.outputs.EXE_suffix }}' ; fi\n          # README and LICENSE\n          cp README.md '${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_BASENAME }}/'\n          cp LICENSE '${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_BASENAME }}/'\n          # base compressed package\n          pushd '${{ steps.vars.outputs.STAGING }}/' >/dev/null\n          case ${{ matrix.job.target }} in\n            *-pc-windows-*) 7z -y a '${{ steps.vars.outputs.PKG_NAME }}' '${{ steps.vars.outputs.PKG_BASENAME }}'/* | tail -2 ;;\n            *) tar czf '${{ steps.vars.outputs.PKG_NAME }}' '${{ steps.vars.outputs.PKG_BASENAME }}'/* ;;\n          esac;\n          popd >/dev/null\n      - name: Publish\n        uses: softprops/action-gh-release@v1\n        if: steps.vars.outputs.DEPLOY\n        with:\n          files: |\n            ${{ steps.vars.outputs.STAGING }}/${{ steps.vars.outputs.PKG_NAME }}\n            target/${{ matrix.job.target }}/debian/*.deb\n\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n  ## fix! [rivy; 2020-22-01] `cargo tarpaulin` is unable to test this repo at the moment; alternate recipe or another testing framework?\n  # coverage:\n  #   name: Code Coverage\n  #   runs-on: ${{ matrix.job.os }}\n  #   strategy:\n  #     fail-fast: true\n  #     matrix:\n  #       # job: [ { os: ubuntu-latest }, { os: macos-latest }, { os: windows-latest } ]\n  #       job: [ { os: ubuntu-latest } ] ## cargo-tarpaulin is currently only available on linux\n  #   steps:\n  #   - uses: actions/checkout@v1\n  #   # - name: Reattach HEAD ## may be needed for accurate code coverage info\n  #   #   run: git checkout ${{ github.head_ref }}\n  #   - name: Initialize workflow variables\n  #     id: vars\n  #     shell: bash\n  #     run: |\n  #       # staging directory\n  #       STAGING='_staging'\n  #       echo set-output name=STAGING::${STAGING}\n  #       echo ::set-output name=STAGING::${STAGING}\n  #       # check for CODECOV_TOKEN availability (work-around for inaccessible 'secrets' object for 'if'; see <https://github.community/t5/GitHub-Actions/jobs-lt-job-id-gt-if-does-not-work-with-env-secrets/m-p/38549>)\n  #       unset HAS_CODECOV_TOKEN\n  #       if [ -n $CODECOV_TOKEN ]; then HAS_CODECOV_TOKEN='true' ; fi\n  #       echo set-output name=HAS_CODECOV_TOKEN::${HAS_CODECOV_TOKEN}\n  #       echo ::set-output name=HAS_CODECOV_TOKEN::${HAS_CODECOV_TOKEN}\n  #     env:\n  #       CODECOV_TOKEN: \"${{ secrets.CODECOV_TOKEN }}\"\n  #   - name: Create all needed build/work directories\n  #     shell: bash\n  #     run: |\n  #       mkdir -p '${{ steps.vars.outputs.STAGING }}/work'\n  #   - name: Install required packages\n  #     run: |\n  #       sudo apt-get -y install libssl-dev\n  #       pushd '${{ steps.vars.outputs.STAGING }}/work' >/dev/null\n  #       wget --no-verbose https://github.com/xd009642/tarpaulin/releases/download/0.9.3/cargo-tarpaulin-0.9.3-travis.tar.gz\n  #       tar xf cargo-tarpaulin-0.9.3-travis.tar.gz\n  #       cp cargo-tarpaulin \"$(dirname -- \"$(which cargo)\")\"/\n  #       popd >/dev/null\n  #   - name: Generate coverage\n  #     run: |\n  #       cargo tarpaulin --out Xml\n  #   - name: Upload coverage results (CodeCov.io)\n  #     # CODECOV_TOKEN (aka, \"Repository Upload Token\" for REPO from CodeCov.io) ## set via REPO/Settings/Secrets\n  #     # if: secrets.CODECOV_TOKEN (not supported {yet?}; see <https://github.community/t5/GitHub-Actions/jobs-lt-job-id-gt-if-does-not-work-with-env-secrets/m-p/38549>)\n  #     if: steps.vars.outputs.HAS_CODECOV_TOKEN\n  #     run: |\n  #       # CodeCov.io\n  #       cargo tarpaulin --out Xml\n  #       bash <(curl -s https://codecov.io/bash)\n  #     env:\n  #       CODECOV_TOKEN: \"${{ secrets.CODECOV_TOKEN }}\"\n"
  },
  {
    "path": ".gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\n/target/\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n*.swp\n.vscode/*\n*.idea/*\n\n#ignore macos files\n.DS_Store"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n  - repo: https://github.com/doublify/pre-commit-rust\n    rev: v1.0\n    hooks:\n      - id: cargo-check\n        stages: [commit]\n      - id: fmt\n        stages: [commit]\n      - id: clippy\n        args: [--all-targets, --all-features]\n        stages: [commit]\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"du-dust\"\ndescription = \"A more intuitive version of du\"\nversion = \"1.2.4\"\nauthors = [\"bootandy <bootandy@gmail.com>\", \"nebkor <code@ardent.nebcorp.com>\"]\nedition = \"2024\"\nreadme = \"README.md\"\n\ndocumentation = \"https://github.com/bootandy/dust\"\nhomepage = \"https://github.com/bootandy/dust\"\nrepository = \"https://github.com/bootandy/dust\"\n\nkeywords = [\"du\", \"command-line\", \"disk\", \"disk-usage\"]\ncategories = [\"command-line-utilities\"]\nlicense = \"Apache-2.0\"\n\n[badges]\ntravis-ci = { repository = \"https://travis-ci.org/bootandy/dust\" }\n\n[[bin]]\nname = \"dust\"\npath = \"src/main.rs\"\n\n[profile.release]\ncodegen-units = 1\nlto = true\nstrip = true\n\n[dependencies]\nclap = { version = \"4\", features = [\"derive\"] }\nlscolors = \"0.21\"\nnu-ansi-term = \"0.50\"\nterminal_size = \"0.4\"\nunicode-width = \"0.2\"\nrayon = \"1\"\nthousands = \"0.2\"\nstfu8 = \"0.2\"\nregex = \"1\"\nconfig-file = \"0.2\"\nserde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"\nsysinfo = \"0.37\"\nctrlc = \"3\"\nchrono = \"0.4\"\n\n[target.'cfg(not(target_has_atomic = \"64\"))'.dependencies]\nportable-atomic = \"1.4\"\n\n[target.'cfg(windows)'.dependencies]\nwinapi-util = \"0.1\"\nfilesize = \"0.2.0\"\n\n[dev-dependencies]\nassert_cmd = \"2\"\ntempfile = \"=3\"\n\n[build-dependencies]\nclap = { version = \"4.4\", features = [\"derive\"] }\nclap_complete = \"4.4\"\nclap_mangen = \"0.2\"\n\n[[test]]\nname = \"integration\"\npath = \"tests/tests.rs\"\n\n[package.metadata.binstall]\npkg-url = \"{ repo }/releases/download/v{ version }/dust-v{ version }-{ target }{ archive-suffix }\"\nbin-dir = \"dust-v{ version }-{ target }/{ bin }{ binary-ext }\"\n\n[package.metadata.deb]\nsection = \"utils\"\nassets = [\n  [\n    \"target/release/dust\",\n    \"usr/bin/\",\n    \"755\",\n  ],\n  [\n    \"LICENSE\",\n    \"usr/share/doc/du-dust/\",\n    \"644\",\n  ],\n  [\n    \"README.md\",\n    \"usr/share/doc/du-dust/README\",\n    \"644\",\n  ],\n  [\n    \"man-page/dust.1\",\n    \"usr/share/man/man1/dust.1\",\n    \"644\",\n  ],\n  [\n    \"completions/dust.bash\",\n    \"usr/share/bash-completion/completions/dust\",\n    \"644\",\n  ],\n]\nextended-description = \"\"\"\\\nDust is meant to give you an instant overview of which directories are using\ndisk space without requiring sort or head. Dust will print a maximum of one\n'Did not have permissions message'.\n\"\"\"\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [2023] [andrew boot]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "[![Build Status](https://github.com/bootandy/dust/actions/workflows/CICD.yml/badge.svg)](https://github.com/bootandy/dust/actions)\n\n\n# Dust\n\ndu + rust = dust. Like du but more intuitive.\n\n# Why\n\nBecause I want an easy way to see where my disk is being used.\n\n# Demo\n\n![Example](media/snap.png)\n\nStudy the above picture. \n\n* We see `target` has 1.8G\n* `target/debug` is the same size as `target` - so we know nearly all the disk usage of the 1.8G is in this folder\n* `target/debug/deps` this is 1.2G - Note the bar jumps down to 70% to indicate that most disk usage is here but not all.\n* `target/debug/deps/dust-e78c9f87a17f24f3` - This is the largest file in this folder, but it is only 46M - Note the bar jumps down to 3% to indicate the file is small.\n\nFrom here we can conclude:\n * `target/debug/deps` takes the majority of the space in `target` and that `target/debug/deps` has a large number of relatively small files.\n  \n\n## Install\n\n### Quick Install (Linux, macOS, Windows) \n```bash\ncurl -sSfL https://raw.githubusercontent.com/bootandy/dust/refs/heads/master/install.sh | sh\n```\n\n### Cargo <a href=\"https://repology.org/project/du-dust/versions\"><img src=\"https://repology.org/badge/vertical-allrepos/du-dust.svg\" alt=\"Packaging status\" align=\"right\"></a>\n\n#### Cargo\n\n- `cargo install du-dust`\n\n#### 🍺 Homebrew (Mac OS)\n\n- `brew install dust`\n\n#### 🍺 Homebrew (Linux)\n\n- `brew install dust`\n\n#### [Snap](https://ubuntu.com/core/services/guide/snaps-intro) Ubuntu and [supported systems](https://snapcraft.io/docs/installing-snapd)\n\n- `snap install dust`\n\nNote: `dust` installed through `snap` can only access files stored in the `/home` directory. See daniejstriata/dust-snap#2 for more information.\n\n#### [Pacstall](https://github.com/pacstall/pacstall) (Debian/Ubuntu)\n\n- `pacstall -I dust-bin`\n\n#### Anaconda (conda-forge)\n\n- `conda install -c conda-forge dust`\n\n#### [deb-get](https://github.com/wimpysworld/deb-get) (Debian/Ubuntu)\n\n- `deb-get install du-dust`\n\n#### [x-cmd](https://www.x-cmd.com/pkg/#VPContent)\n\n- `x env use dust`\n\n#### Windows:\n\n- `scoop install dust`\n- Windows GNU version - works\n- Windows MSVC - requires: [VCRUNTIME140.dll](https://docs.microsoft.com/en-gb/cpp/windows/latest-supported-vc-redist?view=msvc-170)\n\n#### Download\n\n- Download Linux/Mac binary from [Releases](https://github.com/bootandy/dust/releases)\n- unzip file: `tar -xvf _downloaded_file.tar.gz`\n- move file to executable path: `sudo mv dust /usr/local/bin/`\n\n## Overview\n\nDust is meant to give you an instant overview of which directories are using disk space without requiring sort or head. Dust will print a maximum of one 'Did not have permissions message'.\n\nDust will list a slightly-less-than-the-terminal-height number of the biggest subdirectories or files and will smartly recurse down the tree to find the larger ones. There is no need for a '-d' flag or a '-h' flag. The largest subdirectories will be colored.\n\nThe different colors on the bars: These represent the combined tree hierarchy & disk usage. The shades of grey are used to indicate which parent folder a subfolder belongs to. For instance, look at the above screenshot. `.steam` is a folder taking 44% of the space. From the `.steam` bar is a light grey line that goes up. All these folders are inside `.steam` so if you delete `.steam` all that stuff will be gone too.\n\nIf you are new to the tool I recommend to try tweaking the `-n` parameter. `dust -n 10`, `dust -n 50`.\n\n## Usage\n\n```\nUsage: dust\nUsage: dust <dir>\nUsage: dust <dir>  <another_dir> <and_more>\nUsage: dust -p (full-path - Show fullpath of the subdirectories)\nUsage: dust -s (apparent-size - shows the length of the file as opposed to the amount of disk space it uses)\nUsage: dust -n 30  (Shows 30 directories instead of the default [default is terminal height])\nUsage: dust -d 3  (Shows 3 levels of subdirectories)\nUsage: dust -D (Show only directories (eg dust -D))\nUsage: dust -F (Show only files - finds your largest files)\nUsage: dust -r (reverse order of output)\nUsage: dust -o si/b/kb/kib/mb/mib/gb/gib (si - prints sizes in powers of 1000. Others print size in that format).\nUsage: dust -X ignore  (ignore all files and directories with the name 'ignore')\nUsage: dust -x (Only show directories on the same filesystem)\nUsage: dust -b (Do not show percentages or draw ASCII bars)\nUsage: dust -B (--bars-on-right - Percent bars moved to right side of screen)\nUsage: dust -i (Do not show hidden files)\nUsage: dust -c (No colors [monochrome])\nUsage: dust -C (Force colors)\nUsage: dust -f (Count files instead of diskspace [Counts by inode, to include duplicate inodes use dust -f -s])\nUsage: dust -t (Group by filetype)\nUsage: dust -z 10M (min-size, Only include files larger than 10M)\nUsage: dust -e regex (Only include files matching this regex (eg dust -e \"\\.png$\" would match png files))\nUsage: dust -v regex (Exclude files matching this regex (eg dust -v \"\\.png$\" would ignore png files))\nUsage: dust -L (dereference-links - Treat sym links as directories and go into them)\nUsage: dust -P (Disable the progress indicator)\nUsage: dust -R (For screen readers. Removes bars/symbols. Adds new column: depth level. (May want to use -p for full path too))\nUsage: dust -S (Custom Stack size - Use if you see: 'fatal runtime error: stack overflow' (default allocation: low memory=1048576, high memory=1073741824)\"),\nUsage: dust --skip-total (No total row will be displayed)\nUsage: dust -z 40000/30MB/20kib (Exclude output files/directories below size 40000 bytes / 30MB / 20KiB)\nUsage: dust -j (Prints JSON representation of directories, try: dust -j  | jq)\nUsage: dust --files0-from=FILE (Read NUL-terminated file paths from FILE; if FILE is '-', read from stdin)\nUsage: dust --files-from=FILE (Read newline-terminated file paths from FILE; if FILE is '-', read from stdin)\nUsage: dust --collapse=node-modules will keep the node-modules folder collapsed in display instead of recursively opening it\n```\n\n## Config file\n\nDust has a config file where the above options can be set.\nEither: `~/.config/dust/config.toml` or `~/.dust.toml`\n```\n$ cat ~/.config/dust/config.toml\nreverse=true\n```\n\n## Alternatives\n\n- [NCDU](https://dev.yorhel.nl/ncdu)\n- [dutree](https://github.com/nachoparker/dutree)\n- [dua](https://github.com/Byron/dua-cli/)\n- [pdu](https://github.com/KSXGitHub/parallel-disk-usage)\n- [dirstat-rs](https://github.com/scullionw/dirstat-rs)\n- `du -d 1 -h | sort -h`\n\n## Why to use Dust over the Alternatives\n\nDust simply Does The Right Thing when handling lots of small files & directories. Dust keeps the output simple by only showing large entries.\n\nTools like ncdu & baobab, give you a view of directory sizes but you have no idea where the largest files are. For example directory A could have a size larger than directory B, but in fact the largest file is in B and not A. Finding this out via these other tools is not trivial whereas Dust will show the large file clearly in the tree hierarchy \n\nDust will not count hard links multiple times (unless you want to `-s`).\n\nTyping `dust -n 90` will show you your 90 largest entries. `-n` is not quite like `head -n` or `tail -n`, dust is intelligent and chooses the largest entries\n\n\n"
  },
  {
    "path": "build.rs",
    "content": "use clap::CommandFactory;\nuse clap_complete::{generate_to, shells::*};\nuse clap_mangen::Man;\nuse std::fs::File;\nuse std::io::Error;\nuse std::path::Path;\n\ninclude!(\"src/cli.rs\");\n\nfn main() -> Result<(), Error> {\n    let outdir = \"completions\";\n    let app_name = \"dust\";\n    let mut cmd = Cli::command();\n\n    generate_to(Bash, &mut cmd, app_name, outdir)?;\n    generate_to(Zsh, &mut cmd, app_name, outdir)?;\n    generate_to(Fish, &mut cmd, app_name, outdir)?;\n    generate_to(PowerShell, &mut cmd, app_name, outdir)?;\n    generate_to(Elvish, &mut cmd, app_name, outdir)?;\n\n    let file = Path::new(\"man-page\").join(\"dust.1\");\n    std::fs::create_dir_all(\"man-page\")?;\n    let mut file = File::create(file)?;\n\n    Man::new(cmd).render(&mut file)?;\n\n    Ok(())\n}\n"
  },
  {
    "path": "ci/before_deploy.ps1",
    "content": "# This script takes care of packaging the build artifacts that will go in the\n# release zipfile\n\n$SRC_DIR = $PWD.Path\n$STAGE = [System.Guid]::NewGuid().ToString()\n\nSet-Location $ENV:Temp\nNew-Item -Type Directory -Name $STAGE\nSet-Location $STAGE\n\n$ZIP = \"$SRC_DIR\\$($Env:CRATE_NAME)-$($Env:APPVEYOR_REPO_TAG_NAME)-$($Env:TARGET).zip\"\n\n# TODO Update this to package the right artifacts\nCopy-Item \"$SRC_DIR\\target\\$($Env:TARGET)\\release\\dust\" '.\\'\n\n7z a \"$ZIP\" *\n\nPush-AppveyorArtifact \"$ZIP\"\n\nRemove-Item *.* -Force\nSet-Location ..\nRemove-Item $STAGE\nSet-Location $SRC_DIR\n"
  },
  {
    "path": "ci/before_deploy.sh",
    "content": "#!/usr/bin/env bash\n# This script takes care of building your crate and packaging it for release\n\nset -ex\n\nmain() {\n    local src=$(pwd) \\\n          stage=\n\n    case $TRAVIS_OS_NAME in\n        linux)\n            stage=$(mktemp -d)\n            ;;\n        osx)\n            stage=$(mktemp -d -t tmp)\n            ;;\n    esac\n\n    test -f Cargo.lock || cargo generate-lockfile\n\n    # TODO Update this to build the artifacts that matter to you\n    cross rustc --bin dust --target $TARGET --release -- -C lto\n\n    # TODO Update this to package the right artifacts\n    cp target/$TARGET/release/dust $stage/\n\n    cd $stage\n    tar czf $src/$CRATE_NAME-$TRAVIS_TAG-$TARGET.tar.gz *\n    cd $src\n\n    rm -rf $stage\n}\n\nmain\n"
  },
  {
    "path": "ci/how2publish.txt",
    "content": "# ----------- To do a release ---------\n\n# ----------- Pre release ---------\n# Compare times of runs to check no drastic slow down:\n#  hyperfine 'target/release/dust /home/andy'\n#  hyperfine 'dust /home/andy'\n\n# ----------- Release ---------\n# inc version in cargo.toml\n# cargo build --release\n# commit changed files\n# merge to master in github\n\n# tag a commit and push (increment version in Cargo.toml first):\n#   git tag v0.4.5\n#   git push origin v0.4.5\n\n# cargo publish to put it in crates.io\n \n# Optional: To install locally\n#cargo install --path .\n"
  },
  {
    "path": "ci/install.sh",
    "content": "#!/usr/bin/env bash\nset -ex\n\nmain() {\n    local target=\n    if [ $TRAVIS_OS_NAME = linux ]; then\n        target=x86_64-unknown-linux-musl\n        sort=sort\n    else\n        target=x86_64-apple-darwin\n        sort=gsort  # for `sort --sort-version`, from brew's coreutils.\n    fi\n\n    # This fetches latest stable release\n    local tag=$(git ls-remote --tags --refs --exit-code https://github.com/japaric/cross \\\n                       | cut -d/ -f3 \\\n                       | grep -E '^v[0.1.0-9.]+$' \\\n                       | $sort --version-sort \\\n                       | tail -n1)\n    curl -LSfs https://japaric.github.io/trust/install.sh | \\\n        sh -s -- \\\n           --force \\\n           --git japaric/cross \\\n           --tag $tag \\\n           --target $target\n}\n\nmain\n"
  },
  {
    "path": "ci/script.sh",
    "content": "#!/usr/bin/env bash\n# This script takes care of testing your crate\n\nset -ex\n\n# TODO This is the \"test phase\", tweak it as you see fit\nmain() {\n    cross build --target $TARGET\n    cross build --target $TARGET --release\n\n    if [ ! -z $DISABLE_TESTS ]; then\n        return\n    fi\n\n    cross test --target $TARGET\n    cross test --target $TARGET --release\n\n    cross run --target $TARGET\n    cross run --target $TARGET --release\n}\n\n# we don't run the \"test phase\" when doing deploys\nif [ -z $TRAVIS_TAG ]; then\n    main\nfi\n"
  },
  {
    "path": "completions/_dust",
    "content": "#compdef dust\n\nautoload -U is-at-least\n\n_dust() {\n    typeset -A opt_args\n    typeset -a _arguments_options\n    local ret=1\n\n    if is-at-least 5.2; then\n        _arguments_options=(-s -S -C)\n    else\n        _arguments_options=(-s -C)\n    fi\n\n    local context curcontext=\"$curcontext\" state line\n    _arguments \"${_arguments_options[@]}\" : \\\n'-d+[Depth to show]:DEPTH:_default' \\\n'--depth=[Depth to show]:DEPTH:_default' \\\n'-T+[Number of threads to use]:THREADS:_default' \\\n'--threads=[Number of threads to use]:THREADS:_default' \\\n'--config=[Specify a config file to use]:FILE:_files' \\\n'-n+[Display the '\\''n'\\'' largest entries. (Default is terminal_height)]:NUMBER:_default' \\\n'--number-of-lines=[Display the '\\''n'\\'' largest entries. (Default is terminal_height)]:NUMBER:_default' \\\n'*-X+[Exclude any file or directory with this path]:PATH:_files' \\\n'*--ignore-directory=[Exclude any file or directory with this path]:PATH:_files' \\\n'-I+[Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter]:FILE:_files' \\\n'--ignore-all-in-file=[Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter]:FILE:_files' \\\n'-z+[Minimum size file to include in output]:MIN_SIZE:_default' \\\n'--min-size=[Minimum size file to include in output]:MIN_SIZE:_default' \\\n'(-e --filter -t --file-types)*-v+[Exclude filepaths matching this regex. To ignore png files type\\: -v \"\\\\.png\\$\"]:REGEX:_default' \\\n'(-e --filter -t --file-types)*--invert-filter=[Exclude filepaths matching this regex. To ignore png files type\\: -v \"\\\\.png\\$\"]:REGEX:_default' \\\n'(-t --file-types)*-e+[Only include filepaths matching this regex. For png files type\\: -e \"\\\\.png\\$\"]:REGEX:_default' \\\n'(-t --file-types)*--filter=[Only include filepaths matching this regex. For png files type\\: -e \"\\\\.png\\$\"]:REGEX:_default' \\\n'-w+[Specify width of output overriding the auto detection of terminal width]:WIDTH:_default' \\\n'--terminal-width=[Specify width of output overriding the auto detection of terminal width]:WIDTH:_default' \\\n'-o+[Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size]:FORMAT:((si\\:\"SI prefix (powers of 1000)\"\nb\\:\"byte (B)\"\nk\\:\"kibibyte (KiB)\"\nm\\:\"mebibyte (MiB)\"\ng\\:\"gibibyte (GiB)\"\nt\\:\"tebibyte (TiB)\"\nkb\\:\"kilobyte (kB)\"\nmb\\:\"megabyte (MB)\"\ngb\\:\"gigabyte (GB)\"\ntb\\:\"terabyte (TB)\"))' \\\n'--output-format=[Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size]:FORMAT:((si\\:\"SI prefix (powers of 1000)\"\nb\\:\"byte (B)\"\nk\\:\"kibibyte (KiB)\"\nm\\:\"mebibyte (MiB)\"\ng\\:\"gibibyte (GiB)\"\nt\\:\"tebibyte (TiB)\"\nkb\\:\"kilobyte (kB)\"\nmb\\:\"megabyte (MB)\"\ngb\\:\"gigabyte (GB)\"\ntb\\:\"terabyte (TB)\"))' \\\n'-S+[Specify memory to use as stack size - use if you see\\: '\\''fatal runtime error\\: stack overflow'\\'' (default low memory=1048576, high memory=1073741824)]:STACK_SIZE:_default' \\\n'--stack-size=[Specify memory to use as stack size - use if you see\\: '\\''fatal runtime error\\: stack overflow'\\'' (default low memory=1048576, high memory=1073741824)]:STACK_SIZE:_default' \\\n'-M+[+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => \\[curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)]:MTIME:_default' \\\n'--mtime=[+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => \\[curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)]:MTIME:_default' \\\n'-A+[just like -mtime, but based on file access time]:ATIME:_default' \\\n'--atime=[just like -mtime, but based on file access time]:ATIME:_default' \\\n'-y+[just like -mtime, but based on file change time]:CTIME:_default' \\\n'--ctime=[just like -mtime, but based on file change time]:CTIME:_default' \\\n'(--files-from)--files0-from=[Read NUL-terminated paths from FILE (use \\`-\\` for stdin)]:FILES0_FROM:_files' \\\n'(--files0-from)--files-from=[Read newline-terminated paths from FILE (use \\`-\\` for stdin)]:FILES_FROM:_files' \\\n'*--collapse=[Keep these directories collapsed]:COLLAPSE:_files' \\\n'-m+[Directory '\\''size'\\'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time]:FILETIME:((a\\:\"last accessed time\"\nc\\:\"last changed time\"\nm\\:\"last modified time\"))' \\\n'--filetime=[Directory '\\''size'\\'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time]:FILETIME:((a\\:\"last accessed time\"\nc\\:\"last changed time\"\nm\\:\"last modified time\"))' \\\n'-p[Subdirectories will not have their path shortened]' \\\n'--full-paths[Subdirectories will not have their path shortened]' \\\n'-L[dereference sym links - Treat sym links as directories and go into them]' \\\n'--dereference-links[dereference sym links - Treat sym links as directories and go into them]' \\\n'-x[Only count the files and directories on the same filesystem as the supplied directory]' \\\n'--limit-filesystem[Only count the files and directories on the same filesystem as the supplied directory]' \\\n'-s[Use file length instead of blocks]' \\\n'--apparent-size[Use file length instead of blocks]' \\\n'-r[Print tree upside down (biggest highest)]' \\\n'--reverse[Print tree upside down (biggest highest)]' \\\n'-c[No colors will be printed (Useful for commands like\\: watch)]' \\\n'--no-colors[No colors will be printed (Useful for commands like\\: watch)]' \\\n'-C[Force colors print]' \\\n'--force-colors[Force colors print]' \\\n'-b[No percent bars or percentages will be displayed]' \\\n'--no-percent-bars[No percent bars or percentages will be displayed]' \\\n'-B[percent bars moved to right side of screen]' \\\n'--bars-on-right[percent bars moved to right side of screen]' \\\n'-R[For screen readers. Removes bars. Adds new column\\: depth level (May want to use -p too for full path)]' \\\n'--screen-reader[For screen readers. Removes bars. Adds new column\\: depth level (May want to use -p too for full path)]' \\\n'--skip-total[No total row will be displayed]' \\\n'-f[Directory '\\''size'\\'' is number of child files instead of disk size]' \\\n'--filecount[Directory '\\''size'\\'' is number of child files instead of disk size]' \\\n'-i[Do not display hidden files]' \\\n'--ignore-hidden[Do not display hidden files]' \\\n'(-d --depth -D --only-dir)-t[show only these file types]' \\\n'(-d --depth -D --only-dir)--file-types[show only these file types]' \\\n'-P[Disable the progress indication]' \\\n'--no-progress[Disable the progress indication]' \\\n'--print-errors[Print path with errors]' \\\n'(-F --only-file -t --file-types)-D[Only directories will be displayed]' \\\n'(-F --only-file -t --file-types)--only-dir[Only directories will be displayed]' \\\n'(-D --only-dir)-F[Only files will be displayed. (Finds your largest files)]' \\\n'(-D --only-dir)--only-file[Only files will be displayed. (Finds your largest files)]' \\\n'-j[Output the directory tree as json to the current directory]' \\\n'--output-json[Output the directory tree as json to the current directory]' \\\n'-h[Print help (see more with '\\''--help'\\'')]' \\\n'--help[Print help (see more with '\\''--help'\\'')]' \\\n'-V[Print version]' \\\n'--version[Print version]' \\\n'*::params -- Input files or directories:_files' \\\n&& ret=0\n}\n\n(( $+functions[_dust_commands] )) ||\n_dust_commands() {\n    local commands; commands=()\n    _describe -t commands 'dust commands' commands \"$@\"\n}\n\nif [ \"$funcstack[1]\" = \"_dust\" ]; then\n    _dust \"$@\"\nelse\n    compdef _dust dust\nfi\n"
  },
  {
    "path": "completions/_dust.ps1",
    "content": "\nusing namespace System.Management.Automation\nusing namespace System.Management.Automation.Language\n\nRegister-ArgumentCompleter -Native -CommandName 'dust' -ScriptBlock {\n    param($wordToComplete, $commandAst, $cursorPosition)\n\n    $commandElements = $commandAst.CommandElements\n    $command = @(\n        'dust'\n        for ($i = 1; $i -lt $commandElements.Count; $i++) {\n            $element = $commandElements[$i]\n            if ($element -isnot [StringConstantExpressionAst] -or\n                $element.StringConstantType -ne [StringConstantType]::BareWord -or\n                $element.Value.StartsWith('-') -or\n                $element.Value -eq $wordToComplete) {\n                break\n        }\n        $element.Value\n    }) -join ';'\n\n    $completions = @(switch ($command) {\n        'dust' {\n            [CompletionResult]::new('-d', '-d', [CompletionResultType]::ParameterName, 'Depth to show')\n            [CompletionResult]::new('--depth', '--depth', [CompletionResultType]::ParameterName, 'Depth to show')\n            [CompletionResult]::new('-T', '-T ', [CompletionResultType]::ParameterName, 'Number of threads to use')\n            [CompletionResult]::new('--threads', '--threads', [CompletionResultType]::ParameterName, 'Number of threads to use')\n            [CompletionResult]::new('--config', '--config', [CompletionResultType]::ParameterName, 'Specify a config file to use')\n            [CompletionResult]::new('-n', '-n', [CompletionResultType]::ParameterName, 'Display the ''n'' largest entries. (Default is terminal_height)')\n            [CompletionResult]::new('--number-of-lines', '--number-of-lines', [CompletionResultType]::ParameterName, 'Display the ''n'' largest entries. (Default is terminal_height)')\n            [CompletionResult]::new('-X', '-X ', [CompletionResultType]::ParameterName, 'Exclude any file or directory with this path')\n            [CompletionResult]::new('--ignore-directory', '--ignore-directory', [CompletionResultType]::ParameterName, 'Exclude any file or directory with this path')\n            [CompletionResult]::new('-I', '-I ', [CompletionResultType]::ParameterName, 'Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter')\n            [CompletionResult]::new('--ignore-all-in-file', '--ignore-all-in-file', [CompletionResultType]::ParameterName, 'Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter')\n            [CompletionResult]::new('-z', '-z', [CompletionResultType]::ParameterName, 'Minimum size file to include in output')\n            [CompletionResult]::new('--min-size', '--min-size', [CompletionResultType]::ParameterName, 'Minimum size file to include in output')\n            [CompletionResult]::new('-v', '-v', [CompletionResultType]::ParameterName, 'Exclude filepaths matching this regex. To ignore png files type: -v \"\\.png$\"')\n            [CompletionResult]::new('--invert-filter', '--invert-filter', [CompletionResultType]::ParameterName, 'Exclude filepaths matching this regex. To ignore png files type: -v \"\\.png$\"')\n            [CompletionResult]::new('-e', '-e', [CompletionResultType]::ParameterName, 'Only include filepaths matching this regex. For png files type: -e \"\\.png$\"')\n            [CompletionResult]::new('--filter', '--filter', [CompletionResultType]::ParameterName, 'Only include filepaths matching this regex. For png files type: -e \"\\.png$\"')\n            [CompletionResult]::new('-w', '-w', [CompletionResultType]::ParameterName, 'Specify width of output overriding the auto detection of terminal width')\n            [CompletionResult]::new('--terminal-width', '--terminal-width', [CompletionResultType]::ParameterName, 'Specify width of output overriding the auto detection of terminal width')\n            [CompletionResult]::new('-o', '-o', [CompletionResultType]::ParameterName, 'Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size')\n            [CompletionResult]::new('--output-format', '--output-format', [CompletionResultType]::ParameterName, 'Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size')\n            [CompletionResult]::new('-S', '-S ', [CompletionResultType]::ParameterName, 'Specify memory to use as stack size - use if you see: ''fatal runtime error: stack overflow'' (default low memory=1048576, high memory=1073741824)')\n            [CompletionResult]::new('--stack-size', '--stack-size', [CompletionResultType]::ParameterName, 'Specify memory to use as stack size - use if you see: ''fatal runtime error: stack overflow'' (default low memory=1048576, high memory=1073741824)')\n            [CompletionResult]::new('-M', '-M ', [CompletionResultType]::ParameterName, '+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)')\n            [CompletionResult]::new('--mtime', '--mtime', [CompletionResultType]::ParameterName, '+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)')\n            [CompletionResult]::new('-A', '-A ', [CompletionResultType]::ParameterName, 'just like -mtime, but based on file access time')\n            [CompletionResult]::new('--atime', '--atime', [CompletionResultType]::ParameterName, 'just like -mtime, but based on file access time')\n            [CompletionResult]::new('-y', '-y', [CompletionResultType]::ParameterName, 'just like -mtime, but based on file change time')\n            [CompletionResult]::new('--ctime', '--ctime', [CompletionResultType]::ParameterName, 'just like -mtime, but based on file change time')\n            [CompletionResult]::new('--files0-from', '--files0-from', [CompletionResultType]::ParameterName, 'Read NUL-terminated paths from FILE (use `-` for stdin)')\n            [CompletionResult]::new('--files-from', '--files-from', [CompletionResultType]::ParameterName, 'Read newline-terminated paths from FILE (use `-` for stdin)')\n            [CompletionResult]::new('--collapse', '--collapse', [CompletionResultType]::ParameterName, 'Keep these directories collapsed')\n            [CompletionResult]::new('-m', '-m', [CompletionResultType]::ParameterName, 'Directory ''size'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time')\n            [CompletionResult]::new('--filetime', '--filetime', [CompletionResultType]::ParameterName, 'Directory ''size'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time')\n            [CompletionResult]::new('-p', '-p', [CompletionResultType]::ParameterName, 'Subdirectories will not have their path shortened')\n            [CompletionResult]::new('--full-paths', '--full-paths', [CompletionResultType]::ParameterName, 'Subdirectories will not have their path shortened')\n            [CompletionResult]::new('-L', '-L ', [CompletionResultType]::ParameterName, 'dereference sym links - Treat sym links as directories and go into them')\n            [CompletionResult]::new('--dereference-links', '--dereference-links', [CompletionResultType]::ParameterName, 'dereference sym links - Treat sym links as directories and go into them')\n            [CompletionResult]::new('-x', '-x', [CompletionResultType]::ParameterName, 'Only count the files and directories on the same filesystem as the supplied directory')\n            [CompletionResult]::new('--limit-filesystem', '--limit-filesystem', [CompletionResultType]::ParameterName, 'Only count the files and directories on the same filesystem as the supplied directory')\n            [CompletionResult]::new('-s', '-s', [CompletionResultType]::ParameterName, 'Use file length instead of blocks')\n            [CompletionResult]::new('--apparent-size', '--apparent-size', [CompletionResultType]::ParameterName, 'Use file length instead of blocks')\n            [CompletionResult]::new('-r', '-r', [CompletionResultType]::ParameterName, 'Print tree upside down (biggest highest)')\n            [CompletionResult]::new('--reverse', '--reverse', [CompletionResultType]::ParameterName, 'Print tree upside down (biggest highest)')\n            [CompletionResult]::new('-c', '-c', [CompletionResultType]::ParameterName, 'No colors will be printed (Useful for commands like: watch)')\n            [CompletionResult]::new('--no-colors', '--no-colors', [CompletionResultType]::ParameterName, 'No colors will be printed (Useful for commands like: watch)')\n            [CompletionResult]::new('-C', '-C ', [CompletionResultType]::ParameterName, 'Force colors print')\n            [CompletionResult]::new('--force-colors', '--force-colors', [CompletionResultType]::ParameterName, 'Force colors print')\n            [CompletionResult]::new('-b', '-b', [CompletionResultType]::ParameterName, 'No percent bars or percentages will be displayed')\n            [CompletionResult]::new('--no-percent-bars', '--no-percent-bars', [CompletionResultType]::ParameterName, 'No percent bars or percentages will be displayed')\n            [CompletionResult]::new('-B', '-B ', [CompletionResultType]::ParameterName, 'percent bars moved to right side of screen')\n            [CompletionResult]::new('--bars-on-right', '--bars-on-right', [CompletionResultType]::ParameterName, 'percent bars moved to right side of screen')\n            [CompletionResult]::new('-R', '-R ', [CompletionResultType]::ParameterName, 'For screen readers. Removes bars. Adds new column: depth level (May want to use -p too for full path)')\n            [CompletionResult]::new('--screen-reader', '--screen-reader', [CompletionResultType]::ParameterName, 'For screen readers. Removes bars. Adds new column: depth level (May want to use -p too for full path)')\n            [CompletionResult]::new('--skip-total', '--skip-total', [CompletionResultType]::ParameterName, 'No total row will be displayed')\n            [CompletionResult]::new('-f', '-f', [CompletionResultType]::ParameterName, 'Directory ''size'' is number of child files instead of disk size')\n            [CompletionResult]::new('--filecount', '--filecount', [CompletionResultType]::ParameterName, 'Directory ''size'' is number of child files instead of disk size')\n            [CompletionResult]::new('-i', '-i', [CompletionResultType]::ParameterName, 'Do not display hidden files')\n            [CompletionResult]::new('--ignore-hidden', '--ignore-hidden', [CompletionResultType]::ParameterName, 'Do not display hidden files')\n            [CompletionResult]::new('-t', '-t', [CompletionResultType]::ParameterName, 'show only these file types')\n            [CompletionResult]::new('--file-types', '--file-types', [CompletionResultType]::ParameterName, 'show only these file types')\n            [CompletionResult]::new('-P', '-P ', [CompletionResultType]::ParameterName, 'Disable the progress indication')\n            [CompletionResult]::new('--no-progress', '--no-progress', [CompletionResultType]::ParameterName, 'Disable the progress indication')\n            [CompletionResult]::new('--print-errors', '--print-errors', [CompletionResultType]::ParameterName, 'Print path with errors')\n            [CompletionResult]::new('-D', '-D ', [CompletionResultType]::ParameterName, 'Only directories will be displayed')\n            [CompletionResult]::new('--only-dir', '--only-dir', [CompletionResultType]::ParameterName, 'Only directories will be displayed')\n            [CompletionResult]::new('-F', '-F ', [CompletionResultType]::ParameterName, 'Only files will be displayed. (Finds your largest files)')\n            [CompletionResult]::new('--only-file', '--only-file', [CompletionResultType]::ParameterName, 'Only files will be displayed. (Finds your largest files)')\n            [CompletionResult]::new('-j', '-j', [CompletionResultType]::ParameterName, 'Output the directory tree as json to the current directory')\n            [CompletionResult]::new('--output-json', '--output-json', [CompletionResultType]::ParameterName, 'Output the directory tree as json to the current directory')\n            [CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help (see more with ''--help'')')\n            [CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help (see more with ''--help'')')\n            [CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')\n            [CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')\n            break\n        }\n    })\n\n    $completions.Where{ $_.CompletionText -like \"$wordToComplete*\" } |\n        Sort-Object -Property ListItemText\n}\n"
  },
  {
    "path": "completions/dust.bash",
    "content": "_dust() {\n    local i cur prev opts cmd\n    COMPREPLY=()\n    if [[ \"${BASH_VERSINFO[0]}\" -ge 4 ]]; then\n        cur=\"$2\"\n    else\n        cur=\"${COMP_WORDS[COMP_CWORD]}\"\n    fi\n    prev=\"$3\"\n    cmd=\"\"\n    opts=\"\"\n\n    for i in \"${COMP_WORDS[@]:0:COMP_CWORD}\"\n    do\n        case \"${cmd},${i}\" in\n            \",$1\")\n                cmd=\"dust\"\n                ;;\n            *)\n                ;;\n        esac\n    done\n\n    case \"${cmd}\" in\n        dust)\n            opts=\"-d -T -n -p -X -I -L -x -s -r -c -C -b -B -z -R -f -i -v -e -t -w -P -D -F -o -S -j -M -A -y -m -h -V --depth --threads --config --number-of-lines --full-paths --ignore-directory --ignore-all-in-file --dereference-links --limit-filesystem --apparent-size --reverse --no-colors --force-colors --no-percent-bars --bars-on-right --min-size --screen-reader --skip-total --filecount --ignore-hidden --invert-filter --filter --file-types --terminal-width --no-progress --print-errors --only-dir --only-file --output-format --stack-size --output-json --mtime --atime --ctime --files0-from --files-from --collapse --filetime --help --version [PATH]...\"\n            if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then\n                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\n                return 0\n            fi\n            case \"${prev}\" in\n                --depth)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -d)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --threads)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -T)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --config)\n                    local oldifs\n                    if [ -n \"${IFS+x}\" ]; then\n                        oldifs=\"$IFS\"\n                    fi\n                    IFS=$'\\n'\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    if [ -n \"${oldifs+x}\" ]; then\n                        IFS=\"$oldifs\"\n                    fi\n                    if [[ \"${BASH_VERSINFO[0]}\" -ge 4 ]]; then\n                        compopt -o filenames\n                    fi\n                    return 0\n                    ;;\n                --number-of-lines)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -n)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --ignore-directory)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -X)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --ignore-all-in-file)\n                    local oldifs\n                    if [ -n \"${IFS+x}\" ]; then\n                        oldifs=\"$IFS\"\n                    fi\n                    IFS=$'\\n'\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    if [ -n \"${oldifs+x}\" ]; then\n                        IFS=\"$oldifs\"\n                    fi\n                    if [[ \"${BASH_VERSINFO[0]}\" -ge 4 ]]; then\n                        compopt -o filenames\n                    fi\n                    return 0\n                    ;;\n                -I)\n                    local oldifs\n                    if [ -n \"${IFS+x}\" ]; then\n                        oldifs=\"$IFS\"\n                    fi\n                    IFS=$'\\n'\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    if [ -n \"${oldifs+x}\" ]; then\n                        IFS=\"$oldifs\"\n                    fi\n                    if [[ \"${BASH_VERSINFO[0]}\" -ge 4 ]]; then\n                        compopt -o filenames\n                    fi\n                    return 0\n                    ;;\n                --min-size)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -z)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --invert-filter)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -v)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --filter)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -e)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --terminal-width)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -w)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --output-format)\n                    COMPREPLY=($(compgen -W \"si b k m g t kb mb gb tb\" -- \"${cur}\"))\n                    return 0\n                    ;;\n                -o)\n                    COMPREPLY=($(compgen -W \"si b k m g t kb mb gb tb\" -- \"${cur}\"))\n                    return 0\n                    ;;\n                --stack-size)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -S)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --mtime)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -M)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --atime)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -A)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --ctime)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                -y)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --files0-from)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --files-from)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --collapse)\n                    COMPREPLY=($(compgen -f \"${cur}\"))\n                    return 0\n                    ;;\n                --filetime)\n                    COMPREPLY=($(compgen -W \"a c m\" -- \"${cur}\"))\n                    return 0\n                    ;;\n                -m)\n                    COMPREPLY=($(compgen -W \"a c m\" -- \"${cur}\"))\n                    return 0\n                    ;;\n                *)\n                    COMPREPLY=()\n                    ;;\n            esac\n            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\n            return 0\n            ;;\n    esac\n}\n\nif [[ \"${BASH_VERSINFO[0]}\" -eq 4 && \"${BASH_VERSINFO[1]}\" -ge 4 || \"${BASH_VERSINFO[0]}\" -gt 4 ]]; then\n    complete -F _dust -o nosort -o bashdefault -o default dust\nelse\n    complete -F _dust -o bashdefault -o default dust\nfi\n"
  },
  {
    "path": "completions/dust.elv",
    "content": "\nuse builtin;\nuse str;\n\nset edit:completion:arg-completer[dust] = {|@words|\n    fn spaces {|n|\n        builtin:repeat $n ' ' | str:join ''\n    }\n    fn cand {|text desc|\n        edit:complex-candidate $text &display=$text' '(spaces (- 14 (wcswidth $text)))$desc\n    }\n    var command = 'dust'\n    for word $words[1..-1] {\n        if (str:has-prefix $word '-') {\n            break\n        }\n        set command = $command';'$word\n    }\n    var completions = [\n        &'dust'= {\n            cand -d 'Depth to show'\n            cand --depth 'Depth to show'\n            cand -T 'Number of threads to use'\n            cand --threads 'Number of threads to use'\n            cand --config 'Specify a config file to use'\n            cand -n 'Display the ''n'' largest entries. (Default is terminal_height)'\n            cand --number-of-lines 'Display the ''n'' largest entries. (Default is terminal_height)'\n            cand -X 'Exclude any file or directory with this path'\n            cand --ignore-directory 'Exclude any file or directory with this path'\n            cand -I 'Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter'\n            cand --ignore-all-in-file 'Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter'\n            cand -z 'Minimum size file to include in output'\n            cand --min-size 'Minimum size file to include in output'\n            cand -v 'Exclude filepaths matching this regex. To ignore png files type: -v \"\\.png$\"'\n            cand --invert-filter 'Exclude filepaths matching this regex. To ignore png files type: -v \"\\.png$\"'\n            cand -e 'Only include filepaths matching this regex. For png files type: -e \"\\.png$\"'\n            cand --filter 'Only include filepaths matching this regex. For png files type: -e \"\\.png$\"'\n            cand -w 'Specify width of output overriding the auto detection of terminal width'\n            cand --terminal-width 'Specify width of output overriding the auto detection of terminal width'\n            cand -o 'Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size'\n            cand --output-format 'Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size'\n            cand -S 'Specify memory to use as stack size - use if you see: ''fatal runtime error: stack overflow'' (default low memory=1048576, high memory=1073741824)'\n            cand --stack-size 'Specify memory to use as stack size - use if you see: ''fatal runtime error: stack overflow'' (default low memory=1048576, high memory=1073741824)'\n            cand -M '+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)'\n            cand --mtime '+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)'\n            cand -A 'just like -mtime, but based on file access time'\n            cand --atime 'just like -mtime, but based on file access time'\n            cand -y 'just like -mtime, but based on file change time'\n            cand --ctime 'just like -mtime, but based on file change time'\n            cand --files0-from 'Read NUL-terminated paths from FILE (use `-` for stdin)'\n            cand --files-from 'Read newline-terminated paths from FILE (use `-` for stdin)'\n            cand --collapse 'Keep these directories collapsed'\n            cand -m 'Directory ''size'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time'\n            cand --filetime 'Directory ''size'' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time'\n            cand -p 'Subdirectories will not have their path shortened'\n            cand --full-paths 'Subdirectories will not have their path shortened'\n            cand -L 'dereference sym links - Treat sym links as directories and go into them'\n            cand --dereference-links 'dereference sym links - Treat sym links as directories and go into them'\n            cand -x 'Only count the files and directories on the same filesystem as the supplied directory'\n            cand --limit-filesystem 'Only count the files and directories on the same filesystem as the supplied directory'\n            cand -s 'Use file length instead of blocks'\n            cand --apparent-size 'Use file length instead of blocks'\n            cand -r 'Print tree upside down (biggest highest)'\n            cand --reverse 'Print tree upside down (biggest highest)'\n            cand -c 'No colors will be printed (Useful for commands like: watch)'\n            cand --no-colors 'No colors will be printed (Useful for commands like: watch)'\n            cand -C 'Force colors print'\n            cand --force-colors 'Force colors print'\n            cand -b 'No percent bars or percentages will be displayed'\n            cand --no-percent-bars 'No percent bars or percentages will be displayed'\n            cand -B 'percent bars moved to right side of screen'\n            cand --bars-on-right 'percent bars moved to right side of screen'\n            cand -R 'For screen readers. Removes bars. Adds new column: depth level (May want to use -p too for full path)'\n            cand --screen-reader 'For screen readers. Removes bars. Adds new column: depth level (May want to use -p too for full path)'\n            cand --skip-total 'No total row will be displayed'\n            cand -f 'Directory ''size'' is number of child files instead of disk size'\n            cand --filecount 'Directory ''size'' is number of child files instead of disk size'\n            cand -i 'Do not display hidden files'\n            cand --ignore-hidden 'Do not display hidden files'\n            cand -t 'show only these file types'\n            cand --file-types 'show only these file types'\n            cand -P 'Disable the progress indication'\n            cand --no-progress 'Disable the progress indication'\n            cand --print-errors 'Print path with errors'\n            cand -D 'Only directories will be displayed'\n            cand --only-dir 'Only directories will be displayed'\n            cand -F 'Only files will be displayed. (Finds your largest files)'\n            cand --only-file 'Only files will be displayed. (Finds your largest files)'\n            cand -j 'Output the directory tree as json to the current directory'\n            cand --output-json 'Output the directory tree as json to the current directory'\n            cand -h 'Print help (see more with ''--help'')'\n            cand --help 'Print help (see more with ''--help'')'\n            cand -V 'Print version'\n            cand --version 'Print version'\n        }\n    ]\n    $completions[$command]\n}\n"
  },
  {
    "path": "completions/dust.fish",
    "content": "complete -c dust -s d -l depth -d 'Depth to show' -r\ncomplete -c dust -s T -l threads -d 'Number of threads to use' -r\ncomplete -c dust -l config -d 'Specify a config file to use' -r -F\ncomplete -c dust -s n -l number-of-lines -d 'Display the \\'n\\' largest entries. (Default is terminal_height)' -r\ncomplete -c dust -s X -l ignore-directory -d 'Exclude any file or directory with this path' -r -F\ncomplete -c dust -s I -l ignore-all-in-file -d 'Exclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by --invert_filter' -r -F\ncomplete -c dust -s z -l min-size -d 'Minimum size file to include in output' -r\ncomplete -c dust -s v -l invert-filter -d 'Exclude filepaths matching this regex. To ignore png files type: -v \"\\\\.png$\"' -r\ncomplete -c dust -s e -l filter -d 'Only include filepaths matching this regex. For png files type: -e \"\\\\.png$\"' -r\ncomplete -c dust -s w -l terminal-width -d 'Specify width of output overriding the auto detection of terminal width' -r\ncomplete -c dust -s o -l output-format -d 'Changes output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size' -r -f -a \"si\\t'SI prefix (powers of 1000)'\nb\\t'byte (B)'\nk\\t'kibibyte (KiB)'\nm\\t'mebibyte (MiB)'\ng\\t'gibibyte (GiB)'\nt\\t'tebibyte (TiB)'\nkb\\t'kilobyte (kB)'\nmb\\t'megabyte (MB)'\ngb\\t'gigabyte (GB)'\ntb\\t'terabyte (TB)'\"\ncomplete -c dust -s S -l stack-size -d 'Specify memory to use as stack size - use if you see: \\'fatal runtime error: stack overflow\\' (default low memory=1048576, high memory=1073741824)' -r\ncomplete -c dust -s M -l mtime -d '+/-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)' -r\ncomplete -c dust -s A -l atime -d 'just like -mtime, but based on file access time' -r\ncomplete -c dust -s y -l ctime -d 'just like -mtime, but based on file change time' -r\ncomplete -c dust -l files0-from -d 'Read NUL-terminated paths from FILE (use `-` for stdin)' -r -F\ncomplete -c dust -l files-from -d 'Read newline-terminated paths from FILE (use `-` for stdin)' -r -F\ncomplete -c dust -l collapse -d 'Keep these directories collapsed' -r -F\ncomplete -c dust -s m -l filetime -d 'Directory \\'size\\' is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time' -r -f -a \"a\\t'last accessed time'\nc\\t'last changed time'\nm\\t'last modified time'\"\ncomplete -c dust -s p -l full-paths -d 'Subdirectories will not have their path shortened'\ncomplete -c dust -s L -l dereference-links -d 'dereference sym links - Treat sym links as directories and go into them'\ncomplete -c dust -s x -l limit-filesystem -d 'Only count the files and directories on the same filesystem as the supplied directory'\ncomplete -c dust -s s -l apparent-size -d 'Use file length instead of blocks'\ncomplete -c dust -s r -l reverse -d 'Print tree upside down (biggest highest)'\ncomplete -c dust -s c -l no-colors -d 'No colors will be printed (Useful for commands like: watch)'\ncomplete -c dust -s C -l force-colors -d 'Force colors print'\ncomplete -c dust -s b -l no-percent-bars -d 'No percent bars or percentages will be displayed'\ncomplete -c dust -s B -l bars-on-right -d 'percent bars moved to right side of screen'\ncomplete -c dust -s R -l screen-reader -d 'For screen readers. Removes bars. Adds new column: depth level (May want to use -p too for full path)'\ncomplete -c dust -l skip-total -d 'No total row will be displayed'\ncomplete -c dust -s f -l filecount -d 'Directory \\'size\\' is number of child files instead of disk size'\ncomplete -c dust -s i -l ignore-hidden -d 'Do not display hidden files'\ncomplete -c dust -s t -l file-types -d 'show only these file types'\ncomplete -c dust -s P -l no-progress -d 'Disable the progress indication'\ncomplete -c dust -l print-errors -d 'Print path with errors'\ncomplete -c dust -s D -l only-dir -d 'Only directories will be displayed'\ncomplete -c dust -s F -l only-file -d 'Only files will be displayed. (Finds your largest files)'\ncomplete -c dust -s j -l output-json -d 'Output the directory tree as json to the current directory'\ncomplete -c dust -s h -l help -d 'Print help (see more with \\'--help\\')'\ncomplete -c dust -s V -l version -d 'Print version'\n"
  },
  {
    "path": "config/config.toml",
    "content": "# Sample Config file, works with toml and yaml\n# Place in either:\n#   ~/.config/dust/config.toml\n#   ~/.dust.toml\n\n# Print tree upside down (biggest highest)\nreverse=true\n\n# Subdirectories will not have their path shortened\ndisplay-full-paths=true\n\n# Use file length instead of blocks\ndisplay-apparent-size=true\n\n# No colors will be printed\nno-colors=true\n\n# No percent bars or percentages will be displayed\nno-bars=true\n\n# No total row will be displayed\nskip-total=true\n\n# Do not display hidden files\nignore-hidden=true\n\n# print sizes in powers of 1000 (e.g., 1.1G)\noutput-format=\"si\"\n\nnumber-of-lines=5   \n\n# To keep the .git directory collapsed\ncollapse=[\".git\"]\n"
  },
  {
    "path": "install.sh",
    "content": "#!/usr/bin/env bash\n# dust installer script\n# Usage: curl -sSfL https://raw.githubusercontent.com/bootandy/dust/main/install.sh | sh\n\nset -e\n\nREPO=\"bootandy/dust\"\nBINARY_NAME=\"dust\"\n\n# Colors for output\nRED='\\033[0;31m'\nGREEN='\\033[0;32m'\nYELLOW='\\033[1;33m'\nNC='\\033[0m' # No Color\n\ninfo() {\n    echo -e \"${GREEN}[INFO]${NC} $1\"\n}\n\nwarn() {\n    echo -e \"${YELLOW}[WARN]${NC} $1\"\n}\n\nerror() {\n    echo -e \"${RED}[ERROR]${NC} $1\"\n    exit 1\n}\n\n# Detect OS\ndetect_os() {\n    case \"$(uname -s)\" in\n        Linux*)     OS=\"linux\" ;;\n        Darwin*)    OS=\"darwin\" ;;\n        MINGW*|MSYS*|CYGWIN*) OS=\"windows\" ;;\n        *)          error \"Unsupported operating system: $(uname -s)\" ;;\n    esac\n}\n\n# Detect architecture\ndetect_arch() {\n    ARCH=$(uname -m)\n    case \"$ARCH\" in\n        x86_64|amd64)   ARCH=\"x86_64\" ;;\n        aarch64|arm64)  ARCH=\"aarch64\" ;;\n        armv7l)         ARCH=\"arm\" ;;\n        i686|i386)      ARCH=\"i686\" ;;\n        *)              error \"Unsupported architecture: $ARCH\" ;;\n    esac\n}\n\n# Get the latest release version\nget_latest_version() {\n    info \"Fetching latest version...\"\n    \n    # Try using curl\n    if command -v curl >/dev/null 2>&1; then\n        VERSION=$(curl -sSf \"https://api.github.com/repos/$REPO/releases/latest\" | grep '\"tag_name\"' | sed -E 's/.*\"v?([^\"]+)\".*/\\1/')\n    # Try using wget\n    elif command -v wget >/dev/null 2>&1; then\n        VERSION=$(wget -qO- \"https://api.github.com/repos/$REPO/releases/latest\" | grep '\"tag_name\"' | sed -E 's/.*\"v?([^\"]+)\".*/\\1/')\n    else\n        error \"Neither curl nor wget is available. Please install one of them.\"\n    fi\n    \n    if [ -z \"$VERSION\" ]; then\n        error \"Failed to fetch latest version\"\n    fi\n    \n    info \"Latest version: v$VERSION\"\n}\n\n# Determine target triple\nget_target() {\n    if [ \"$OS\" = \"linux\" ]; then\n        if [ \"$ARCH\" = \"x86_64\" ]; then\n            TARGET=\"x86_64-unknown-linux-musl\"\n        elif [ \"$ARCH\" = \"aarch64\" ]; then\n            TARGET=\"aarch64-unknown-linux-musl\"\n        elif [ \"$ARCH\" = \"arm\" ]; then\n            TARGET=\"arm-unknown-linux-musleabi\"\n        elif [ \"$ARCH\" = \"i686\" ]; then\n            TARGET=\"i686-unknown-linux-musl\"\n        else\n            error \"Unsupported Linux architecture: $ARCH\"\n        fi\n    elif [ \"$OS\" = \"darwin\" ]; then\n        if [ \"$ARCH\" = \"x86_64\" ]; then\n            TARGET=\"x86_64-apple-darwin\"\n        elif [ \"$ARCH\" = \"aarch64\" ]; then\n            # For Apple Silicon, use x86_64 with Rosetta if native build not available\n            TARGET=\"x86_64-apple-darwin\"\n            warn \"Using x86_64 binary (will run via Rosetta 2 on Apple Silicon)\"\n        else\n            error \"Unsupported macOS architecture: $ARCH\"\n        fi\n    elif [ \"$OS\" = \"windows\" ]; then\n        if [ \"$ARCH\" = \"x86_64\" ]; then\n            TARGET=\"x86_64-pc-windows-msvc\"\n        elif [ \"$ARCH\" = \"i686\" ]; then\n            TARGET=\"i686-pc-windows-msvc\"\n        else\n            error \"Unsupported Windows architecture: $ARCH\"\n        fi\n    else\n        error \"Unsupported OS: $OS\"\n    fi\n    \n    info \"Target platform: $TARGET\"\n}\n\n# Download and extract\ndownload_and_install() {\n    # Construct download URL\n    if [ \"$OS\" = \"windows\" ]; then\n        ARCHIVE_NAME=\"dust-v${VERSION}-${TARGET}.zip\"\n        ARCHIVE_EXT=\"zip\"\n    else\n        ARCHIVE_NAME=\"dust-v${VERSION}-${TARGET}.tar.gz\"\n        ARCHIVE_EXT=\"tar.gz\"\n    fi\n    \n    DOWNLOAD_URL=\"https://github.com/$REPO/releases/download/v${VERSION}/${ARCHIVE_NAME}\"\n    \n    info \"Downloading from: $DOWNLOAD_URL\"\n    \n    # Create temporary directory\n    TMP_DIR=$(mktemp -d)\n    cd \"$TMP_DIR\"\n    \n    # Download\n    if command -v curl >/dev/null 2>&1; then\n        curl -sSfL \"$DOWNLOAD_URL\" -o \"$ARCHIVE_NAME\" || error \"Download failed\"\n    elif command -v wget >/dev/null 2>&1; then\n        wget -q \"$DOWNLOAD_URL\" -O \"$ARCHIVE_NAME\" || error \"Download failed\"\n    fi\n    \n    # Extract\n    info \"Extracting archive...\"\n    if [ \"$ARCHIVE_EXT\" = \"tar.gz\" ]; then\n        tar -xzf \"$ARCHIVE_NAME\" || error \"Extraction failed\"\n    elif [ \"$ARCHIVE_EXT\" = \"zip\" ]; then\n        unzip -q \"$ARCHIVE_NAME\" || error \"Extraction failed\"\n    fi\n    \n    # Find the binary (it might be in a subdirectory)\n    if [ \"$OS\" = \"windows\" ]; then\n        BINARY_PATH=$(find . -name \"${BINARY_NAME}.exe\" | head -n 1)\n    else\n        BINARY_PATH=$(find . -name \"$BINARY_NAME\" -type f | head -n 1)\n    fi\n    \n    if [ -z \"$BINARY_PATH\" ]; then\n        error \"Binary not found in archive\"\n    fi\n    \n    # Determine installation directory\n    if [ -n \"$DUST_INSTALL\" ]; then\n        INSTALL_DIR=\"$DUST_INSTALL\"\n    elif [ -w \"/usr/local/bin\" ]; then\n        INSTALL_DIR=\"/usr/local/bin\"\n    elif [ -w \"$HOME/.local/bin\" ]; then\n        INSTALL_DIR=\"$HOME/.local/bin\"\n        mkdir -p \"$INSTALL_DIR\"\n    else\n        INSTALL_DIR=\"$HOME/.local/bin\"\n        mkdir -p \"$INSTALL_DIR\"\n    fi\n    \n    # Install binary\n    info \"Installing to $INSTALL_DIR...\"\n    \n    if [ -w \"$INSTALL_DIR\" ]; then\n        cp \"$BINARY_PATH\" \"$INSTALL_DIR/\" || error \"Installation failed\"\n        chmod +x \"$INSTALL_DIR/$BINARY_NAME\" || true\n    else\n        # Try with sudo\n        warn \"Installing with sudo (requires administrator privileges)...\"\n        sudo cp \"$BINARY_PATH\" \"$INSTALL_DIR/\" || error \"Installation failed\"\n        sudo chmod +x \"$INSTALL_DIR/$BINARY_NAME\" || true\n    fi\n    \n    # Clean up\n    cd - > /dev/null\n    rm -rf \"$TMP_DIR\"\n    \n    info \"${GREEN}✓${NC} dust v$VERSION installed successfully!\"\n    \n    # Check if install directory is in PATH\n    case \":$PATH:\" in\n        *:$INSTALL_DIR:*)\n            ;;\n        *)\n            warn \"⚠️  $INSTALL_DIR is not in your PATH\"\n            warn \"   Add the following to your shell config (~/.bashrc, ~/.zshrc, etc.):\"\n            echo \"\"\n            echo \"       export PATH=\\\"$INSTALL_DIR:\\$PATH\\\"\"\n            echo \"\"\n            ;;\n    esac\n    \n    # Show version\n    if command -v \"$BINARY_NAME\" >/dev/null 2>&1; then\n        info \"Version check:\"\n        \"$BINARY_NAME\" --version || true\n    fi\n}\n\n# Main execution\nmain() {\n    info \"dust installer\"\n    echo \"\"\n    \n    # Check for required tools\n    if ! command -v tar >/dev/null 2>&1 && ! command -v unzip >/dev/null 2>&1; then\n        error \"Neither tar nor unzip is available. Please install one of them.\"\n    fi\n    \n    detect_os\n    detect_arch\n    get_latest_version\n    get_target\n    download_and_install\n    \n    echo \"\"\n    info \"Installation complete! Try running: ${GREEN}dust${NC}\"\n}\n\n# Allow version to be specified via environment variable\nif [ -n \"$DUST_VERSION\" ]; then\n    VERSION=\"$DUST_VERSION\"\nfi\n\nmain\n"
  },
  {
    "path": "man-page/dust.1",
    "content": ".ie \\n(.g .ds Aq \\(aq\n.el .ds Aq '\n.TH Dust 1  \"Dust 1.2.4\" \n.SH NAME\nDust \\- Like du but more intuitive\n.SH SYNOPSIS\n\\fBdust\\fR [\\fB\\-d\\fR|\\fB\\-\\-depth\\fR] [\\fB\\-T\\fR|\\fB\\-\\-threads\\fR] [\\fB\\-\\-config\\fR] [\\fB\\-n\\fR|\\fB\\-\\-number\\-of\\-lines\\fR] [\\fB\\-p\\fR|\\fB\\-\\-full\\-paths\\fR] [\\fB\\-X\\fR|\\fB\\-\\-ignore\\-directory\\fR] [\\fB\\-I\\fR|\\fB\\-\\-ignore\\-all\\-in\\-file\\fR] [\\fB\\-L\\fR|\\fB\\-\\-dereference\\-links\\fR] [\\fB\\-x\\fR|\\fB\\-\\-limit\\-filesystem\\fR] [\\fB\\-s\\fR|\\fB\\-\\-apparent\\-size\\fR] [\\fB\\-r\\fR|\\fB\\-\\-reverse\\fR] [\\fB\\-c\\fR|\\fB\\-\\-no\\-colors\\fR] [\\fB\\-C\\fR|\\fB\\-\\-force\\-colors\\fR] [\\fB\\-b\\fR|\\fB\\-\\-no\\-percent\\-bars\\fR] [\\fB\\-B\\fR|\\fB\\-\\-bars\\-on\\-right\\fR] [\\fB\\-z\\fR|\\fB\\-\\-min\\-size\\fR] [\\fB\\-R\\fR|\\fB\\-\\-screen\\-reader\\fR] [\\fB\\-\\-skip\\-total\\fR] [\\fB\\-f\\fR|\\fB\\-\\-filecount\\fR] [\\fB\\-i\\fR|\\fB\\-\\-ignore\\-hidden\\fR] [\\fB\\-v\\fR|\\fB\\-\\-invert\\-filter\\fR] [\\fB\\-e\\fR|\\fB\\-\\-filter\\fR] [\\fB\\-t\\fR|\\fB\\-\\-file\\-types\\fR] [\\fB\\-w\\fR|\\fB\\-\\-terminal\\-width\\fR] [\\fB\\-P\\fR|\\fB\\-\\-no\\-progress\\fR] [\\fB\\-\\-print\\-errors\\fR] [\\fB\\-D\\fR|\\fB\\-\\-only\\-dir\\fR] [\\fB\\-F\\fR|\\fB\\-\\-only\\-file\\fR] [\\fB\\-o\\fR|\\fB\\-\\-output\\-format\\fR] [\\fB\\-S\\fR|\\fB\\-\\-stack\\-size\\fR] [\\fB\\-j\\fR|\\fB\\-\\-output\\-json\\fR] [\\fB\\-M\\fR|\\fB\\-\\-mtime\\fR] [\\fB\\-A\\fR|\\fB\\-\\-atime\\fR] [\\fB\\-y\\fR|\\fB\\-\\-ctime\\fR] [\\fB\\-\\-files0\\-from\\fR] [\\fB\\-\\-files\\-from\\fR] [\\fB\\-\\-collapse\\fR] [\\fB\\-m\\fR|\\fB\\-\\-filetime\\fR] [\\fB\\-h\\fR|\\fB\\-\\-help\\fR] [\\fB\\-V\\fR|\\fB\\-\\-version\\fR] [\\fIPATH\\fR] \n.SH DESCRIPTION\nLike du but more intuitive\n.SH OPTIONS\n.TP\n\\fB\\-d\\fR, \\fB\\-\\-depth\\fR \\fI<DEPTH>\\fR\nDepth to show\n.TP\n\\fB\\-T\\fR, \\fB\\-\\-threads\\fR \\fI<THREADS>\\fR\nNumber of threads to use\n.TP\n\\fB\\-\\-config\\fR \\fI<FILE>\\fR\nSpecify a config file to use\n.TP\n\\fB\\-n\\fR, \\fB\\-\\-number\\-of\\-lines\\fR \\fI<NUMBER>\\fR\nDisplay the \\*(Aqn\\*(Aq largest entries. (Default is terminal_height)\n.TP\n\\fB\\-p\\fR, \\fB\\-\\-full\\-paths\\fR\nSubdirectories will not have their path shortened\n.TP\n\\fB\\-X\\fR, \\fB\\-\\-ignore\\-directory\\fR \\fI<PATH>\\fR\nExclude any file or directory with this path\n.TP\n\\fB\\-I\\fR, \\fB\\-\\-ignore\\-all\\-in\\-file\\fR \\fI<FILE>\\fR\nExclude any file or directory with a regex matching that listed in this file, the file entries will be added to the ignore regexs provided by \\-\\-invert_filter\n.TP\n\\fB\\-L\\fR, \\fB\\-\\-dereference\\-links\\fR\ndereference sym links \\- Treat sym links as directories and go into them\n.TP\n\\fB\\-x\\fR, \\fB\\-\\-limit\\-filesystem\\fR\nOnly count the files and directories on the same filesystem as the supplied directory\n.TP\n\\fB\\-s\\fR, \\fB\\-\\-apparent\\-size\\fR\nUse file length instead of blocks\n.TP\n\\fB\\-r\\fR, \\fB\\-\\-reverse\\fR\nPrint tree upside down (biggest highest)\n.TP\n\\fB\\-c\\fR, \\fB\\-\\-no\\-colors\\fR\nNo colors will be printed (Useful for commands like: watch)\n.TP\n\\fB\\-C\\fR, \\fB\\-\\-force\\-colors\\fR\nForce colors print\n.TP\n\\fB\\-b\\fR, \\fB\\-\\-no\\-percent\\-bars\\fR\nNo percent bars or percentages will be displayed\n.TP\n\\fB\\-B\\fR, \\fB\\-\\-bars\\-on\\-right\\fR\npercent bars moved to right side of screen\n.TP\n\\fB\\-z\\fR, \\fB\\-\\-min\\-size\\fR \\fI<MIN_SIZE>\\fR\nMinimum size file to include in output\n.TP\n\\fB\\-R\\fR, \\fB\\-\\-screen\\-reader\\fR\nFor screen readers. Removes bars. Adds new column: depth level (May want to use \\-p too for full path)\n.TP\n\\fB\\-\\-skip\\-total\\fR\nNo total row will be displayed\n.TP\n\\fB\\-f\\fR, \\fB\\-\\-filecount\\fR\nDirectory \\*(Aqsize\\*(Aq is number of child files instead of disk size\n.TP\n\\fB\\-i\\fR, \\fB\\-\\-ignore\\-hidden\\fR\nDo not display hidden files\n.TP\n\\fB\\-v\\fR, \\fB\\-\\-invert\\-filter\\fR \\fI<REGEX>\\fR\nExclude filepaths matching this regex. To ignore png files type: \\-v \"\\\\.png$\"\n.TP\n\\fB\\-e\\fR, \\fB\\-\\-filter\\fR \\fI<REGEX>\\fR\nOnly include filepaths matching this regex. For png files type: \\-e \"\\\\.png$\"\n.TP\n\\fB\\-t\\fR, \\fB\\-\\-file\\-types\\fR\nshow only these file types\n.TP\n\\fB\\-w\\fR, \\fB\\-\\-terminal\\-width\\fR \\fI<WIDTH>\\fR\nSpecify width of output overriding the auto detection of terminal width\n.TP\n\\fB\\-P\\fR, \\fB\\-\\-no\\-progress\\fR\nDisable the progress indication\n.TP\n\\fB\\-\\-print\\-errors\\fR\nPrint path with errors\n.TP\n\\fB\\-D\\fR, \\fB\\-\\-only\\-dir\\fR\nOnly directories will be displayed\n.TP\n\\fB\\-F\\fR, \\fB\\-\\-only\\-file\\fR\nOnly files will be displayed. (Finds your largest files)\n.TP\n\\fB\\-o\\fR, \\fB\\-\\-output\\-format\\fR \\fI<FORMAT>\\fR\nChanges output display size. si will print sizes in powers of 1000. b k m g t kb mb gb tb will print the whole tree in that size\n.br\n\n.br\n\\fIPossible values:\\fR\n.RS 14\n.IP \\(bu 2\nsi: SI prefix (powers of 1000)\n.IP \\(bu 2\nb: byte (B)\n.IP \\(bu 2\nk: kibibyte (KiB)\n.IP \\(bu 2\nm: mebibyte (MiB)\n.IP \\(bu 2\ng: gibibyte (GiB)\n.IP \\(bu 2\nt: tebibyte (TiB)\n.IP \\(bu 2\nkb: kilobyte (kB)\n.IP \\(bu 2\nmb: megabyte (MB)\n.IP \\(bu 2\ngb: gigabyte (GB)\n.IP \\(bu 2\ntb: terabyte (TB)\n.RE\n.TP\n\\fB\\-S\\fR, \\fB\\-\\-stack\\-size\\fR \\fI<STACK_SIZE>\\fR\nSpecify memory to use as stack size \\- use if you see: \\*(Aqfatal runtime error: stack overflow\\*(Aq (default low memory=1048576, high memory=1073741824)\n.TP\n\\fB\\-j\\fR, \\fB\\-\\-output\\-json\\fR\nOutput the directory tree as json to the current directory\n.TP\n\\fB\\-M\\fR, \\fB\\-\\-mtime\\fR \\fI<MTIME>\\fR\n+/\\-n matches files modified more/less than n days ago , and n matches files modified exactly n days ago, days are rounded down.That is +n => (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and \\-n => (𝑐𝑢𝑟𝑟−𝑛, +∞)\n.TP\n\\fB\\-A\\fR, \\fB\\-\\-atime\\fR \\fI<ATIME>\\fR\njust like \\-mtime, but based on file access time\n.TP\n\\fB\\-y\\fR, \\fB\\-\\-ctime\\fR \\fI<CTIME>\\fR\njust like \\-mtime, but based on file change time\n.TP\n\\fB\\-\\-files0\\-from\\fR \\fI<FILES0_FROM>\\fR\nRead NUL\\-terminated paths from FILE (use `\\-` for stdin)\n.TP\n\\fB\\-\\-files\\-from\\fR \\fI<FILES_FROM>\\fR\nRead newline\\-terminated paths from FILE (use `\\-` for stdin)\n.TP\n\\fB\\-\\-collapse\\fR \\fI<COLLAPSE>\\fR\nKeep these directories collapsed\n.TP\n\\fB\\-m\\fR, \\fB\\-\\-filetime\\fR \\fI<FILETIME>\\fR\nDirectory \\*(Aqsize\\*(Aq is max filetime of child files instead of disk size. while a/c/m for last accessed/changed/modified time\n.br\n\n.br\n\\fIPossible values:\\fR\n.RS 14\n.IP \\(bu 2\na: last accessed time\n.IP \\(bu 2\nc: last changed time\n.IP \\(bu 2\nm: last modified time\n.RE\n.TP\n\\fB\\-h\\fR, \\fB\\-\\-help\\fR\nPrint help (see a summary with \\*(Aq\\-h\\*(Aq)\n.TP\n\\fB\\-V\\fR, \\fB\\-\\-version\\fR\nPrint version\n.TP\n[\\fIPATH\\fR]\nInput files or directories\n.SH VERSION\nv1.2.4\n"
  },
  {
    "path": "src/cli.rs",
    "content": "use std::fmt;\n\nuse clap::{Parser, ValueEnum, ValueHint};\n\n// For single thread mode set this variable on your command line:\n// export RAYON_NUM_THREADS=1\n\n/// Like du but more intuitive\n#[derive(Debug, Parser)]\n#[command(name(\"Dust\"), version)]\npub struct Cli {\n    /// Depth to show\n    #[arg(short, long)]\n    pub depth: Option<usize>,\n\n    /// Number of threads to use\n    #[arg(short('T'), long)]\n    pub threads: Option<usize>,\n\n    /// Specify a config file to use\n    #[arg(long, value_name(\"FILE\"), value_hint(ValueHint::FilePath))]\n    pub config: Option<String>,\n\n    /// Display the 'n' largest entries. (Default is terminal_height)\n    #[arg(short, long, value_name(\"NUMBER\"))]\n    pub number_of_lines: Option<usize>,\n\n    /// Subdirectories will not have their path shortened\n    #[arg(short('p'), long)]\n    pub full_paths: bool,\n\n    /// Exclude any file or directory with this path\n    #[arg(short('X'), long, value_name(\"PATH\"), value_hint(ValueHint::AnyPath))]\n    pub ignore_directory: Option<Vec<String>>,\n\n    /// Exclude any file or directory with a regex matching that listed in this\n    /// file, the file entries will be added to the ignore regexs provided by\n    /// --invert_filter\n    #[arg(short('I'), long, value_name(\"FILE\"), value_hint(ValueHint::FilePath))]\n    pub ignore_all_in_file: Option<String>,\n\n    /// dereference sym links - Treat sym links as directories and go into them\n    #[arg(short('L'), long)]\n    pub dereference_links: bool,\n\n    /// Only count the files and directories on the same filesystem as the\n    /// supplied directory\n    #[arg(short('x'), long)]\n    pub limit_filesystem: bool,\n\n    /// Use file length instead of blocks\n    #[arg(short('s'), long)]\n    pub apparent_size: bool,\n\n    /// Print tree upside down (biggest highest)\n    #[arg(short, long)]\n    pub reverse: bool,\n\n    /// No colors will be printed (Useful for commands like: watch)\n    #[arg(short('c'), long)]\n    pub no_colors: bool,\n\n    /// Force colors print\n    #[arg(short('C'), long)]\n    pub force_colors: bool,\n\n    /// No percent bars or percentages will be displayed\n    #[arg(short('b'), long)]\n    pub no_percent_bars: bool,\n\n    /// percent bars moved to right side of screen\n    #[arg(short('B'), long)]\n    pub bars_on_right: bool,\n\n    /// Minimum size file to include in output\n    #[arg(short('z'), long)]\n    pub min_size: Option<String>,\n\n    /// For screen readers. Removes bars. Adds new column: depth level (May want\n    /// to use -p too for full path)\n    #[arg(short('R'), long)]\n    pub screen_reader: bool,\n\n    /// No total row will be displayed\n    #[arg(long)]\n    pub skip_total: bool,\n\n    /// Directory 'size' is number of child files instead of disk size\n    #[arg(short, long)]\n    pub filecount: bool,\n\n    /// Do not display hidden files\n    // Do not use 'h' this is used by 'help'\n    #[arg(short, long)]\n    pub ignore_hidden: bool,\n\n    /// Exclude filepaths matching this regex. To ignore png files type: -v\n    /// \"\\.png$\"\n    #[arg(\n        short('v'),\n        long,\n        value_name(\"REGEX\"),\n        conflicts_with(\"filter\"),\n        conflicts_with(\"file_types\")\n    )]\n    pub invert_filter: Option<Vec<String>>,\n\n    /// Only include filepaths matching this regex. For png files type: -e\n    /// \"\\.png$\"\n    #[arg(short('e'), long, value_name(\"REGEX\"), conflicts_with(\"file_types\"))]\n    pub filter: Option<Vec<String>>,\n\n    /// show only these file types\n    #[arg(short('t'), long, conflicts_with(\"depth\"), conflicts_with(\"only_dir\"))]\n    pub file_types: bool,\n\n    /// Specify width of output overriding the auto detection of terminal width\n    #[arg(short('w'), long, value_name(\"WIDTH\"))]\n    pub terminal_width: Option<usize>,\n\n    /// Disable the progress indication.\n    #[arg(short('P'), long)]\n    pub no_progress: bool,\n\n    /// Print path with errors.\n    #[arg(long)]\n    pub print_errors: bool,\n\n    /// Only directories will be displayed.\n    #[arg(\n        short('D'),\n        long,\n        conflicts_with(\"only_file\"),\n        conflicts_with(\"file_types\")\n    )]\n    pub only_dir: bool,\n\n    /// Only files will be displayed. (Finds your largest files)\n    #[arg(short('F'), long, conflicts_with(\"only_dir\"))]\n    pub only_file: bool,\n\n    /// Changes output display size. si will print sizes in powers of 1000. b k\n    /// m g t kb mb gb tb will print the whole tree in that size.\n    #[arg(short, long, value_enum, value_name(\"FORMAT\"), ignore_case(true))]\n    pub output_format: Option<OutputFormat>,\n\n    /// Specify memory to use as stack size - use if you see: 'fatal runtime\n    /// error: stack overflow' (default low memory=1048576, high\n    /// memory=1073741824)\n    #[arg(short('S'), long)]\n    pub stack_size: Option<usize>,\n\n    /// Input files or directories.\n    #[arg(value_name(\"PATH\"), value_hint(ValueHint::AnyPath))]\n    pub params: Option<Vec<String>>,\n\n    /// Output the directory tree as json to the current directory\n    #[arg(short('j'), long)]\n    pub output_json: bool,\n\n    /// +/-n matches files modified more/less than n days ago , and n matches\n    /// files modified exactly n days ago, days are rounded down.That is +n =>\n    /// (−∞, curr−(n+1)), n => [curr−(n+1), curr−n), and -n => (𝑐𝑢𝑟𝑟−𝑛, +∞)\n    #[arg(short('M'), long, allow_hyphen_values(true))]\n    pub mtime: Option<String>,\n\n    /// just like -mtime, but based on file access time\n    #[arg(short('A'), long, allow_hyphen_values(true))]\n    pub atime: Option<String>,\n\n    /// just like -mtime, but based on file change time\n    #[arg(short('y'), long, allow_hyphen_values(true))]\n    pub ctime: Option<String>,\n\n    /// Read NUL-terminated paths from FILE (use `-` for stdin).\n    #[arg(long, value_hint(ValueHint::AnyPath), conflicts_with(\"files_from\"))]\n    pub files0_from: Option<String>,\n\n    /// Read newline-terminated paths from FILE (use `-` for stdin).\n    #[arg(long, value_hint(ValueHint::AnyPath), conflicts_with(\"files0_from\"))]\n    pub files_from: Option<String>,\n\n    /// Keep these directories collapsed\n    #[arg(long, value_hint(ValueHint::AnyPath))]\n    pub collapse: Option<Vec<String>>,\n\n    /// Directory 'size' is max filetime of child files instead of disk size.\n    /// while a/c/m for last accessed/changed/modified time\n    #[arg(short('m'), long, value_enum)]\n    pub filetime: Option<FileTime>,\n}\n\n#[derive(Clone, Copy, Debug, ValueEnum)]\n#[value(rename_all = \"lower\")]\npub enum OutputFormat {\n    /// SI prefix (powers of 1000)\n    SI,\n\n    /// byte (B)\n    B,\n\n    /// kibibyte (KiB)\n    #[value(name = \"k\", alias(\"kib\"))]\n    KiB,\n\n    /// mebibyte (MiB)\n    #[value(name = \"m\", alias(\"mib\"))]\n    MiB,\n\n    /// gibibyte (GiB)\n    #[value(name = \"g\", alias(\"gib\"))]\n    GiB,\n\n    /// tebibyte (TiB)\n    #[value(name = \"t\", alias(\"tib\"))]\n    TiB,\n\n    /// kilobyte (kB)\n    KB,\n\n    /// megabyte (MB)\n    MB,\n\n    /// gigabyte (GB)\n    GB,\n\n    /// terabyte (TB)\n    TB,\n}\n\nimpl fmt::Display for OutputFormat {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        match self {\n            Self::SI => write!(f, \"si\"),\n            Self::B => write!(f, \"b\"),\n            Self::KiB => write!(f, \"k\"),\n            Self::MiB => write!(f, \"m\"),\n            Self::GiB => write!(f, \"g\"),\n            Self::TiB => write!(f, \"t\"),\n            Self::KB => write!(f, \"kb\"),\n            Self::MB => write!(f, \"mb\"),\n            Self::GB => write!(f, \"gb\"),\n            Self::TB => write!(f, \"tb\"),\n        }\n    }\n}\n\n#[derive(Clone, Copy, Debug, ValueEnum)]\npub enum FileTime {\n    /// last accessed time\n    #[value(name = \"a\", alias(\"accessed\"))]\n    Accessed,\n\n    /// last changed time\n    #[value(name = \"c\", alias(\"changed\"))]\n    Changed,\n\n    /// last modified time\n    #[value(name = \"m\", alias(\"modified\"))]\n    Modified,\n}\n"
  },
  {
    "path": "src/config.rs",
    "content": "use crate::node::FileTime;\nuse chrono::{Local, TimeZone};\nuse config_file::FromConfigFile;\nuse regex::Regex;\nuse serde::Deserialize;\nuse std::path::Path;\nuse std::path::PathBuf;\n\nuse crate::cli::Cli;\nuse crate::dir_walker::Operator;\nuse crate::display::get_number_format;\n\npub static DAY_SECONDS: i64 = 24 * 60 * 60;\n\n#[derive(Deserialize, Default)]\n#[serde(rename_all = \"kebab-case\")]\npub struct Config {\n    pub display_full_paths: Option<bool>,\n    pub display_apparent_size: Option<bool>,\n    pub reverse: Option<bool>,\n    pub no_colors: Option<bool>,\n    pub force_colors: Option<bool>,\n    pub no_bars: Option<bool>,\n    pub skip_total: Option<bool>,\n    pub screen_reader: Option<bool>,\n    pub ignore_hidden: Option<bool>,\n    pub output_format: Option<String>,\n    pub min_size: Option<String>,\n    pub only_dir: Option<bool>,\n    pub only_file: Option<bool>,\n    pub disable_progress: Option<bool>,\n    pub depth: Option<usize>,\n    pub bars_on_right: Option<bool>,\n    pub stack_size: Option<usize>,\n    pub threads: Option<usize>,\n    pub output_json: Option<bool>,\n    pub print_errors: Option<bool>,\n    pub files0_from: Option<String>,\n    pub number_of_lines: Option<usize>,\n    pub files_from: Option<String>,\n    pub collapse: Option<Vec<String>>,\n}\n\nimpl Config {\n    pub fn get_files0_from(&self, options: &Cli) -> Option<String> {\n        let from_file = &options.files0_from;\n        match from_file {\n            None => self.files0_from.as_ref().map(|x| x.to_string()),\n            Some(x) => Some(x.to_string()),\n        }\n    }\n\n    pub fn get_files_from(&self, options: &Cli) -> Option<String> {\n        let from_file = &options.files_from;\n        match from_file {\n            None => self.files_from.as_ref().map(|x| x.to_string()),\n            Some(x) => Some(x.to_string()),\n        }\n    }\n    pub fn get_no_colors(&self, options: &Cli) -> bool {\n        Some(true) == self.no_colors || options.no_colors\n    }\n    pub fn get_force_colors(&self, options: &Cli) -> bool {\n        Some(true) == self.force_colors || options.force_colors\n    }\n    pub fn get_disable_progress(&self, options: &Cli) -> bool {\n        Some(true) == self.disable_progress || options.no_progress\n    }\n    pub fn get_apparent_size(&self, options: &Cli) -> bool {\n        Some(true) == self.display_apparent_size || options.apparent_size\n    }\n    pub fn get_ignore_hidden(&self, options: &Cli) -> bool {\n        Some(true) == self.ignore_hidden || options.ignore_hidden\n    }\n    pub fn get_full_paths(&self, options: &Cli) -> bool {\n        Some(true) == self.display_full_paths || options.full_paths\n    }\n    pub fn get_reverse(&self, options: &Cli) -> bool {\n        Some(true) == self.reverse || options.reverse\n    }\n    pub fn get_no_bars(&self, options: &Cli) -> bool {\n        Some(true) == self.no_bars || options.no_percent_bars\n    }\n    pub fn get_output_format(&self, options: &Cli) -> String {\n        let out_fmt = options.output_format;\n        (match out_fmt {\n            None => match &self.output_format {\n                None => \"\".to_string(),\n                Some(x) => x.to_string(),\n            },\n            Some(x) => x.to_string(),\n        })\n        .to_lowercase()\n    }\n\n    pub fn get_filetime(&self, options: &Cli) -> Option<FileTime> {\n        options.filetime.map(FileTime::from)\n    }\n\n    pub fn get_skip_total(&self, options: &Cli) -> bool {\n        Some(true) == self.skip_total || options.skip_total\n    }\n    pub fn get_screen_reader(&self, options: &Cli) -> bool {\n        Some(true) == self.screen_reader || options.screen_reader\n    }\n    pub fn get_depth(&self, options: &Cli) -> usize {\n        if let Some(v) = options.depth {\n            return v;\n        }\n\n        self.depth.unwrap_or(usize::MAX)\n    }\n    pub fn get_min_size(&self, options: &Cli) -> Option<usize> {\n        let size_from_param = options.min_size.as_ref();\n        self._get_min_size(size_from_param)\n    }\n    fn _get_min_size(&self, min_size: Option<&String>) -> Option<usize> {\n        let size_from_param = min_size.and_then(|a| convert_min_size(a));\n\n        if size_from_param.is_none() {\n            self.min_size\n                .as_ref()\n                .and_then(|a| convert_min_size(a.as_ref()))\n        } else {\n            size_from_param\n        }\n    }\n    pub fn get_only_dir(&self, options: &Cli) -> bool {\n        Some(true) == self.only_dir || options.only_dir\n    }\n\n    pub fn get_print_errors(&self, options: &Cli) -> bool {\n        Some(true) == self.print_errors || options.print_errors\n    }\n    pub fn get_only_file(&self, options: &Cli) -> bool {\n        Some(true) == self.only_file || options.only_file\n    }\n    pub fn get_bars_on_right(&self, options: &Cli) -> bool {\n        Some(true) == self.bars_on_right || options.bars_on_right\n    }\n    pub fn get_custom_stack_size(&self, options: &Cli) -> Option<usize> {\n        let from_cmd_line = options.stack_size;\n        if from_cmd_line.is_none() {\n            self.stack_size\n        } else {\n            from_cmd_line\n        }\n    }\n    pub fn get_threads(&self, options: &Cli) -> Option<usize> {\n        let from_cmd_line = options.threads;\n        if from_cmd_line.is_none() {\n            self.threads\n        } else {\n            from_cmd_line\n        }\n    }\n    pub fn get_output_json(&self, options: &Cli) -> bool {\n        Some(true) == self.output_json || options.output_json\n    }\n\n    pub fn get_number_of_lines(&self, options: &Cli) -> Option<usize> {\n        let from_cmd_line = options.number_of_lines;\n        if from_cmd_line.is_none() {\n            self.number_of_lines\n        } else {\n            from_cmd_line\n        }\n    }\n\n    pub fn get_modified_time_operator(&self, options: &Cli) -> Option<(Operator, i64)> {\n        get_filter_time_operator(options.mtime.as_ref(), get_current_date_epoch_seconds())\n    }\n\n    pub fn get_accessed_time_operator(&self, options: &Cli) -> Option<(Operator, i64)> {\n        get_filter_time_operator(options.atime.as_ref(), get_current_date_epoch_seconds())\n    }\n\n    pub fn get_changed_time_operator(&self, options: &Cli) -> Option<(Operator, i64)> {\n        get_filter_time_operator(options.ctime.as_ref(), get_current_date_epoch_seconds())\n    }\n\n    pub fn get_collapse(&self, options: &Cli) -> Option<Vec<String>> {\n        if self.collapse.is_none() {\n            options.collapse.clone()\n        } else {\n            self.collapse.clone()\n        }\n    }\n}\n\nfn get_current_date_epoch_seconds() -> i64 {\n    // calculate current date epoch seconds\n    let now = Local::now();\n    let current_date = now.date_naive();\n\n    let current_date_time = current_date.and_hms_opt(0, 0, 0).unwrap();\n    Local\n        .from_local_datetime(&current_date_time)\n        .unwrap()\n        .timestamp()\n}\n\nfn get_filter_time_operator(\n    option_value: Option<&String>,\n    current_date_epoch_seconds: i64,\n) -> Option<(Operator, i64)> {\n    match option_value {\n        Some(val) => {\n            let time = current_date_epoch_seconds\n                - val\n                    .parse::<i64>()\n                    .unwrap_or_else(|_| panic!(\"invalid data format\"))\n                    .abs()\n                    * DAY_SECONDS;\n            match val.chars().next().expect(\"Value should not be empty\") {\n                '+' => Some((Operator::LessThan, time - DAY_SECONDS)),\n                '-' => Some((Operator::GreaterThan, time)),\n                _ => Some((Operator::Equal, time - DAY_SECONDS)),\n            }\n        }\n        None => None,\n    }\n}\n\nfn convert_min_size(input: &str) -> Option<usize> {\n    let re = Regex::new(r\"([0-9]+)(\\w*)\").unwrap();\n\n    if let Some(cap) = re.captures(input) {\n        let (_, [digits, letters]) = cap.extract();\n\n        // Failure to parse should be impossible due to regex match\n        let digits_as_usize: Option<usize> = digits.parse().ok();\n\n        match digits_as_usize {\n            Some(parsed_digits) => {\n                let number_format = get_number_format(&letters.to_lowercase());\n                match number_format {\n                    Some((multiple, _)) => Some(parsed_digits * (multiple as usize)),\n                    None => {\n                        if letters.is_empty() {\n                            Some(parsed_digits)\n                        } else {\n                            eprintln!(\"Ignoring invalid min-size: {input}\");\n                            None\n                        }\n                    }\n                }\n            }\n            None => None,\n        }\n    } else {\n        None\n    }\n}\n\nfn get_config_locations(base: PathBuf) -> Vec<PathBuf> {\n    vec![\n        base.join(\".dust.toml\"),\n        base.join(\".config\").join(\"dust\").join(\"config.toml\"),\n    ]\n}\n\npub fn get_config(conf_path: Option<&String>) -> Config {\n    match conf_path {\n        Some(path_str) => {\n            let path = Path::new(path_str);\n            if path.exists() {\n                match Config::from_config_file(path) {\n                    Ok(config) => return config,\n                    Err(e) => {\n                        eprintln!(\"Ignoring invalid config file '{}': {}\", &path.display(), e)\n                    }\n                }\n            } else {\n                eprintln!(\"Config file {:?} doesn't exists\", &path.display());\n            }\n        }\n        None => {\n            if let Some(home) = std::env::home_dir() {\n                for path in get_config_locations(home) {\n                    if path.exists()\n                        && let Ok(config) = Config::from_config_file(&path)\n                    {\n                        return config;\n                    }\n                }\n            }\n        }\n    }\n    Config {\n        ..Default::default()\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    #[allow(unused_imports)]\n    use super::*;\n    use chrono::{Datelike, Timelike};\n    use clap::Parser;\n\n    #[test]\n    fn test_get_current_date_epoch_seconds() {\n        let epoch_seconds = get_current_date_epoch_seconds();\n        let dt = Local.timestamp_opt(epoch_seconds, 0).unwrap();\n\n        assert_eq!(dt.hour(), 0);\n        assert_eq!(dt.minute(), 0);\n        assert_eq!(dt.second(), 0);\n        assert_eq!(dt.date_naive().day(), Local::now().date_naive().day());\n        assert_eq!(dt.date_naive().month(), Local::now().date_naive().month());\n        assert_eq!(dt.date_naive().year(), Local::now().date_naive().year());\n    }\n\n    #[test]\n    fn test_conversion() {\n        assert_eq!(convert_min_size(\"55\"), Some(55));\n        assert_eq!(convert_min_size(\"12344321\"), Some(12344321));\n        assert_eq!(convert_min_size(\"95RUBBISH\"), None);\n        assert_eq!(convert_min_size(\"10Ki\"), Some(10 * 1024));\n        assert_eq!(convert_min_size(\"10MiB\"), Some(10 * 1024usize.pow(2)));\n        assert_eq!(convert_min_size(\"10M\"), Some(10 * 1024usize.pow(2)));\n        assert_eq!(convert_min_size(\"10Mb\"), Some(10 * 1000usize.pow(2)));\n        assert_eq!(convert_min_size(\"2Gi\"), Some(2 * 1024usize.pow(3)));\n    }\n\n    #[test]\n    fn test_min_size_from_config_applied_or_overridden() {\n        let c = Config {\n            min_size: Some(\"1KiB\".to_owned()),\n            ..Default::default()\n        };\n        assert_eq!(c._get_min_size(None), Some(1024));\n        assert_eq!(c._get_min_size(Some(&\"2KiB\".into())), Some(2048));\n\n        assert_eq!(c._get_min_size(Some(&\"1kb\".into())), Some(1000));\n        assert_eq!(c._get_min_size(Some(&\"2KB\".into())), Some(2000));\n    }\n\n    #[test]\n    fn test_get_depth() {\n        // No config and no flag.\n        let c = Config::default();\n        let args = get_args(vec![]);\n        assert_eq!(c.get_depth(&args), usize::MAX);\n\n        // Config is not defined and flag is defined.\n        let c = Config::default();\n        let args = get_args(vec![\"dust\", \"--depth\", \"5\"]);\n        assert_eq!(c.get_depth(&args), 5);\n\n        // Config is defined and flag is not defined.\n        let c = Config {\n            depth: Some(3),\n            ..Default::default()\n        };\n        let args = get_args(vec![]);\n        assert_eq!(c.get_depth(&args), 3);\n\n        // Both config and flag are defined.\n        let c = Config {\n            depth: Some(3),\n            ..Default::default()\n        };\n        let args = get_args(vec![\"dust\", \"--depth\", \"5\"]);\n        assert_eq!(c.get_depth(&args), 5);\n    }\n\n    fn get_args(args: Vec<&str>) -> Cli {\n        Cli::parse_from(args)\n    }\n\n    #[test]\n    fn test_get_filetime() {\n        // No config and no flag.\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\"]);\n        assert_eq!(c.get_filetime(&args), None);\n\n        // Config is not defined and flag is defined as access time\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"a\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Accessed));\n\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"accessed\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Accessed));\n\n        // Config is not defined and flag is defined as modified time\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"m\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Modified));\n\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"modified\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Modified));\n\n        // Config is not defined and flag is defined as changed time\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"c\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Changed));\n\n        let c = Config::default();\n        let args = get_filetime_args(vec![\"dust\", \"--filetime\", \"changed\"]);\n        assert_eq!(c.get_filetime(&args), Some(FileTime::Changed));\n    }\n\n    fn get_filetime_args(args: Vec<&str>) -> Cli {\n        Cli::parse_from(args)\n    }\n\n    #[test]\n    fn test_get_number_of_lines() {\n        // No config and no flag.\n        let c = Config::default();\n        let args = get_args(vec![]);\n        assert_eq!(c.get_number_of_lines(&args), None);\n\n        // Config is not defined and flag is defined.\n        let c = Config::default();\n        let args = get_args(vec![\"dust\", \"--number-of-lines\", \"5\"]);\n        assert_eq!(c.get_number_of_lines(&args), Some(5));\n\n        // Config is defined and flag is not defined.\n        let c = Config {\n            number_of_lines: Some(3),\n            ..Default::default()\n        };\n        let args = get_args(vec![]);\n        assert_eq!(c.get_number_of_lines(&args), Some(3));\n\n        // Both config and flag are defined.\n        let c = Config {\n            number_of_lines: Some(3),\n            ..Default::default()\n        };\n        let args = get_args(vec![\"dust\", \"--number-of-lines\", \"5\"]);\n        assert_eq!(c.get_number_of_lines(&args), Some(5));\n    }\n}\n"
  },
  {
    "path": "src/dir_walker.rs",
    "content": "use std::cmp::Ordering;\nuse std::fs;\nuse std::io::Error;\nuse std::sync::Arc;\nuse std::sync::Mutex;\n\nuse crate::node::Node;\nuse crate::progress::ORDERING;\nuse crate::progress::Operation;\nuse crate::progress::PAtomicInfo;\nuse crate::progress::RuntimeErrors;\nuse crate::utils::is_filtered_out_due_to_file_time;\nuse crate::utils::is_filtered_out_due_to_invert_regex;\nuse crate::utils::is_filtered_out_due_to_regex;\nuse rayon::iter::ParallelBridge;\nuse rayon::prelude::ParallelIterator;\nuse regex::Regex;\nuse std::path::Path;\nuse std::path::PathBuf;\n\nuse std::collections::HashSet;\n\nuse crate::node::build_node;\nuse std::fs::DirEntry;\n\nuse crate::node::FileTime;\nuse crate::platform::get_metadata;\n\n#[derive(Debug)]\npub enum Operator {\n    Equal = 0,\n    LessThan = 1,\n    GreaterThan = 2,\n}\n\npub struct WalkData<'a> {\n    pub ignore_directories: HashSet<PathBuf>,\n    pub filter_regex: &'a [Regex],\n    pub invert_filter_regex: &'a [Regex],\n    pub allowed_filesystems: HashSet<u64>,\n    pub filter_modified_time: Option<(Operator, i64)>,\n    pub filter_accessed_time: Option<(Operator, i64)>,\n    pub filter_changed_time: Option<(Operator, i64)>,\n    pub use_apparent_size: bool,\n    pub by_filecount: bool,\n    pub by_filetime: &'a Option<FileTime>,\n    pub ignore_hidden: bool,\n    pub follow_links: bool,\n    pub progress_data: Arc<PAtomicInfo>,\n    pub errors: Arc<Mutex<RuntimeErrors>>,\n}\n\npub fn walk_it(dirs: HashSet<PathBuf>, walk_data: &WalkData) -> Vec<Node> {\n    let mut inodes = HashSet::new();\n    let top_level_nodes: Vec<_> = dirs\n        .into_iter()\n        .filter_map(|d| {\n            let prog_data = &walk_data.progress_data;\n            prog_data.clear_state(&d);\n            let node = walk(d, walk_data, 0)?;\n\n            prog_data.state.store(Operation::PREPARING, ORDERING);\n\n            clean_inodes(node, &mut inodes, walk_data)\n        })\n        .collect();\n    top_level_nodes\n}\n\n// Remove files which have the same inode, we don't want to double count them.\nfn clean_inodes(x: Node, inodes: &mut HashSet<(u64, u64)>, walk_data: &WalkData) -> Option<Node> {\n    if !walk_data.use_apparent_size\n        && let Some(id) = x.inode_device\n        && !inodes.insert(id)\n    {\n        return None;\n    }\n\n    // Sort Nodes so iteration order is predictable\n    let mut tmp: Vec<_> = x.children;\n    tmp.sort_by(sort_by_inode);\n    let new_children: Vec<_> = tmp\n        .into_iter()\n        .filter_map(|c| clean_inodes(c, inodes, walk_data))\n        .collect();\n\n    let actual_size = if walk_data.by_filetime.is_some() {\n        // If by_filetime is Some, directory 'size' is the maximum filetime among child files instead of disk size\n        new_children\n            .iter()\n            .map(|c| c.size)\n            .chain(std::iter::once(x.size))\n            .max()\n            .unwrap_or(0)\n    } else {\n        // If by_filetime is None, directory 'size' is the sum of disk sizes or file counts of child files\n        x.size + new_children.iter().map(|c| c.size).sum::<u64>()\n    };\n\n    Some(Node {\n        name: x.name,\n        size: actual_size,\n        children: new_children,\n        inode_device: x.inode_device,\n        depth: x.depth,\n    })\n}\n\nfn sort_by_inode(a: &Node, b: &Node) -> std::cmp::Ordering {\n    // Sorting by inode is quicker than by sorting by name/size\n    match (a.inode_device, b.inode_device) {\n        (Some(x), Some(y)) => {\n            if x.0 != y.0 {\n                x.0.cmp(&y.0)\n            } else if x.1 != y.1 {\n                x.1.cmp(&y.1)\n            } else {\n                a.name.cmp(&b.name)\n            }\n        }\n        (Some(_), None) => Ordering::Greater,\n        (None, Some(_)) => Ordering::Less,\n        (None, None) => a.name.cmp(&b.name),\n    }\n}\n\n// Check if `path` is inside ignored directory\nfn is_ignored_path(path: &Path, walk_data: &WalkData) -> bool {\n    if walk_data.ignore_directories.contains(path) {\n        return true;\n    }\n\n    // Entry is inside an ignored absolute path\n    // Absolute paths should be canonicalized before being added to `WalkData.ignore_directories`\n    for ignored_path in walk_data.ignore_directories.iter() {\n        if !ignored_path.is_absolute() {\n            continue;\n        }\n        let absolute_entry_path = std::fs::canonicalize(path).unwrap_or_default();\n        if absolute_entry_path.starts_with(ignored_path) {\n            return true;\n        }\n    }\n\n    false\n}\n\nfn ignore_file(entry: &DirEntry, walk_data: &WalkData) -> bool {\n    if is_ignored_path(&entry.path(), walk_data) {\n        return true;\n    }\n\n    let is_dot_file = entry.file_name().to_str().unwrap_or(\"\").starts_with('.');\n    let follow_links = walk_data.follow_links && entry.file_type().is_ok_and(|ft| ft.is_symlink());\n\n    if !walk_data.allowed_filesystems.is_empty() {\n        let size_inode_device = get_metadata(entry.path(), false, follow_links);\n        if let Some((_size, Some((_id, dev)), _gunk)) = size_inode_device\n            && !walk_data.allowed_filesystems.contains(&dev)\n        {\n            return true;\n        }\n    }\n    if walk_data.filter_accessed_time.is_some()\n        || walk_data.filter_modified_time.is_some()\n        || walk_data.filter_changed_time.is_some()\n    {\n        let size_inode_device = get_metadata(entry.path(), false, follow_links);\n        if let Some((_, _, (modified_time, accessed_time, changed_time))) = size_inode_device\n            && entry.path().is_file()\n            && [\n                (&walk_data.filter_modified_time, modified_time),\n                (&walk_data.filter_accessed_time, accessed_time),\n                (&walk_data.filter_changed_time, changed_time),\n            ]\n            .iter()\n            .any(|(filter_time, actual_time)| {\n                is_filtered_out_due_to_file_time(filter_time, *actual_time)\n            })\n        {\n            return true;\n        }\n    }\n\n    // Keeping `walk_data.filter_regex.is_empty()` is important for performance reasons, it stops unnecessary work\n    if !walk_data.filter_regex.is_empty()\n        && entry.path().is_file()\n        && is_filtered_out_due_to_regex(walk_data.filter_regex, &entry.path())\n    {\n        return true;\n    }\n\n    if !walk_data.invert_filter_regex.is_empty()\n        && entry.path().is_file()\n        && is_filtered_out_due_to_invert_regex(walk_data.invert_filter_regex, &entry.path())\n    {\n        return true;\n    }\n\n    is_dot_file && walk_data.ignore_hidden\n}\n\nfn walk(dir: PathBuf, walk_data: &WalkData, depth: usize) -> Option<Node> {\n    let prog_data = &walk_data.progress_data;\n    let errors = &walk_data.errors;\n\n    let children = if dir.is_dir() {\n        let read_dir = fs::read_dir(&dir);\n        match read_dir {\n            Ok(entries) => {\n                entries\n                    .into_iter()\n                    .par_bridge()\n                    .filter_map(|entry| {\n                        match entry {\n                            Ok(ref entry) => {\n                                // uncommenting the below line gives simpler code but\n                                // rayon doesn't parallelize as well giving a 3X performance drop\n                                // hence we unravel the recursion a bit\n\n                                // return walk(entry.path(), walk_data, depth)\n\n                                if !ignore_file(entry, walk_data)\n                                    && let Ok(data) = entry.file_type()\n                                {\n                                    if data.is_dir()\n                                        || (walk_data.follow_links && data.is_symlink())\n                                    {\n                                        return walk(entry.path(), walk_data, depth + 1);\n                                    }\n\n                                    let node = build_node(\n                                        entry.path(),\n                                        vec![],\n                                        data.is_symlink(),\n                                        data.is_file(),\n                                        depth,\n                                        walk_data,\n                                    );\n\n                                    prog_data.num_files.fetch_add(1, ORDERING);\n                                    if let Some(ref file) = node {\n                                        prog_data.total_file_size.fetch_add(file.size, ORDERING);\n                                    }\n\n                                    return node;\n                                }\n                            }\n                            Err(ref failed) => {\n                                if handle_error_and_retry(failed, &dir, walk_data) {\n                                    return walk(dir.clone(), walk_data, depth);\n                                }\n                            }\n                        }\n                        None\n                    })\n                    .collect()\n            }\n            Err(failed) => {\n                if handle_error_and_retry(&failed, &dir, walk_data) {\n                    return walk(dir, walk_data, depth);\n                } else {\n                    vec![]\n                }\n            }\n        }\n    } else {\n        if !dir.is_file() {\n            let mut editable_error = errors.lock().unwrap();\n            let bad_file = dir.as_os_str().to_string_lossy().into();\n            editable_error.file_not_found.insert(bad_file);\n        }\n        vec![]\n    };\n    let is_symlink = if walk_data.follow_links {\n        match fs::symlink_metadata(&dir) {\n            Ok(metadata) => metadata.file_type().is_symlink(),\n            Err(_) => false,\n        }\n    } else {\n        false\n    };\n    build_node(dir, children, is_symlink, false, depth, walk_data)\n}\n\nfn handle_error_and_retry(failed: &Error, dir: &Path, walk_data: &WalkData) -> bool {\n    let mut editable_error = walk_data.errors.lock().unwrap();\n    match failed.kind() {\n        std::io::ErrorKind::PermissionDenied => {\n            editable_error\n                .no_permissions\n                .insert(dir.to_string_lossy().into());\n        }\n        std::io::ErrorKind::InvalidInput => {\n            editable_error\n                .no_permissions\n                .insert(dir.to_string_lossy().into());\n        }\n        std::io::ErrorKind::NotFound => {\n            editable_error.file_not_found.insert(failed.to_string());\n        }\n        std::io::ErrorKind::Interrupted => {\n            editable_error.interrupted_error += 1;\n            // This does happen on some systems. It was set to 3 but sometimes dust runs would exceed this\n            // However, if there is no limit this results in infinite retrys and dust never finishes\n            if editable_error.interrupted_error > 999 {\n                panic!(\"Multiple Interrupted Errors occurred while scanning filesystem. Aborting\");\n            } else {\n                return true;\n            }\n        }\n        _ => {\n            editable_error.unknown_error.insert(failed.to_string());\n        }\n    }\n    false\n}\n\nmod tests {\n\n    #[allow(unused_imports)]\n    use super::*;\n\n    #[cfg(test)]\n    fn create_node() -> Node {\n        Node {\n            name: PathBuf::new(),\n            size: 10,\n            children: vec![],\n            inode_device: Some((5, 6)),\n            depth: 0,\n        }\n    }\n\n    #[cfg(test)]\n    fn create_walker<'a>(use_apparent_size: bool) -> WalkData<'a> {\n        use crate::PIndicator;\n        let indicator = PIndicator::build_me();\n        WalkData {\n            ignore_directories: HashSet::new(),\n            filter_regex: &[],\n            invert_filter_regex: &[],\n            allowed_filesystems: HashSet::new(),\n            filter_modified_time: Some((Operator::GreaterThan, 0)),\n            filter_accessed_time: Some((Operator::GreaterThan, 0)),\n            filter_changed_time: Some((Operator::GreaterThan, 0)),\n            use_apparent_size,\n            by_filecount: false,\n            by_filetime: &None,\n            ignore_hidden: false,\n            follow_links: false,\n            progress_data: indicator.data.clone(),\n            errors: Arc::new(Mutex::new(RuntimeErrors::default())),\n        }\n    }\n\n    #[test]\n    #[allow(clippy::redundant_clone)]\n    fn test_should_ignore_file() {\n        let mut inodes = HashSet::new();\n        let n = create_node();\n        let walkdata = create_walker(false);\n\n        // First time we insert the node\n        assert_eq!(\n            clean_inodes(n.clone(), &mut inodes, &walkdata),\n            Some(n.clone())\n        );\n\n        // Second time is a duplicate - we ignore it\n        assert_eq!(clean_inodes(n.clone(), &mut inodes, &walkdata), None);\n    }\n\n    #[test]\n    #[allow(clippy::redundant_clone)]\n    fn test_should_not_ignore_files_if_using_apparent_size() {\n        let mut inodes = HashSet::new();\n        let n = create_node();\n        let walkdata = create_walker(true);\n\n        // If using apparent size we include Nodes, even if duplicate inodes\n        assert_eq!(\n            clean_inodes(n.clone(), &mut inodes, &walkdata),\n            Some(n.clone())\n        );\n        assert_eq!(\n            clean_inodes(n.clone(), &mut inodes, &walkdata),\n            Some(n.clone())\n        );\n    }\n\n    #[test]\n    fn test_total_ordering_of_sort_by_inode() {\n        use std::str::FromStr;\n\n        let a = Node {\n            name: PathBuf::from_str(\"a\").unwrap(),\n            size: 0,\n            children: vec![],\n            inode_device: Some((3, 66310)),\n            depth: 0,\n        };\n\n        let b = Node {\n            name: PathBuf::from_str(\"b\").unwrap(),\n            size: 0,\n            children: vec![],\n            inode_device: None,\n            depth: 0,\n        };\n\n        let c = Node {\n            name: PathBuf::from_str(\"c\").unwrap(),\n            size: 0,\n            children: vec![],\n            inode_device: Some((1, 66310)),\n            depth: 0,\n        };\n\n        assert_eq!(sort_by_inode(&a, &b), Ordering::Greater);\n        assert_eq!(sort_by_inode(&a, &c), Ordering::Greater);\n        assert_eq!(sort_by_inode(&c, &b), Ordering::Greater);\n\n        assert_eq!(sort_by_inode(&b, &a), Ordering::Less);\n        assert_eq!(sort_by_inode(&c, &a), Ordering::Less);\n        assert_eq!(sort_by_inode(&b, &c), Ordering::Less);\n    }\n}\n"
  },
  {
    "path": "src/display.rs",
    "content": "use crate::display_node::DisplayNode;\nuse crate::node::FileTime;\n\nuse lscolors::{LsColors, Style};\nuse nu_ansi_term::Color::Red;\n\nuse unicode_width::UnicodeWidthStr;\n\nuse stfu8::encode_u8;\n\nuse chrono::{DateTime, Local, TimeZone, Utc};\nuse std::cmp::max;\nuse std::cmp::min;\nuse std::fs;\nuse std::iter::repeat_n;\nuse std::path::Path;\nuse thousands::Separable;\n\npub static UNITS: [char; 5] = ['P', 'T', 'G', 'M', 'K'];\nstatic BLOCKS: [char; 5] = ['█', '▓', '▒', '░', ' '];\nconst FILETIME_SHOW_LENGTH: usize = 19;\n\npub struct InitialDisplayData {\n    pub short_paths: bool,\n    pub is_reversed: bool,\n    pub colors_on: bool,\n    pub by_filecount: bool,\n    pub by_filetime: Option<FileTime>,\n    pub is_screen_reader: bool,\n    pub output_format: String,\n    pub bars_on_right: bool,\n}\n\npub struct DisplayData {\n    pub initial: InitialDisplayData,\n    pub num_chars_needed_on_left_most: usize,\n    pub base_size: u64,\n    pub longest_string_length: usize,\n    pub ls_colors: LsColors,\n}\n\nimpl DisplayData {\n    fn get_tree_chars(&self, was_i_last: bool, has_children: bool) -> &'static str {\n        match (self.initial.is_reversed, was_i_last, has_children) {\n            (true, true, true) => \"┌─┴\",\n            (true, true, false) => \"┌──\",\n            (true, false, true) => \"├─┴\",\n            (true, false, false) => \"├──\",\n            (false, true, true) => \"└─┬\",\n            (false, true, false) => \"└──\",\n            (false, false, true) => \"├─┬\",\n            (false, false, false) => \"├──\",\n        }\n    }\n\n    fn is_biggest(&self, num_siblings: usize, max_siblings: u64) -> bool {\n        if self.initial.is_reversed {\n            num_siblings == (max_siblings - 1) as usize\n        } else {\n            num_siblings == 0\n        }\n    }\n\n    fn is_last(&self, num_siblings: usize, max_siblings: u64) -> bool {\n        if self.initial.is_reversed {\n            num_siblings == 0\n        } else {\n            num_siblings == (max_siblings - 1) as usize\n        }\n    }\n\n    fn percent_size(&self, node: &DisplayNode) -> f32 {\n        let result = node.size as f32 / self.base_size as f32;\n        if result.is_normal() { result } else { 0.0 }\n    }\n}\n\nstruct DrawData<'a> {\n    indent: String,\n    percent_bar: String,\n    display_data: &'a DisplayData,\n}\n\nimpl DrawData<'_> {\n    fn get_new_indent(&self, has_children: bool, was_i_last: bool) -> String {\n        let chars = self.display_data.get_tree_chars(was_i_last, has_children);\n        self.indent.to_string() + chars\n    }\n\n    // TODO: can we test this?\n    fn generate_bar(&self, node: &DisplayNode, level: usize) -> String {\n        if self.display_data.initial.is_screen_reader {\n            return level.to_string();\n        }\n        let chars_in_bar = self.percent_bar.chars().count();\n        let num_bars = chars_in_bar as f32 * self.display_data.percent_size(node);\n        let mut num_not_my_bar = (chars_in_bar as i32) - num_bars as i32;\n\n        let mut new_bar = \"\".to_string();\n        let idx = 5 - level.clamp(1, 4);\n\n        let itr: Box<dyn Iterator<Item = char>> = if self.display_data.initial.bars_on_right {\n            Box::new(self.percent_bar.chars())\n        } else {\n            Box::new(self.percent_bar.chars().rev())\n        };\n\n        for c in itr {\n            num_not_my_bar -= 1;\n            if num_not_my_bar <= 0 {\n                new_bar.push(BLOCKS[0]);\n            } else if c == BLOCKS[0] {\n                new_bar.push(BLOCKS[idx]);\n            } else {\n                new_bar.push(c);\n            }\n        }\n        if self.display_data.initial.bars_on_right {\n            new_bar\n        } else {\n            new_bar.chars().rev().collect()\n        }\n    }\n}\n\npub fn draw_it(\n    idd: InitialDisplayData,\n    root_node: &DisplayNode,\n    no_percent_bars: bool,\n    terminal_width: usize,\n    skip_total: bool,\n) {\n    let num_chars_needed_on_left_most = if idd.by_filecount {\n        let max_size = root_node.size;\n        max_size.separate_with_commas().chars().count()\n    } else if idd.by_filetime.is_some() {\n        FILETIME_SHOW_LENGTH\n    } else {\n        find_biggest_size_str(root_node, &idd.output_format)\n    };\n\n    assert!(\n        terminal_width > num_chars_needed_on_left_most + 2,\n        \"Not enough terminal width\"\n    );\n\n    let allowed_width = terminal_width - num_chars_needed_on_left_most - 2;\n    let num_indent_chars = 3;\n    let longest_string_length =\n        find_longest_dir_name(root_node, num_indent_chars, allowed_width, &idd);\n\n    let max_bar_length = if no_percent_bars || longest_string_length + 7 >= allowed_width {\n        0\n    } else {\n        allowed_width - longest_string_length - 7\n    };\n\n    let first_size_bar = repeat_n(BLOCKS[0], max_bar_length).collect();\n\n    let display_data = DisplayData {\n        initial: idd,\n        num_chars_needed_on_left_most,\n        base_size: root_node.size,\n        longest_string_length,\n        ls_colors: LsColors::from_env().unwrap_or_default(),\n    };\n    let draw_data = DrawData {\n        indent: \"\".to_string(),\n        percent_bar: first_size_bar,\n        display_data: &display_data,\n    };\n\n    if !skip_total {\n        display_node(root_node, &draw_data, true, true);\n    } else {\n        for (count, c) in root_node\n            .get_children_from_node(draw_data.display_data.initial.is_reversed)\n            .enumerate()\n        {\n            let is_biggest = display_data.is_biggest(count, root_node.num_siblings());\n            let was_i_last = display_data.is_last(count, root_node.num_siblings());\n            display_node(c, &draw_data, is_biggest, was_i_last);\n        }\n    }\n}\n\nfn find_biggest_size_str(node: &DisplayNode, output_format: &str) -> usize {\n    let mut mx = human_readable_number(node.size, output_format)\n        .chars()\n        .count();\n    for n in node.children.iter() {\n        mx = max(mx, find_biggest_size_str(n, output_format));\n    }\n    mx\n}\n\nfn find_longest_dir_name(\n    node: &DisplayNode,\n    indent: usize,\n    terminal: usize,\n    idd: &InitialDisplayData,\n) -> usize {\n    let printable_name = get_printable_name(&node.name, idd.short_paths);\n\n    let longest = if idd.is_screen_reader {\n        UnicodeWidthStr::width(&*printable_name) + 1\n    } else {\n        min(\n            UnicodeWidthStr::width(&*printable_name) + 1 + indent,\n            terminal,\n        )\n    };\n\n    // each none root tree drawing is 2 more chars, hence we increment indent by 2\n    node.children\n        .iter()\n        .map(|c| find_longest_dir_name(c, indent + 2, terminal, idd))\n        .fold(longest, max)\n}\n\nfn display_node(node: &DisplayNode, draw_data: &DrawData, is_biggest: bool, is_last: bool) {\n    // hacky way of working out how deep we are in the tree\n    let indent = draw_data.get_new_indent(!node.children.is_empty(), is_last);\n    let level = ((indent.chars().count() - 1) / 2) - 1;\n    let bar_text = draw_data.generate_bar(node, level);\n\n    let to_print = format_string(node, &indent, &bar_text, is_biggest, draw_data.display_data);\n\n    if !draw_data.display_data.initial.is_reversed {\n        println!(\"{to_print}\")\n    }\n\n    let dd = DrawData {\n        indent: clean_indentation_string(&indent),\n        percent_bar: bar_text,\n        display_data: draw_data.display_data,\n    };\n\n    let num_siblings = node.num_siblings();\n\n    for (count, c) in node\n        .get_children_from_node(draw_data.display_data.initial.is_reversed)\n        .enumerate()\n    {\n        let is_biggest = dd.display_data.is_biggest(count, num_siblings);\n        let was_i_last = dd.display_data.is_last(count, num_siblings);\n        display_node(c, &dd, is_biggest, was_i_last);\n    }\n\n    if draw_data.display_data.initial.is_reversed {\n        println!(\"{to_print}\")\n    }\n}\n\nfn clean_indentation_string(s: &str) -> String {\n    let mut is: String = s.into();\n    // For reversed:\n    is = is.replace(\"┌─┴\", \"  \");\n    is = is.replace(\"┌──\", \"  \");\n    is = is.replace(\"├─┴\", \"│ \");\n    is = is.replace(\"─┴\", \" \");\n    // For normal\n    is = is.replace(\"└─┬\", \"  \");\n    is = is.replace(\"└──\", \"  \");\n    is = is.replace(\"├─┬\", \"│ \");\n    is = is.replace(\"─┬\", \" \");\n    // For both\n    is = is.replace(\"├──\", \"│ \");\n    is\n}\n\npub fn get_printable_name<P: AsRef<Path>>(dir_name: &P, short_paths: bool) -> String {\n    let dir_name = dir_name.as_ref();\n    let printable_name = {\n        if short_paths {\n            match dir_name.parent() {\n                Some(prefix) => match dir_name.strip_prefix(prefix) {\n                    Ok(base) => base,\n                    Err(_) => dir_name,\n                },\n                None => dir_name,\n            }\n        } else {\n            dir_name\n        }\n    };\n    encode_u8(printable_name.display().to_string().as_bytes())\n}\n\nfn pad_or_trim_filename(node: &DisplayNode, indent: &str, display_data: &DisplayData) -> String {\n    let name = get_printable_name(&node.name, display_data.initial.short_paths);\n    let indent_and_name = format!(\"{indent} {name}\");\n    let width = UnicodeWidthStr::width(&*indent_and_name);\n\n    assert!(\n        display_data.longest_string_length >= width,\n        \"Terminal width not wide enough to draw directory tree\"\n    );\n\n    // Add spaces after the filename so we can draw the % used bar chart.\n    name + \" \"\n        .repeat(display_data.longest_string_length - width)\n        .as_str()\n}\n\nfn maybe_trim_filename(name_in: String, indent: &str, display_data: &DisplayData) -> String {\n    let indent_length = UnicodeWidthStr::width(indent);\n    assert!(\n        display_data.longest_string_length >= indent_length + 2,\n        \"Terminal width not wide enough to draw directory tree\"\n    );\n\n    let max_size = display_data.longest_string_length - indent_length;\n    if UnicodeWidthStr::width(&*name_in) > max_size {\n        let name = name_in.chars().take(max_size - 2).collect::<String>();\n        name + \"..\"\n    } else {\n        name_in\n    }\n}\n\npub fn format_string(\n    node: &DisplayNode,\n    indent: &str,\n    bars: &str,\n    is_biggest: bool,\n    display_data: &DisplayData,\n) -> String {\n    let (percent, name_and_padding) = get_name_percent(node, indent, bars, display_data);\n    let pretty_size = get_pretty_size(node, is_biggest, display_data);\n    let pretty_name = get_pretty_name(node, name_and_padding, display_data);\n    // we can clean this and the method below somehow, not sure yet\n    if display_data.initial.is_screen_reader {\n        // if screen_reader then bars is 'depth'\n        format!(\"{pretty_name} {bars} {pretty_size}{percent}\")\n    } else if display_data.initial.by_filetime.is_some() {\n        format!(\"{pretty_size} {indent}{pretty_name}\")\n    } else {\n        format!(\"{pretty_size} {indent} {pretty_name}{percent}\")\n    }\n}\n\nfn get_name_percent(\n    node: &DisplayNode,\n    indent: &str,\n    bar_chart: &str,\n    display_data: &DisplayData,\n) -> (String, String) {\n    if display_data.initial.is_screen_reader {\n        let percent = display_data.percent_size(node) * 100.0;\n        let percent_size_str = format!(\"{percent:.0}%\");\n        let percents = format!(\" {percent_size_str:>4}\",);\n        let name = pad_or_trim_filename(node, \"\", display_data);\n        (percents, name)\n    // Bar chart being empty may come from either config or the screen not being wide enough\n    } else if !bar_chart.is_empty() {\n        let percent = display_data.percent_size(node) * 100.0;\n        let percent_size_str = format!(\"{percent:.0}%\");\n        let percents = format!(\"│{bar_chart} │ {percent_size_str:>4}\");\n        let name_and_padding = pad_or_trim_filename(node, indent, display_data);\n        (percents, name_and_padding)\n    } else {\n        let n = get_printable_name(&node.name, display_data.initial.short_paths);\n        let name = maybe_trim_filename(n, indent, display_data);\n        (\"\".into(), name)\n    }\n}\n\nfn get_pretty_size(node: &DisplayNode, is_biggest: bool, display_data: &DisplayData) -> String {\n    let output = if display_data.initial.by_filecount {\n        node.size.separate_with_commas()\n    } else if display_data.initial.by_filetime.is_some() {\n        get_pretty_file_modified_time(node.size as i64)\n    } else {\n        human_readable_number(node.size, &display_data.initial.output_format)\n    };\n    let spaces_to_add = display_data.num_chars_needed_on_left_most - output.chars().count();\n    let output = \" \".repeat(spaces_to_add) + output.as_str();\n\n    if is_biggest && display_data.initial.colors_on {\n        format!(\"{}\", Red.paint(output))\n    } else {\n        output\n    }\n}\n\nfn get_pretty_file_modified_time(timestamp: i64) -> String {\n    let datetime: DateTime<Utc> = Utc.timestamp_opt(timestamp, 0).unwrap();\n\n    let local_datetime = datetime.with_timezone(&Local);\n\n    local_datetime.format(\"%Y-%m-%dT%H:%M:%S\").to_string()\n}\n\nfn get_pretty_name(\n    node: &DisplayNode,\n    name_and_padding: String,\n    display_data: &DisplayData,\n) -> String {\n    if display_data.initial.colors_on {\n        let meta_result = fs::metadata(&node.name);\n        let directory_color = display_data\n            .ls_colors\n            .style_for_path_with_metadata(&node.name, meta_result.as_ref().ok());\n        let ansi_style = directory_color\n            .map(Style::to_nu_ansi_term_style)\n            .unwrap_or_default();\n        let out = ansi_style.paint(name_and_padding);\n        format!(\"{out}\")\n    } else {\n        name_and_padding\n    }\n}\n\n// If we are working with SI units or not\npub fn get_type_of_thousand(output_str: &str) -> u64 {\n    if output_str.is_empty() {\n        1024\n    } else if output_str == \"si\" {\n        1000\n    } else if output_str.contains('i') || output_str.len() == 1 {\n        1024\n    } else {\n        1000\n    }\n}\n\npub fn get_number_format(output_str: &str) -> Option<(u64, char)> {\n    if output_str.starts_with('b') {\n        return Some((1, 'B'));\n    }\n    for (i, u) in UNITS.iter().enumerate() {\n        if output_str.starts_with((*u).to_ascii_lowercase()) {\n            let marker = get_type_of_thousand(output_str).pow((UNITS.len() - i) as u32);\n            return Some((marker, *u));\n        }\n    }\n    None\n}\n\npub fn human_readable_number(size: u64, output_str: &str) -> String {\n    if output_str == \"count\" {\n        return size.to_string();\n    };\n    match get_number_format(output_str) {\n        Some((x, u)) => {\n            format!(\"{}{}\", (size / x), u)\n        }\n        None => {\n            for (i, u) in UNITS.iter().enumerate() {\n                let marker = get_type_of_thousand(output_str).pow((UNITS.len() - i) as u32);\n                if size >= marker {\n                    if size / marker < 10 {\n                        return format!(\"{:.1}{}\", (size as f32 / marker as f32), u);\n                    } else {\n                        return format!(\"{}{}\", (size / marker), u);\n                    }\n                }\n            }\n            format!(\"{size}B\")\n        }\n    }\n}\n\nmod tests {\n    #[allow(unused_imports)]\n    use super::*;\n    #[allow(unused_imports)]\n    use std::path::PathBuf;\n\n    #[cfg(test)]\n    fn get_fake_display_data(longest_string_length: usize) -> DisplayData {\n        let initial = InitialDisplayData {\n            short_paths: true,\n            is_reversed: false,\n            colors_on: false,\n            by_filecount: false,\n            by_filetime: None,\n            is_screen_reader: false,\n            output_format: \"\".into(),\n            bars_on_right: false,\n        };\n        DisplayData {\n            initial,\n            num_chars_needed_on_left_most: 5,\n            base_size: 2_u64.pow(12), // 4.0K\n            longest_string_length,\n            ls_colors: LsColors::from_env().unwrap_or_default(),\n        }\n    }\n\n    #[test]\n    fn test_format_str() {\n        let n = DisplayNode {\n            name: PathBuf::from(\"/short\"),\n            size: 2_u64.pow(12), // This is 4.0K\n            children: vec![],\n        };\n        let indent = \"┌─┴\";\n        let percent_bar = \"\";\n        let is_biggest = false;\n        let data = get_fake_display_data(20);\n\n        let s = format_string(&n, indent, percent_bar, is_biggest, &data);\n        assert_eq!(s, \" 4.0K ┌─┴ short\");\n    }\n\n    #[test]\n    fn test_format_str_long_name() {\n        let name = \"very_long_name_longer_than_the_eighty_character_limit_very_long_name_this_bit_will_truncate\";\n        let n = DisplayNode {\n            name: PathBuf::from(name),\n            size: 2_u64.pow(12), // This is 4.0K\n            children: vec![],\n        };\n        let indent = \"┌─┴\";\n        let percent_bar = \"\";\n        let is_biggest = false;\n\n        let data = get_fake_display_data(64);\n        let s = format_string(&n, indent, percent_bar, is_biggest, &data);\n        assert_eq!(\n            s,\n            \" 4.0K ┌─┴ very_long_name_longer_than_the_eighty_character_limit_very_..\"\n        );\n    }\n\n    #[test]\n    fn test_format_str_screen_reader() {\n        let n = DisplayNode {\n            name: PathBuf::from(\"/short\"),\n            size: 2_u64.pow(12), // This is 4.0K\n            children: vec![],\n        };\n        let indent = \"\";\n        let percent_bar = \"3\";\n        let is_biggest = false;\n        let mut data = get_fake_display_data(20);\n        data.initial.is_screen_reader = true;\n\n        let s = format_string(&n, indent, percent_bar, is_biggest, &data);\n        assert_eq!(s, \"short               3  4.0K 100%\");\n    }\n\n    #[test]\n    fn test_machine_readable_filecount() {\n        assert_eq!(human_readable_number(1, \"count\"), \"1\");\n        assert_eq!(human_readable_number(1000, \"count\"), \"1000\");\n        assert_eq!(human_readable_number(1024, \"count\"), \"1024\");\n    }\n\n    #[test]\n    fn test_human_readable_number() {\n        assert_eq!(human_readable_number(1, \"\"), \"1B\");\n        assert_eq!(human_readable_number(956, \"\"), \"956B\");\n        assert_eq!(human_readable_number(1004, \"\"), \"1004B\");\n        assert_eq!(human_readable_number(1024, \"\"), \"1.0K\");\n        assert_eq!(human_readable_number(1536, \"\"), \"1.5K\");\n        assert_eq!(human_readable_number(1024 * 512, \"\"), \"512K\");\n        assert_eq!(human_readable_number(1024 * 1024, \"\"), \"1.0M\");\n        assert_eq!(human_readable_number(1024 * 1024 * 1024 - 1, \"\"), \"1023M\");\n        assert_eq!(human_readable_number(1024 * 1024 * 1024 * 20, \"\"), \"20G\");\n        assert_eq!(human_readable_number(1024 * 1024 * 1024 * 1024, \"\"), \"1.0T\");\n        assert_eq!(\n            human_readable_number(1024 * 1024 * 1024 * 1024 * 234, \"\"),\n            \"234T\"\n        );\n        assert_eq!(\n            human_readable_number(1024 * 1024 * 1024 * 1024 * 1024, \"\"),\n            \"1.0P\"\n        );\n    }\n\n    #[test]\n    fn test_human_readable_number_si() {\n        assert_eq!(human_readable_number(1024 * 100, \"\"), \"100K\");\n        assert_eq!(human_readable_number(1024 * 100, \"si\"), \"102K\");\n    }\n\n    // Refer to https://en.wikipedia.org/wiki/Byte#Multiple-byte_units\n    #[test]\n    fn test_human_readable_number_kb() {\n        let hrn = human_readable_number;\n        assert_eq!(hrn(1023, \"b\"), \"1023B\");\n        assert_eq!(hrn(1000 * 1000, \"bytes\"), \"1000000B\");\n        assert_eq!(hrn(1023, \"kb\"), \"1K\");\n        assert_eq!(hrn(1023, \"k\"), \"0K\");\n        assert_eq!(hrn(1023, \"kib\"), \"0K\");\n        assert_eq!(hrn(1024, \"kib\"), \"1K\");\n        assert_eq!(hrn(1024 * 512, \"kib\"), \"512K\");\n        assert_eq!(hrn(1024 * 1024, \"kib\"), \"1024K\");\n        assert_eq!(hrn(1024 * 1000 * 1000 * 20, \"kib\"), \"20000000K\");\n        assert_eq!(hrn(1024 * 1024 * 1000 * 20, \"mib\"), \"20000M\");\n        assert_eq!(hrn(1024 * 1024 * 1024 * 20, \"gib\"), \"20G\");\n    }\n\n    #[cfg(test)]\n    fn build_draw_data(disp: &DisplayData, size: u32) -> (DrawData<'_>, DisplayNode) {\n        let n = DisplayNode {\n            name: PathBuf::from(\"/short\"),\n            size: 2_u64.pow(size),\n            children: vec![],\n        };\n        let first_size_bar = repeat_n(BLOCKS[0], 13).collect();\n        let dd = DrawData {\n            indent: \"\".into(),\n            percent_bar: first_size_bar,\n            display_data: disp,\n        };\n        (dd, n)\n    }\n\n    #[test]\n    fn test_draw_data() {\n        let disp = &get_fake_display_data(20);\n        let (dd, n) = build_draw_data(disp, 12);\n        let bar = dd.generate_bar(&n, 1);\n        assert_eq!(bar, \"█████████████\");\n    }\n\n    #[test]\n    fn test_draw_data2() {\n        let disp = &get_fake_display_data(20);\n        let (dd, n) = build_draw_data(disp, 11);\n        let bar = dd.generate_bar(&n, 2);\n        assert_eq!(bar, \"███████░░░░░░\");\n    }\n    #[test]\n    fn test_draw_data3() {\n        let mut disp = get_fake_display_data(20);\n        let (dd, n) = build_draw_data(&disp, 11);\n        let bar = dd.generate_bar(&n, 3);\n        assert_eq!(bar, \"███████▒▒▒▒▒▒\");\n\n        disp.initial.bars_on_right = true;\n        let (dd, n) = build_draw_data(&disp, 11);\n        let bar = dd.generate_bar(&n, 3);\n        assert_eq!(bar, \"▒▒▒▒▒▒███████\")\n    }\n    #[test]\n    fn test_draw_data4() {\n        let disp = &get_fake_display_data(20);\n        let (dd, n) = build_draw_data(disp, 10);\n        // After 4 we have no more levels of shading so 4+ is the same\n        let bar = dd.generate_bar(&n, 4);\n        assert_eq!(bar, \"████▓▓▓▓▓▓▓▓▓\");\n        let bar = dd.generate_bar(&n, 5);\n        assert_eq!(bar, \"████▓▓▓▓▓▓▓▓▓\");\n    }\n\n    #[test]\n    fn test_get_pretty_file_modified_time() {\n        // Create a timestamp for 2023-07-12 00:00:00 in local time\n        let local_dt = Local.with_ymd_and_hms(2023, 7, 12, 0, 0, 0).unwrap();\n        let timestamp = local_dt.timestamp();\n\n        // Format expected output\n        let expected_output = local_dt.format(\"%Y-%m-%dT%H:%M:%S\").to_string();\n\n        assert_eq!(get_pretty_file_modified_time(timestamp), expected_output);\n\n        // Test another timestamp\n        let local_dt = Local.with_ymd_and_hms(2020, 1, 1, 12, 0, 0).unwrap();\n        let timestamp = local_dt.timestamp();\n        let expected_output = local_dt.format(\"%Y-%m-%dT%H:%M:%S\").to_string();\n\n        assert_eq!(get_pretty_file_modified_time(timestamp), expected_output);\n\n        // Test timestamp for epoch start (1970-01-01T00:00:00)\n        let local_dt = Local.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap();\n        let timestamp = local_dt.timestamp();\n        let expected_output = local_dt.format(\"%Y-%m-%dT%H:%M:%S\").to_string();\n\n        assert_eq!(get_pretty_file_modified_time(timestamp), expected_output);\n\n        // Test a future timestamp\n        let local_dt = Local.with_ymd_and_hms(2030, 12, 25, 6, 30, 0).unwrap();\n        let timestamp = local_dt.timestamp();\n        let expected_output = local_dt.format(\"%Y-%m-%dT%H:%M:%S\").to_string();\n\n        assert_eq!(get_pretty_file_modified_time(timestamp), expected_output);\n    }\n}\n"
  },
  {
    "path": "src/display_node.rs",
    "content": "use std::cell::RefCell;\nuse std::path::PathBuf;\n\nuse serde::ser::SerializeStruct;\nuse serde::{Serialize, Serializer};\n\nuse crate::display::human_readable_number;\n\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]\npub struct DisplayNode {\n    // Note: the order of fields in important here, for PartialEq and PartialOrd\n    pub size: u64,\n    pub name: PathBuf,\n    pub children: Vec<DisplayNode>,\n}\n\nimpl DisplayNode {\n    pub fn num_siblings(&self) -> u64 {\n        self.children.len() as u64\n    }\n\n    pub fn get_children_from_node(&self, is_reversed: bool) -> impl Iterator<Item = &DisplayNode> {\n        // we box to avoid the clippy lint warning\n        let out: Box<dyn Iterator<Item = &DisplayNode>> = if is_reversed {\n            Box::new(self.children.iter().rev())\n        } else {\n            Box::new(self.children.iter())\n        };\n        out\n    }\n}\n\n// Only used for -j 'json' flag combined with -o 'output_type' flag\n// Used to pass the output_type into the custom Serde serializer\nthread_local! {\n    pub static OUTPUT_TYPE: RefCell<String> = const { RefCell::new(String::new()) };\n}\n\n/*\nWe need the custom Serialize incase someone uses the -o flag to pass a custom output type in\n(show size in Mb / Gb etc).\nSadly this also necessitates a global variable OUTPUT_TYPE as we can not pass the output_type flag\ninto the serialize method\n */\nimpl Serialize for DisplayNode {\n    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {\n        let readable_size = OUTPUT_TYPE\n            .with(|output_type| human_readable_number(self.size, output_type.borrow().as_str()));\n        let mut state = serializer.serialize_struct(\"DisplayNode\", 2)?;\n        state.serialize_field(\"size\", &(readable_size))?;\n        state.serialize_field(\"name\", &self.name)?;\n        state.serialize_field(\"children\", &self.children)?;\n        state.end()\n    }\n}\n"
  },
  {
    "path": "src/filter.rs",
    "content": "use stfu8::encode_u8;\n\nuse crate::display::get_printable_name;\nuse crate::display_node::DisplayNode;\nuse crate::node::FileTime;\nuse crate::node::Node;\nuse std::collections::BinaryHeap;\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::path::Path;\nuse std::path::PathBuf;\n\npub struct AggregateData {\n    pub min_size: Option<usize>,\n    pub only_dir: bool,\n    pub only_file: bool,\n    pub number_of_lines: usize,\n    pub depth: usize,\n    pub using_a_filter: bool,\n    pub short_paths: bool,\n}\n\npub fn get_biggest(\n    top_level_nodes: Vec<Node>,\n    display_data: AggregateData,\n    by_filetime: &Option<FileTime>,\n    keep_collapsed: HashSet<PathBuf>,\n) -> DisplayNode {\n    let mut heap = BinaryHeap::new();\n    let number_top_level_nodes = top_level_nodes.len();\n    let root;\n\n    if number_top_level_nodes == 0 {\n        root = total_node_builder(0, vec![])\n    } else if number_top_level_nodes > 1 {\n        let size = if by_filetime.is_some() {\n            top_level_nodes\n                .iter()\n                .map(|node| node.size)\n                .max()\n                .unwrap_or(0)\n        } else {\n            top_level_nodes.iter().map(|node| node.size).sum()\n        };\n\n        let nodes = handle_duplicate_top_level_names(top_level_nodes, display_data.short_paths);\n        root = total_node_builder(size, nodes);\n        heap = always_add_children(&display_data, &root, heap);\n    } else {\n        root = top_level_nodes.into_iter().next().unwrap();\n        heap = add_children(&display_data, &root, heap);\n    }\n\n    fill_remaining_lines(heap, &root, display_data, keep_collapsed)\n}\n\nfn total_node_builder(size: u64, children: Vec<Node>) -> Node {\n    Node {\n        name: PathBuf::from(\"(total)\"),\n        size,\n        children,\n        inode_device: None,\n        depth: 0,\n    }\n}\n\npub fn fill_remaining_lines<'a>(\n    mut heap: BinaryHeap<&'a Node>,\n    root: &'a Node,\n    display_data: AggregateData,\n    keep_collapsed: HashSet<PathBuf>,\n) -> DisplayNode {\n    let mut allowed_nodes = HashMap::new();\n\n    while allowed_nodes.len() < display_data.number_of_lines {\n        let line = heap.pop();\n        match line {\n            Some(line) => {\n                // If we are not doing only_file OR if we are doing\n                // only_file and it has no children (ie is a file not a dir)\n                if !display_data.only_file || line.children.is_empty() {\n                    allowed_nodes.insert(line.name.as_path(), line);\n                }\n                if !keep_collapsed.contains(&line.name) {\n                    heap = add_children(&display_data, line, heap);\n                }\n            }\n            None => break,\n        }\n    }\n\n    if display_data.only_file {\n        flat_rebuilder(allowed_nodes, root)\n    } else {\n        recursive_rebuilder(&allowed_nodes, root)\n    }\n}\n\nfn add_children<'a>(\n    display_data: &AggregateData,\n    file_or_folder: &'a Node,\n    heap: BinaryHeap<&'a Node>,\n) -> BinaryHeap<&'a Node> {\n    if display_data.depth > file_or_folder.depth {\n        always_add_children(display_data, file_or_folder, heap)\n    } else {\n        heap\n    }\n}\n\nfn always_add_children<'a>(\n    display_data: &AggregateData,\n    file_or_folder: &'a Node,\n    mut heap: BinaryHeap<&'a Node>,\n) -> BinaryHeap<&'a Node> {\n    heap.extend(\n        file_or_folder\n            .children\n            .iter()\n            .filter(|c| match display_data.min_size {\n                Some(ms) => c.size > ms as u64,\n                None => !display_data.using_a_filter || c.name.is_file() || c.size > 0,\n            })\n            .filter(|c| {\n                if display_data.only_dir {\n                    c.name.is_dir()\n                } else {\n                    true\n                }\n            }),\n    );\n    heap\n}\n\n// Finds children of current, if in allowed_nodes adds them as children to new DisplayNode\nfn recursive_rebuilder(allowed_nodes: &HashMap<&Path, &Node>, current: &Node) -> DisplayNode {\n    let new_children: Vec<_> = current\n        .children\n        .iter()\n        .filter(|c| allowed_nodes.contains_key(c.name.as_path()))\n        .map(|c| recursive_rebuilder(allowed_nodes, c))\n        .collect();\n\n    build_display_node(new_children, current)\n}\n\n// Applies all allowed nodes as children to current node\nfn flat_rebuilder(allowed_nodes: HashMap<&Path, &Node>, current: &Node) -> DisplayNode {\n    let new_children: Vec<DisplayNode> = allowed_nodes\n        .into_values()\n        .map(|v| DisplayNode {\n            name: v.name.clone(),\n            size: v.size,\n            children: vec![],\n        })\n        .collect::<Vec<DisplayNode>>();\n    build_display_node(new_children, current)\n}\n\nfn build_display_node(mut new_children: Vec<DisplayNode>, current: &Node) -> DisplayNode {\n    new_children.sort_by(|lhs, rhs| lhs.cmp(rhs).reverse());\n    DisplayNode {\n        name: current.name.clone(),\n        size: current.size,\n        children: new_children,\n    }\n}\n\nfn names_have_dup(top_level_nodes: &Vec<Node>) -> bool {\n    let mut stored = HashSet::new();\n    for node in top_level_nodes {\n        let name = get_printable_name(&node.name, true);\n        if stored.contains(&name) {\n            return true;\n        }\n        stored.insert(name);\n    }\n    false\n}\n\nfn handle_duplicate_top_level_names(top_level_nodes: Vec<Node>, short_paths: bool) -> Vec<Node> {\n    // If we have top level names that are the same - we need to tweak them:\n    if short_paths && names_have_dup(&top_level_nodes) {\n        let mut new_top_nodes = top_level_nodes.clone();\n        let mut dir_walk_up_count = 0;\n\n        while names_have_dup(&new_top_nodes) && dir_walk_up_count < 10 {\n            dir_walk_up_count += 1;\n            let mut newer = vec![];\n\n            for node in new_top_nodes.iter() {\n                let mut folders = node.name.iter().rev();\n                // Get parent folder (if second time round get grandparent and so on)\n                for _ in 0..dir_walk_up_count {\n                    folders.next();\n                }\n                match folders.next() {\n                    // Add (parent_name) to path of Node\n                    Some(data) => {\n                        let parent = encode_u8(data.as_encoded_bytes());\n                        let current_node = node.name.display();\n                        let n = Node {\n                            name: PathBuf::from(format!(\"{current_node}({parent})\")),\n                            size: node.size,\n                            children: node.children.clone(),\n                            inode_device: node.inode_device,\n                            depth: node.depth,\n                        };\n                        newer.push(n)\n                    }\n                    // Node does not have a parent\n                    None => newer.push(node.clone()),\n                }\n            }\n            new_top_nodes = newer;\n        }\n        new_top_nodes\n    } else {\n        top_level_nodes\n    }\n}\n"
  },
  {
    "path": "src/filter_type.rs",
    "content": "use crate::display_node::DisplayNode;\nuse crate::node::FileTime;\nuse crate::node::Node;\nuse std::collections::HashMap;\nuse std::ffi::OsStr;\nuse std::path::PathBuf;\n\n#[derive(PartialEq, Eq, PartialOrd, Ord)]\nstruct ExtensionNode<'a> {\n    size: u64,\n    extension: Option<&'a OsStr>,\n}\n\npub fn get_all_file_types(\n    top_level_nodes: &[Node],\n    n: usize,\n    by_filetime: &Option<FileTime>,\n) -> DisplayNode {\n    let ext_nodes = {\n        let mut extension_cumulative_sizes = HashMap::new();\n        build_by_all_file_types(top_level_nodes, &mut extension_cumulative_sizes);\n\n        let mut extension_cumulative_sizes: Vec<ExtensionNode<'_>> = extension_cumulative_sizes\n            .iter()\n            .map(|(&extension, &size)| ExtensionNode { extension, size })\n            .collect();\n\n        extension_cumulative_sizes.sort_by(|lhs, rhs| lhs.cmp(rhs).reverse());\n\n        extension_cumulative_sizes\n    };\n\n    let mut ext_nodes_iter = ext_nodes.iter();\n\n    // First, collect the first N - 1 nodes...\n    let mut displayed: Vec<DisplayNode> = ext_nodes_iter\n        .by_ref()\n        .take(if n > 1 { n - 1 } else { 1 })\n        .map(|node| DisplayNode {\n            name: PathBuf::from(\n                node.extension\n                    .map(|ext| format!(\".{}\", ext.to_string_lossy()))\n                    .unwrap_or_else(|| \"(no extension)\".to_owned()),\n            ),\n            size: node.size,\n            children: vec![],\n        })\n        .collect();\n\n    // ...then, aggregate the remaining nodes (if any) into a single  \"(others)\" node\n    if ext_nodes_iter.len() > 0 {\n        let actual_size = if by_filetime.is_some() {\n            ext_nodes_iter.map(|node| node.size).max().unwrap_or(0)\n        } else {\n            ext_nodes_iter.map(|node| node.size).sum()\n        };\n        displayed.push(DisplayNode {\n            name: PathBuf::from(\"(others)\"),\n            size: actual_size,\n            children: vec![],\n        });\n    }\n\n    let actual_size: u64 = if by_filetime.is_some() {\n        displayed.iter().map(|node| node.size).max().unwrap_or(0)\n    } else {\n        displayed.iter().map(|node| node.size).sum()\n    };\n\n    DisplayNode {\n        name: PathBuf::from(\"(total)\"),\n        size: actual_size,\n        children: displayed,\n    }\n}\n\nfn build_by_all_file_types<'a>(\n    top_level_nodes: &'a [Node],\n    counter: &mut HashMap<Option<&'a OsStr>, u64>,\n) {\n    for node in top_level_nodes {\n        if node.name.is_file() {\n            let ext = node.name.extension();\n            let cumulative_size = counter.entry(ext).or_default();\n            *cumulative_size += node.size;\n        }\n        build_by_all_file_types(&node.children, counter)\n    }\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "mod cli;\nmod config;\nmod dir_walker;\nmod display;\nmod display_node;\nmod filter;\nmod filter_type;\nmod node;\nmod platform;\nmod progress;\nmod utils;\n\nuse crate::cli::Cli;\nuse crate::config::Config;\nuse crate::display_node::DisplayNode;\nuse crate::progress::RuntimeErrors;\nuse clap::Parser;\nuse dir_walker::WalkData;\nuse display::InitialDisplayData;\nuse filter::AggregateData;\nuse progress::PIndicator;\nuse regex::Error;\nuse std::collections::HashSet;\nuse std::env;\nuse std::fs::{read, read_to_string};\nuse std::io;\nuse std::io::Read;\nuse std::panic;\nuse std::process;\nuse std::sync::Arc;\nuse std::sync::Mutex;\nuse sysinfo::System;\nuse utils::canonicalize_absolute_path;\n\nuse self::display::draw_it;\nuse config::get_config;\nuse dir_walker::walk_it;\nuse display_node::OUTPUT_TYPE;\nuse filter::get_biggest;\nuse filter_type::get_all_file_types;\nuse regex::Regex;\nuse std::cmp::max;\nuse std::path::PathBuf;\nuse terminal_size::{Height, Width, terminal_size};\nuse utils::get_filesystem_devices;\nuse utils::simplify_dir_names;\n\nstatic DEFAULT_NUMBER_OF_LINES: usize = 30;\nstatic DEFAULT_TERMINAL_WIDTH: usize = 80;\n\nfn should_init_color(no_color: bool, force_color: bool) -> bool {\n    if force_color {\n        return true;\n    }\n    if no_color {\n        return false;\n    }\n    // check if NO_COLOR is set\n    // https://no-color.org/\n    if env::var_os(\"NO_COLOR\").is_some() {\n        return false;\n    }\n    if terminal_size().is_none() {\n        // we are not in a terminal, color may not be needed\n        return false;\n    }\n    // we are in a terminal\n    #[cfg(windows)]\n    {\n        // Required for windows 10\n        // Fails to resolve for windows 8 so disable color\n        match nu_ansi_term::enable_ansi_support() {\n            Ok(_) => true,\n            Err(_) => {\n                eprintln!(\"This version of Windows does not support ANSI colors\");\n                false\n            }\n        }\n    }\n    #[cfg(not(windows))]\n    {\n        true\n    }\n}\n\nfn get_height_of_terminal() -> usize {\n    terminal_size()\n        // Windows CI runners detect a terminal height of 0\n        .map(|(_, Height(h))| max(h.into(), DEFAULT_NUMBER_OF_LINES))\n        .unwrap_or(DEFAULT_NUMBER_OF_LINES)\n        - 10\n}\n\nfn get_width_of_terminal() -> usize {\n    terminal_size()\n        .map(|(Width(w), _)| match cfg!(windows) {\n            // Windows CI runners detect a very low terminal width\n            true => max(w.into(), DEFAULT_TERMINAL_WIDTH),\n            false => w.into(),\n        })\n        .unwrap_or(DEFAULT_TERMINAL_WIDTH)\n}\n\nfn get_regex_value(maybe_value: Option<&Vec<String>>) -> Vec<Regex> {\n    maybe_value\n        .unwrap_or(&Vec::new())\n        .iter()\n        .map(|reg| {\n            Regex::new(reg).unwrap_or_else(|err| {\n                eprintln!(\"Ignoring bad value for regex {err:?}\");\n                process::exit(1)\n            })\n        })\n        .collect()\n}\n\nfn main() {\n    let options = Cli::parse();\n    let config = get_config(options.config.as_ref());\n\n    let errors = RuntimeErrors::default();\n    let error_listen_for_ctrlc = Arc::new(Mutex::new(errors));\n    let errors_for_rayon = error_listen_for_ctrlc.clone();\n\n    ctrlc::set_handler(move || {\n        println!(\"\\nAborting\");\n        process::exit(1);\n    })\n    .expect(\"Error setting Ctrl-C handler\");\n\n    let target_dirs = if let Some(path) = config.get_files0_from(&options) {\n        read_paths_from_source(&path, true)\n    } else if let Some(path) = config.get_files_from(&options) {\n        read_paths_from_source(&path, false)\n    } else {\n        match options.params {\n            Some(ref values) => values.clone(),\n            None => vec![\".\".to_owned()],\n        }\n    };\n\n    let summarize_file_types = options.file_types;\n\n    let filter_regexs = get_regex_value(options.filter.as_ref());\n    let invert_filter_regexs = get_regex_value(options.invert_filter.as_ref());\n\n    let terminal_width: usize = match options.terminal_width {\n        Some(val) => val,\n        None => get_width_of_terminal(),\n    };\n\n    let depth = config.get_depth(&options);\n\n    // If depth is set, then we set the default number_of_lines to be max\n    // instead of screen height\n\n    let number_of_lines = match config.get_number_of_lines(&options) {\n        Some(val) => val,\n        None => {\n            if depth != usize::MAX {\n                usize::MAX\n            } else {\n                get_height_of_terminal()\n            }\n        }\n    };\n\n    let is_colors = should_init_color(\n        config.get_no_colors(&options),\n        config.get_force_colors(&options),\n    );\n\n    let ignore_directories = match options.ignore_directory {\n        Some(ref values) => values\n            .iter()\n            .map(PathBuf::from)\n            .map(canonicalize_absolute_path)\n            .collect::<Vec<PathBuf>>(),\n        None => vec![],\n    };\n\n    let ignore_from_file_result = match options.ignore_all_in_file {\n        Some(ref val) => read_to_string(val)\n            .unwrap()\n            .lines()\n            .map(Regex::new)\n            .collect::<Vec<Result<Regex, Error>>>(),\n        None => vec![],\n    };\n    let ignore_from_file = ignore_from_file_result\n        .into_iter()\n        .filter_map(|x| x.ok())\n        .collect::<Vec<Regex>>();\n\n    let invert_filter_regexs = invert_filter_regexs\n        .into_iter()\n        .chain(ignore_from_file)\n        .collect::<Vec<Regex>>();\n\n    let by_filecount = options.filecount;\n    let by_filetime = config.get_filetime(&options);\n    let limit_filesystem = options.limit_filesystem;\n    let follow_links = options.dereference_links;\n\n    let allowed_filesystems = if limit_filesystem {\n        get_filesystem_devices(&target_dirs, follow_links)\n    } else {\n        Default::default()\n    };\n\n    let simplified_dirs = simplify_dir_names(&target_dirs);\n\n    let ignored_full_path: HashSet<PathBuf> = ignore_directories\n        .into_iter()\n        .flat_map(|x| simplified_dirs.iter().map(move |d| d.join(&x)))\n        .collect();\n\n    let output_format = config.get_output_format(&options);\n\n    let ignore_hidden = config.get_ignore_hidden(&options);\n\n    let mut indicator = PIndicator::build_me();\n    if !config.get_disable_progress(&options) {\n        indicator.spawn(output_format.clone())\n    }\n\n    let keep_collapsed: HashSet<PathBuf> = match config.get_collapse(&options) {\n        Some(ref collapse) => {\n            let mut combined_dirs = HashSet::new();\n            for collapse_dir in collapse {\n                for target_dir in target_dirs.iter() {\n                    combined_dirs.insert(PathBuf::from(target_dir).join(collapse_dir));\n                }\n            }\n            combined_dirs\n        }\n        None => HashSet::new(),\n    };\n\n    let filter_modified_time = config.get_modified_time_operator(&options);\n    let filter_accessed_time = config.get_accessed_time_operator(&options);\n    let filter_changed_time = config.get_changed_time_operator(&options);\n\n    let walk_data = WalkData {\n        ignore_directories: ignored_full_path,\n        filter_regex: &filter_regexs,\n        invert_filter_regex: &invert_filter_regexs,\n        allowed_filesystems,\n        filter_modified_time,\n        filter_accessed_time,\n        filter_changed_time,\n        use_apparent_size: config.get_apparent_size(&options),\n        by_filecount,\n        by_filetime: &by_filetime,\n        ignore_hidden,\n        follow_links,\n        progress_data: indicator.data.clone(),\n        errors: errors_for_rayon,\n    };\n\n    let threads_to_use = config.get_threads(&options);\n    let stack_size = config.get_custom_stack_size(&options);\n\n    init_rayon(&stack_size, &threads_to_use).install(|| {\n        let top_level_nodes = walk_it(simplified_dirs, &walk_data);\n\n        let tree = match summarize_file_types {\n            true => get_all_file_types(&top_level_nodes, number_of_lines, walk_data.by_filetime),\n            false => {\n                let agg_data = AggregateData {\n                    min_size: config.get_min_size(&options),\n                    only_dir: config.get_only_dir(&options),\n                    only_file: config.get_only_file(&options),\n                    number_of_lines,\n                    depth,\n                    using_a_filter: !filter_regexs.is_empty() || !invert_filter_regexs.is_empty(),\n                    short_paths: !config.get_full_paths(&options),\n                };\n                get_biggest(\n                    top_level_nodes,\n                    agg_data,\n                    walk_data.by_filetime,\n                    keep_collapsed,\n                )\n            }\n        };\n\n        // Must have stopped indicator before we print to stderr\n        indicator.stop();\n\n        let print_errors = config.get_print_errors(&options);\n        let final_errors = walk_data.errors.lock().unwrap();\n        print_any_errors(print_errors, &final_errors);\n\n        if tree.children.is_empty() && !final_errors.file_not_found.is_empty() {\n            std::process::exit(1)\n        } else {\n            print_output(\n                config,\n                options,\n                tree,\n                walk_data.by_filecount,\n                is_colors,\n                terminal_width,\n            )\n        }\n    });\n}\n\nfn print_output(\n    config: Config,\n    options: Cli,\n    tree: DisplayNode,\n    by_filecount: bool,\n    is_colors: bool,\n    terminal_width: usize,\n) {\n    let output_format = config.get_output_format(&options);\n\n    if config.get_output_json(&options) {\n        OUTPUT_TYPE.with(|wrapped| {\n            if by_filecount {\n                wrapped.replace(\"count\".to_string());\n            } else {\n                wrapped.replace(output_format);\n            }\n        });\n        println!(\"{}\", serde_json::to_string(&tree).unwrap());\n    } else {\n        let idd = InitialDisplayData {\n            short_paths: !config.get_full_paths(&options),\n            is_reversed: !config.get_reverse(&options),\n            colors_on: is_colors,\n            by_filecount,\n            by_filetime: config.get_filetime(&options),\n            is_screen_reader: config.get_screen_reader(&options),\n            output_format,\n            bars_on_right: config.get_bars_on_right(&options),\n        };\n\n        draw_it(\n            idd,\n            &tree,\n            config.get_no_bars(&options),\n            terminal_width,\n            config.get_skip_total(&options),\n        )\n    }\n}\n\nfn print_any_errors(print_errors: bool, final_errors: &RuntimeErrors) {\n    if !final_errors.file_not_found.is_empty() {\n        let err = final_errors\n            .file_not_found\n            .iter()\n            .map(|a| a.as_ref())\n            .collect::<Vec<&str>>()\n            .join(\", \");\n        eprintln!(\"No such file or directory: {err}\");\n    }\n    if !final_errors.no_permissions.is_empty() {\n        if print_errors {\n            let err = final_errors\n                .no_permissions\n                .iter()\n                .map(|a| a.as_ref())\n                .collect::<Vec<&str>>()\n                .join(\", \");\n            eprintln!(\"Did not have permissions for directories: {err}\");\n        } else {\n            eprintln!(\n                \"Did not have permissions for all directories (add --print-errors to see errors)\"\n            );\n        }\n    }\n    if !final_errors.unknown_error.is_empty() {\n        let err = final_errors\n            .unknown_error\n            .iter()\n            .map(|a| a.as_ref())\n            .collect::<Vec<&str>>()\n            .join(\", \");\n        eprintln!(\"Unknown Error: {err}\");\n    }\n}\n\nfn read_paths_from_source(path: &str, null_terminated: bool) -> Vec<String> {\n    let from_stdin = path == \"-\";\n\n    let result: Result<Vec<String>, Option<String>> = (|| {\n        // 1) read bytes\n        let bytes = if from_stdin {\n            let mut b = Vec::new();\n            io::stdin().lock().read_to_end(&mut b).map_err(|_| None)?;\n            b\n        } else {\n            read(path).map_err(|e| Some(e.to_string()))?\n        };\n\n        let text = std::str::from_utf8(&bytes).map_err(|e| {\n            if from_stdin {\n                None\n            } else {\n                Some(e.to_string())\n            }\n        })?;\n        let items: Vec<String> = if null_terminated {\n            text.split('\\0')\n                .filter(|s| !s.is_empty())\n                .map(str::to_owned)\n                .collect()\n        } else {\n            text.lines().map(str::to_owned).collect()\n        };\n        if from_stdin && items.is_empty() {\n            return Err(None);\n        }\n        Ok(items)\n    })();\n\n    match result {\n        Ok(v) => v,\n        Err(None) => {\n            eprintln!(\"No files provided, defaulting to current directory\");\n            vec![\".\".to_owned()]\n        }\n        Err(Some(msg)) => {\n            eprintln!(\"Failed to read file: {msg}\");\n            vec![\".\".to_owned()]\n        }\n    }\n}\n\nfn init_rayon(stack: &Option<usize>, threads: &Option<usize>) -> rayon::ThreadPool {\n    let stack_size = match stack {\n        Some(s) => Some(*s),\n        None => {\n            // Do not increase the stack size on a 32 bit system, it will fail\n            if cfg!(target_pointer_width = \"32\") {\n                None\n            } else {\n                let large_stack = usize::pow(1024, 3);\n                let mut sys = System::new_all();\n                sys.refresh_memory();\n                // Larger stack size if possible to handle cases with lots of nested directories\n                let available = sys.available_memory();\n                if available > (large_stack * threads.unwrap_or(1)).try_into().unwrap() {\n                    Some(large_stack)\n                } else {\n                    None\n                }\n            }\n        }\n    };\n\n    match build_thread_pool(stack_size, threads) {\n        Ok(pool) => pool,\n        Err(err) => {\n            eprintln!(\"Problem initializing rayon, try: export RAYON_NUM_THREADS=1\");\n            if stack.is_none() && stack_size.is_some() {\n                // stack parameter was none, try with default stack size\n                if let Ok(pool) = build_thread_pool(None, threads) {\n                    eprintln!(\"WARNING: not using large stack size, got error: {err}\");\n                    return pool;\n                }\n            }\n            panic!(\"{err}\");\n        }\n    }\n}\n\nfn build_thread_pool(\n    stack_size: Option<usize>,\n    threads: &Option<usize>,\n) -> Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {\n    let mut pool_builder = rayon::ThreadPoolBuilder::new();\n    if let Some(stack_size_param) = stack_size {\n        pool_builder = pool_builder.stack_size(stack_size_param);\n    }\n    if let Some(thread_count) = threads {\n        pool_builder = pool_builder.num_threads(*thread_count);\n    }\n    pool_builder.build()\n}\n"
  },
  {
    "path": "src/node.rs",
    "content": "use crate::dir_walker::WalkData;\nuse crate::platform::get_metadata;\nuse crate::utils::is_filtered_out_due_to_file_time;\nuse crate::utils::is_filtered_out_due_to_invert_regex;\nuse crate::utils::is_filtered_out_due_to_regex;\n\nuse std::cmp::Ordering;\nuse std::path::PathBuf;\n\n#[derive(Debug, Eq, Clone)]\npub struct Node {\n    pub name: PathBuf,\n    pub size: u64,\n    pub children: Vec<Node>,\n    pub inode_device: Option<(u64, u64)>,\n    pub depth: usize,\n}\n\n#[derive(Debug, PartialEq)]\npub enum FileTime {\n    Modified,\n    Accessed,\n    Changed,\n}\n\nimpl From<crate::cli::FileTime> for FileTime {\n    fn from(time: crate::cli::FileTime) -> Self {\n        match time {\n            crate::cli::FileTime::Modified => Self::Modified,\n            crate::cli::FileTime::Accessed => Self::Accessed,\n            crate::cli::FileTime::Changed => Self::Changed,\n        }\n    }\n}\n\n#[allow(clippy::too_many_arguments)]\npub fn build_node(\n    dir: PathBuf,\n    children: Vec<Node>,\n    is_symlink: bool,\n    is_file: bool,\n    depth: usize,\n    walk_data: &WalkData,\n) -> Option<Node> {\n    let use_apparent_size = walk_data.use_apparent_size;\n    let by_filecount = walk_data.by_filecount;\n    let by_filetime = &walk_data.by_filetime;\n\n    get_metadata(\n        &dir,\n        use_apparent_size,\n        walk_data.follow_links && is_symlink,\n    )\n    .map(|data| {\n        let inode_device = data.1;\n\n        let size = if is_filtered_out_due_to_regex(walk_data.filter_regex, &dir)\n            || is_filtered_out_due_to_invert_regex(walk_data.invert_filter_regex, &dir)\n            || by_filecount && !is_file\n            || [\n                (&walk_data.filter_modified_time, data.2.0),\n                (&walk_data.filter_accessed_time, data.2.1),\n                (&walk_data.filter_changed_time, data.2.2),\n            ]\n            .iter()\n            .any(|(filter_time, actual_time)| {\n                is_filtered_out_due_to_file_time(filter_time, *actual_time)\n            }) {\n            0\n        } else if by_filecount {\n            1\n        } else if by_filetime.is_some() {\n            match by_filetime {\n                Some(FileTime::Modified) => data.2.0.unsigned_abs(),\n                Some(FileTime::Accessed) => data.2.1.unsigned_abs(),\n                Some(FileTime::Changed) => data.2.2.unsigned_abs(),\n                None => unreachable!(),\n            }\n        } else {\n            data.0\n        };\n\n        Node {\n            name: dir,\n            size,\n            children,\n            inode_device,\n            depth,\n        }\n    })\n}\n\nimpl PartialEq for Node {\n    fn eq(&self, other: &Self) -> bool {\n        self.name == other.name && self.size == other.size && self.children == other.children\n    }\n}\n\nimpl Ord for Node {\n    fn cmp(&self, other: &Self) -> Ordering {\n        self.size\n            .cmp(&other.size)\n            .then_with(|| self.name.cmp(&other.name))\n            .then_with(|| self.children.cmp(&other.children))\n    }\n}\n\nimpl PartialOrd for Node {\n    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n        Some(self.cmp(other))\n    }\n}\n"
  },
  {
    "path": "src/platform.rs",
    "content": "#[allow(unused_imports)]\nuse std::fs;\n\nuse std::path::Path;\n\n#[cfg(target_family = \"unix\")]\nfn get_block_size() -> u64 {\n    // All os specific implementations of MetadataExt seem to define a block as 512 bytes\n    // https://doc.rust-lang.org/std/os/linux/fs/trait.MetadataExt.html#tymethod.st_blocks\n    512\n}\n\ntype InodeAndDevice = (u64, u64);\ntype FileTime = (i64, i64, i64);\n\n#[cfg(target_family = \"unix\")]\npub fn get_metadata<P: AsRef<Path>>(\n    path: P,\n    use_apparent_size: bool,\n    follow_links: bool,\n) -> Option<(u64, Option<InodeAndDevice>, FileTime)> {\n    use std::os::unix::fs::MetadataExt;\n    let metadata = if follow_links {\n        path.as_ref().metadata()\n    } else {\n        path.as_ref().symlink_metadata()\n    };\n    match metadata {\n        Ok(md) => {\n            let file_size = md.len();\n            if use_apparent_size {\n                Some((\n                    file_size,\n                    Some((md.ino(), md.dev())),\n                    (md.mtime(), md.atime(), md.ctime()),\n                ))\n            } else {\n                // On NTFS mounts, the reported block count can be unexpectedly large.\n                // To avoid overestimating disk usage, cap the allocated size to what the\n                // file should occupy based on the file system I/O block size (blksize).\n                // Related: https://github.com/bootandy/dust/issues/295\n                let blksize = md.blksize();\n                let target_size = file_size.div_ceil(blksize) * blksize;\n                let reported_size = md.blocks() * get_block_size();\n\n                // File systems can pre-allocate more space for a file than what would be necessary\n                let pre_allocation_buffer = blksize * 65536;\n                let max_size = target_size + pre_allocation_buffer;\n                let allocated_size = if reported_size > max_size {\n                    target_size\n                } else {\n                    reported_size\n                };\n                Some((\n                    allocated_size,\n                    Some((md.ino(), md.dev())),\n                    (md.mtime(), md.atime(), md.ctime()),\n                ))\n            }\n        }\n        Err(_e) => None,\n    }\n}\n\n#[cfg(target_family = \"windows\")]\npub fn get_metadata<P: AsRef<Path>>(\n    path: P,\n    use_apparent_size: bool,\n    follow_links: bool,\n) -> Option<(u64, Option<InodeAndDevice>, FileTime)> {\n    // On windows opening the file to get size, file ID and volume can be very\n    // expensive because 1) it causes a few system calls, and more importantly 2) it can cause\n    // windows defender to scan the file.\n    // Therefore we try to avoid doing that for common cases, mainly those of\n    // plain files:\n\n    // The idea is to make do with the file size that we get from the OS for\n    // free as part of iterating a folder. Therefore we want to make sure that\n    // it makes sense to use that free size information:\n\n    // Volume boundaries:\n    // The user can ask us not to cross volume boundaries. If the DirEntry is a\n    // plain file and not a reparse point or other non-trivial stuff, we assume\n    // that the file is located on the same volume as the directory that\n    // contains it.\n\n    // File ID:\n    // This optimization does deprive us of access to a file ID. As a\n    // workaround, we just make one up that hopefully does not collide with real\n    // file IDs.\n    // Hard links: Unresolved. We don't get inode/file index, so hard links\n    // count once for each link. Hopefully they are not too commonly in use on\n    // windows.\n\n    // Size:\n    // We assume (naively?) that for the common cases the free size info is the\n    // same as one would get by doing the expensive thing. Sparse, encrypted and\n    // compressed files are not included in the common cases, as one can image\n    // there being more than view on their size.\n\n    // Savings in orders of magnitude in terms of time, io and cpu have been\n    // observed on hdd, windows 10, some 100Ks files taking up some hundreds of\n    // GBs:\n    // Consistently opening the file: 30 minutes.\n    // With this optimization:         8 sec.\n\n    use std::io;\n    use winapi_util::Handle;\n    fn handle_from_path_limited(path: &Path) -> io::Result<Handle> {\n        use std::fs::OpenOptions;\n        use std::os::windows::fs::OpenOptionsExt;\n        const FILE_READ_ATTRIBUTES: u32 = 0x0080;\n\n        // So, it seems that it does does have to be that expensive to open\n        // files to get their info: Avoiding opening the file with the full\n        // GENERIC_READ is key:\n\n        // https://docs.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights:\n        // \"For example, a Windows file object maps the GENERIC_READ bit to the\n        // READ_CONTROL and SYNCHRONIZE standard access rights and to the\n        // FILE_READ_DATA, FILE_READ_EA, and FILE_READ_ATTRIBUTES\n        // object-specific access rights\"\n\n        // The flag FILE_READ_DATA seems to be the expensive one, so we'll avoid\n        // that, and a most of the other ones. Simply because it seems that we\n        // don't need them.\n\n        let file = OpenOptions::new()\n            .access_mode(FILE_READ_ATTRIBUTES)\n            .open(path)?;\n        Ok(Handle::from_file(file))\n    }\n\n    fn get_metadata_expensive(\n        path: &Path,\n        use_apparent_size: bool,\n    ) -> Option<(u64, Option<InodeAndDevice>, FileTime)> {\n        use winapi_util::file::information;\n\n        let h = handle_from_path_limited(path).ok()?;\n        let info = information(&h).ok()?;\n\n        if use_apparent_size {\n            use filesize::PathExt;\n            Some((\n                path.size_on_disk().ok()?,\n                Some((info.file_index(), info.volume_serial_number())),\n                (\n                    info.last_write_time().unwrap() as i64,\n                    info.last_access_time().unwrap() as i64,\n                    info.creation_time().unwrap() as i64,\n                ),\n            ))\n        } else {\n            Some((\n                info.file_size(),\n                Some((info.file_index(), info.volume_serial_number())),\n                (\n                    info.last_write_time().unwrap() as i64,\n                    info.last_access_time().unwrap() as i64,\n                    info.creation_time().unwrap() as i64,\n                ),\n            ))\n        }\n    }\n\n    use std::os::windows::fs::MetadataExt;\n    let path = path.as_ref();\n    let metadata = if follow_links {\n        path.metadata()\n    } else {\n        path.symlink_metadata()\n    };\n    match metadata {\n        Ok(ref md) => {\n            const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x20;\n            const FILE_ATTRIBUTE_READONLY: u32 = 0x01;\n            const FILE_ATTRIBUTE_HIDDEN: u32 = 0x02;\n            const FILE_ATTRIBUTE_SYSTEM: u32 = 0x04;\n            const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;\n            const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;\n            const FILE_ATTRIBUTE_SPARSE_FILE: u32 = 0x00000200;\n            const FILE_ATTRIBUTE_PINNED: u32 = 0x00080000;\n            const FILE_ATTRIBUTE_UNPINNED: u32 = 0x00100000;\n            const FILE_ATTRIBUTE_RECALL_ON_OPEN: u32 = 0x00040000;\n            const FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS: u32 = 0x00400000;\n            const FILE_ATTRIBUTE_OFFLINE: u32 = 0x00001000;\n            // normally FILE_ATTRIBUTE_SPARSE_FILE would be enough, however Windows sometimes likes to mask it out. see: https://stackoverflow.com/q/54560454\n            const IS_PROBABLY_ONEDRIVE: u32 = FILE_ATTRIBUTE_SPARSE_FILE\n                | FILE_ATTRIBUTE_PINNED\n                | FILE_ATTRIBUTE_UNPINNED\n                | FILE_ATTRIBUTE_RECALL_ON_OPEN\n                | FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS\n                | FILE_ATTRIBUTE_OFFLINE;\n            let attr_filtered = md.file_attributes()\n                & !(FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM);\n            if ((attr_filtered & FILE_ATTRIBUTE_ARCHIVE) != 0\n                || (attr_filtered & FILE_ATTRIBUTE_DIRECTORY) != 0\n                || md.file_attributes() == FILE_ATTRIBUTE_NORMAL)\n                && !((attr_filtered & IS_PROBABLY_ONEDRIVE != 0) && use_apparent_size)\n            {\n                Some((\n                    md.len(),\n                    None,\n                    (\n                        md.last_write_time() as i64,\n                        md.last_access_time() as i64,\n                        md.creation_time() as i64,\n                    ),\n                ))\n            } else {\n                get_metadata_expensive(path, use_apparent_size)\n            }\n        }\n        _ => get_metadata_expensive(path, use_apparent_size),\n    }\n}\n"
  },
  {
    "path": "src/progress.rs",
    "content": "use std::{\n    collections::HashSet,\n    io::Write,\n    path::Path,\n    sync::{\n        Arc, RwLock,\n        atomic::{AtomicU8, AtomicUsize, Ordering},\n        mpsc::{self, RecvTimeoutError, Sender},\n    },\n    thread::JoinHandle,\n    time::Duration,\n};\n\n#[cfg(not(target_has_atomic = \"64\"))]\nuse portable_atomic::AtomicU64;\n#[cfg(target_has_atomic = \"64\")]\nuse std::sync::atomic::AtomicU64;\n\nuse crate::display::human_readable_number;\n\n/* -------------------------------------------------------------------------- */\n\npub const ORDERING: Ordering = Ordering::Relaxed;\n\nconst SPINNER_SLEEP_TIME: u64 = 100;\nconst PROGRESS_CHARS: [char; 4] = ['-', '\\\\', '|', '/'];\nconst PROGRESS_CHARS_LEN: usize = PROGRESS_CHARS.len();\n\npub trait ThreadSyncTrait<T> {\n    fn set(&self, val: T);\n    fn get(&self) -> T;\n}\n\n#[derive(Default)]\npub struct ThreadStringWrapper {\n    inner: RwLock<String>,\n}\n\nimpl ThreadSyncTrait<String> for ThreadStringWrapper {\n    fn set(&self, val: String) {\n        *self.inner.write().unwrap() = val;\n    }\n\n    fn get(&self) -> String {\n        (*self.inner.read().unwrap()).clone()\n    }\n}\n\n/* -------------------------------------------------------------------------- */\n\n// creating an enum this way allows to have simpler syntax compared to a Mutex or a RwLock\n#[allow(non_snake_case)]\npub mod Operation {\n    pub const INDEXING: u8 = 0;\n    pub const PREPARING: u8 = 1;\n}\n\n#[derive(Default)]\npub struct PAtomicInfo {\n    pub num_files: AtomicUsize,\n    pub total_file_size: AtomicU64,\n    pub state: AtomicU8,\n    pub current_path: ThreadStringWrapper,\n}\n\nimpl PAtomicInfo {\n    pub fn clear_state(&self, dir: &Path) {\n        self.state.store(Operation::INDEXING, ORDERING);\n        let dir_name = dir.to_string_lossy().to_string();\n        self.current_path.set(dir_name);\n        self.total_file_size.store(0, ORDERING);\n        self.num_files.store(0, ORDERING);\n    }\n}\n\n#[derive(Default)]\npub struct RuntimeErrors {\n    pub no_permissions: HashSet<String>,\n    pub file_not_found: HashSet<String>,\n    pub unknown_error: HashSet<String>,\n    pub interrupted_error: i32,\n}\n\n/* -------------------------------------------------------------------------- */\n\nfn format_preparing_str(prog_char: char, data: &PAtomicInfo, output_display: &str) -> String {\n    let path_in = data.current_path.get();\n    let size = human_readable_number(data.total_file_size.load(ORDERING), output_display);\n    format!(\"Preparing: {path_in} {size} ... {prog_char}\")\n}\n\nfn format_indexing_str(prog_char: char, data: &PAtomicInfo, output_display: &str) -> String {\n    let path_in = data.current_path.get();\n    let file_count = data.num_files.load(ORDERING);\n    let size = human_readable_number(data.total_file_size.load(ORDERING), output_display);\n    let file_str = format!(\"{file_count} files, {size}\");\n    format!(\"Indexing: {path_in} {file_str} ... {prog_char}\")\n}\n\npub struct PIndicator {\n    pub thread: Option<(Sender<()>, JoinHandle<()>)>,\n    pub data: Arc<PAtomicInfo>,\n}\n\nimpl PIndicator {\n    pub fn build_me() -> Self {\n        Self {\n            thread: None,\n            data: Arc::new(PAtomicInfo {\n                ..Default::default()\n            }),\n        }\n    }\n\n    pub fn spawn(&mut self, output_display: String) {\n        let data = self.data.clone();\n        let (stop_handler, receiver) = mpsc::channel::<()>();\n\n        let time_info_thread = std::thread::spawn(move || {\n            let mut progress_char_i: usize = 0;\n            let mut stderr = std::io::stderr();\n            let mut msg = \"\".to_string();\n\n            // While the timeout triggers we go round the loop\n            // If we disconnect or the sender sends its message we exit the while loop\n            while let Err(RecvTimeoutError::Timeout) =\n                receiver.recv_timeout(Duration::from_millis(SPINNER_SLEEP_TIME))\n            {\n                // Clear the text written by 'write!'& Return at the start of line\n                let clear = format!(\"\\r{:width$}\", \" \", width = msg.len());\n                write!(stderr, \"{clear}\").unwrap();\n                let prog_char = PROGRESS_CHARS[progress_char_i];\n\n                msg = match data.state.load(ORDERING) {\n                    Operation::INDEXING => format_indexing_str(prog_char, &data, &output_display),\n                    Operation::PREPARING => format_preparing_str(prog_char, &data, &output_display),\n                    _ => panic!(\"Unknown State\"),\n                };\n\n                write!(stderr, \"\\r{msg}\").unwrap();\n                stderr.flush().unwrap();\n\n                progress_char_i += 1;\n                progress_char_i %= PROGRESS_CHARS_LEN;\n            }\n\n            let clear = format!(\"\\r{:width$}\", \" \", width = msg.len());\n            write!(stderr, \"{clear}\").unwrap();\n            write!(stderr, \"\\r\").unwrap();\n            stderr.flush().unwrap();\n        });\n        self.thread = Some((stop_handler, time_info_thread))\n    }\n\n    pub fn stop(self) {\n        if let Some((stop_handler, thread)) = self.thread {\n            stop_handler.send(()).unwrap();\n            thread.join().unwrap();\n        }\n    }\n}\n"
  },
  {
    "path": "src/utils.rs",
    "content": "use platform::get_metadata;\nuse std::collections::HashSet;\nuse std::path::{Path, PathBuf};\n\nuse crate::config::DAY_SECONDS;\n\nuse crate::dir_walker::Operator;\nuse crate::platform;\nuse regex::Regex;\n\npub fn simplify_dir_names<P: AsRef<Path>>(dirs: &[P]) -> HashSet<PathBuf> {\n    let mut top_level_names: HashSet<PathBuf> = HashSet::with_capacity(dirs.len());\n\n    for t in dirs {\n        let top_level_name = normalize_path(t);\n        let mut can_add = true;\n        let mut to_remove: Vec<PathBuf> = Vec::new();\n\n        for tt in top_level_names.iter() {\n            if is_a_parent_of(&top_level_name, tt) {\n                to_remove.push(tt.to_path_buf());\n            } else if is_a_parent_of(tt, &top_level_name) {\n                can_add = false;\n            }\n        }\n        for r in to_remove {\n            top_level_names.remove(&r);\n        }\n        if can_add {\n            top_level_names.insert(top_level_name);\n        }\n    }\n\n    top_level_names\n}\n\npub fn get_filesystem_devices<P: AsRef<Path>>(paths: &[P], follow_links: bool) -> HashSet<u64> {\n    use std::fs;\n    // Gets the device ids for the filesystems which are used by the argument paths\n    paths\n        .iter()\n        .filter_map(|p| {\n            let follow_links = if follow_links {\n                // slow path: If dereference-links is set, then we check if the file is a symbolic link\n                match fs::symlink_metadata(p) {\n                    Ok(metadata) => metadata.file_type().is_symlink(),\n                    Err(_) => false,\n                }\n            } else {\n                false\n            };\n            match get_metadata(p, false, follow_links) {\n                Some((_size, Some((_id, dev)), _time)) => Some(dev),\n                _ => None,\n            }\n        })\n        .collect()\n}\n\npub fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf {\n    // normalize path ...\n    // 1. removing repeated separators\n    // 2. removing interior '.' (\"current directory\") path segments\n    // 3. removing trailing extra separators and '.' (\"current directory\") path segments\n    // * `Path.components()` does all the above work; ref: <https://doc.rust-lang.org/std/path/struct.Path.html#method.components>\n    // 4. changing to os preferred separator (automatically done by recollecting components back into a PathBuf)\n    path.as_ref().components().collect()\n}\n\n// Canonicalize the path only if it is an absolute path\npub fn canonicalize_absolute_path(path: PathBuf) -> PathBuf {\n    if !path.is_absolute() {\n        return path;\n    }\n    match std::fs::canonicalize(&path) {\n        Ok(canonicalized_path) => canonicalized_path,\n        Err(_) => path,\n    }\n}\n\npub fn is_filtered_out_due_to_regex(filter_regex: &[Regex], dir: &Path) -> bool {\n    if filter_regex.is_empty() {\n        false\n    } else {\n        filter_regex\n            .iter()\n            .all(|f| !f.is_match(&dir.as_os_str().to_string_lossy()))\n    }\n}\n\npub fn is_filtered_out_due_to_file_time(\n    filter_time: &Option<(Operator, i64)>,\n    actual_time: i64,\n) -> bool {\n    match filter_time {\n        None => false,\n        Some((Operator::Equal, bound_time)) => {\n            !(actual_time >= *bound_time && actual_time < *bound_time + DAY_SECONDS)\n        }\n        Some((Operator::GreaterThan, bound_time)) => actual_time < *bound_time,\n        Some((Operator::LessThan, bound_time)) => actual_time > *bound_time,\n    }\n}\n\npub fn is_filtered_out_due_to_invert_regex(filter_regex: &[Regex], dir: &Path) -> bool {\n    filter_regex\n        .iter()\n        .any(|f| f.is_match(&dir.as_os_str().to_string_lossy()))\n}\n\nfn is_a_parent_of<P: AsRef<Path>>(parent: P, child: P) -> bool {\n    let parent = parent.as_ref();\n    let child = child.as_ref();\n    child.starts_with(parent) && !parent.starts_with(child)\n}\n\nmod tests {\n    #[allow(unused_imports)]\n    use super::*;\n\n    #[test]\n    fn test_simplify_dir() {\n        let mut correct = HashSet::new();\n        correct.insert(PathBuf::from(\"a\"));\n        assert_eq!(simplify_dir_names(&[\"a\"]), correct);\n    }\n\n    #[test]\n    fn test_simplify_dir_rm_subdir() {\n        let mut correct = HashSet::new();\n        correct.insert([\"a\", \"b\"].iter().collect::<PathBuf>());\n        assert_eq!(simplify_dir_names(&[\"a/b/c\", \"a/b\", \"a/b/d/f\"]), correct);\n        assert_eq!(simplify_dir_names(&[\"a/b\", \"a/b/c\", \"a/b/d/f\"]), correct);\n    }\n\n    #[test]\n    fn test_simplify_dir_duplicates() {\n        let mut correct = HashSet::new();\n        correct.insert([\"a\", \"b\"].iter().collect::<PathBuf>());\n        correct.insert(PathBuf::from(\"c\"));\n        assert_eq!(\n            simplify_dir_names(&[\n                \"a/b\",\n                \"a/b//\",\n                \"a/././b///\",\n                \"c\",\n                \"c/\",\n                \"c/.\",\n                \"c/././\",\n                \"c/././.\"\n            ]),\n            correct\n        );\n    }\n    #[test]\n    fn test_simplify_dir_rm_subdir_and_not_substrings() {\n        let mut correct = HashSet::new();\n        correct.insert(PathBuf::from(\"b\"));\n        correct.insert([\"c\", \"a\", \"b\"].iter().collect::<PathBuf>());\n        correct.insert([\"a\", \"b\"].iter().collect::<PathBuf>());\n        assert_eq!(simplify_dir_names(&[\"a/b\", \"c/a/b/\", \"b\"]), correct);\n    }\n\n    #[test]\n    fn test_simplify_dir_dots() {\n        let mut correct = HashSet::new();\n        correct.insert(PathBuf::from(\"src\"));\n        assert_eq!(simplify_dir_names(&[\"src/.\"]), correct);\n    }\n\n    #[test]\n    fn test_simplify_dir_substring_names() {\n        let mut correct = HashSet::new();\n        correct.insert(PathBuf::from(\"src\"));\n        correct.insert(PathBuf::from(\"src_v2\"));\n        assert_eq!(simplify_dir_names(&[\"src/\", \"src_v2\"]), correct);\n    }\n\n    #[test]\n    fn test_is_a_parent_of() {\n        assert!(is_a_parent_of(\"/usr\", \"/usr/andy\"));\n        assert!(is_a_parent_of(\"/usr\", \"/usr/andy/i/am/descendant\"));\n        assert!(!is_a_parent_of(\"/usr\", \"/usr/.\"));\n        assert!(!is_a_parent_of(\"/usr\", \"/usr/\"));\n        assert!(!is_a_parent_of(\"/usr\", \"/usr\"));\n        assert!(!is_a_parent_of(\"/usr/\", \"/usr\"));\n        assert!(!is_a_parent_of(\"/usr/andy\", \"/usr\"));\n        assert!(!is_a_parent_of(\"/usr/andy\", \"/usr/sibling\"));\n        assert!(!is_a_parent_of(\"/usr/folder\", \"/usr/folder_not_a_child\"));\n    }\n\n    #[test]\n    fn test_is_a_parent_of_root() {\n        assert!(is_a_parent_of(\"/\", \"/usr/andy\"));\n        assert!(is_a_parent_of(\"/\", \"/usr\"));\n        assert!(!is_a_parent_of(\"/\", \"/\"));\n    }\n}\n"
  },
  {
    "path": "tests/test_dir/many/a_file",
    "content": ""
  },
  {
    "path": "tests/test_dir/many/hello_file",
    "content": "hello\n"
  },
  {
    "path": "tests/test_dir2/dir/hello",
    "content": "hello"
  },
  {
    "path": "tests/test_dir2/dir_name_clash",
    "content": "hello"
  },
  {
    "path": "tests/test_dir2/dir_substring/hello",
    "content": "hello\n"
  },
  {
    "path": "tests/test_dir2/long_dir_name_what_a_very_long_dir_name_what_happens_when_this_goes_over_80_characters_i_wonder",
    "content": ""
  },
  {
    "path": "tests/test_dir_files_from/a_file",
    "content": ""
  },
  {
    "path": "tests/test_dir_files_from/files_from.txt",
    "content": "tests/test_dir_files_from/a_file\ntests/test_dir_files_from/hello_file\n"
  },
  {
    "path": "tests/test_dir_files_from/hello_file",
    "content": "hello\n"
  },
  {
    "path": "tests/test_dir_hidden_entries/.hidden_file",
    "content": "something\n.secret\n"
  },
  {
    "path": "tests/test_dir_hidden_entries/.secret",
    "content": ""
  },
  {
    "path": "tests/test_dir_matching/andy/dup_name/hello",
    "content": ""
  },
  {
    "path": "tests/test_dir_matching/dave/dup_name/hello",
    "content": ""
  },
  {
    "path": "tests/test_dir_unicode/ラウトは難しいです！.japan",
    "content": ""
  },
  {
    "path": "tests/test_dir_unicode/👩.unicode",
    "content": ""
  },
  {
    "path": "tests/test_exact_output.rs",
    "content": "use assert_cmd::{Command, cargo_bin_cmd};\nuse std::ffi::OsStr;\nuse std::process::Output;\nuse std::sync::Once;\nuse std::{io, str};\n\nstatic INIT: Once = Once::new();\nstatic UNREADABLE_DIR_PATH: &str = \"/tmp/unreadable_dir\";\n\n/**\n * This file contains tests that verify the exact output of the command.\n * This output differs on Linux / Mac so the tests are harder to write and debug\n * Windows is ignored here because the results vary by host making exact testing impractical\n *\n * Despite the above problems, these tests are good as they are the closest to 'the real thing'.\n */\n\n//  Warning: File sizes differ on both platform and on the format of the disk.\n/// Copy to /tmp dir - we assume that the formatting of the /tmp partition\n/// is consistent. If the tests fail your /tmp filesystem probably differs\nfn copy_test_data(dir: &str) {\n    // First remove the existing directory - just in case it is there and has incorrect data\n    let last_slash = dir.rfind('/').unwrap();\n    let last_part_of_dir = dir.chars().skip(last_slash).collect::<String>();\n    let _ = Command::new(\"rm\")\n        .arg(\"-rf\")\n        .arg(\"/tmp/\".to_owned() + &*last_part_of_dir)\n        .ok();\n\n    let _ = Command::new(\"cp\")\n        .arg(\"-r\")\n        .arg(dir)\n        .arg(\"/tmp/\")\n        .ok()\n        .map_err(|err| eprintln!(\"Error copying directory for test setup\\n{:?}\", err));\n}\n\nfn create_unreadable_directory() -> io::Result<()> {\n    #[cfg(unix)]\n    {\n        use std::fs;\n        use std::fs::Permissions;\n        use std::os::unix::fs::PermissionsExt;\n        fs::create_dir_all(UNREADABLE_DIR_PATH)?;\n        fs::set_permissions(UNREADABLE_DIR_PATH, Permissions::from_mode(0))?;\n    }\n    Ok(())\n}\n\nfn initialize() {\n    INIT.call_once(|| {\n        copy_test_data(\"tests/test_dir\");\n        copy_test_data(\"tests/test_dir2\");\n        copy_test_data(\"tests/test_dir_unicode\");\n\n        if let Err(e) = create_unreadable_directory() {\n            panic!(\"Failed to create unreadable directory: {}\", e);\n        }\n    });\n}\n\nfn run_cmd<T: AsRef<OsStr>>(command_args: &[T]) -> Output {\n    initialize();\n    let mut to_run = cargo_bin_cmd!(\"dust\");\n    // Hide progress bar\n    to_run.arg(\"-P\");\n    for p in command_args {\n        to_run.arg(p);\n    }\n    to_run.unwrap()\n}\n\nfn exact_stdout_test<T: AsRef<OsStr>>(command_args: &[T], valid_stdout: Vec<String>) {\n    let to_run = run_cmd(command_args);\n\n    let stdout_output = str::from_utf8(&to_run.stdout).unwrap().to_owned();\n    let will_fail = valid_stdout.iter().any(|i| stdout_output.contains(i));\n    if !will_fail {\n        eprintln!(\n            \"output(stdout):\\n{}\\ndoes not contain any of:\\n{}\",\n            stdout_output,\n            valid_stdout.join(\"\\n\\n\")\n        );\n    }\n    assert!(will_fail);\n}\n\nfn exact_stderr_test<T: AsRef<OsStr>>(command_args: &[T], valid_stderr: String) {\n    let to_run = run_cmd(command_args);\n\n    let stderr_output = str::from_utf8(&to_run.stderr).unwrap().trim();\n    assert_eq!(stderr_output, valid_stderr);\n}\n\n// \"windows\" result data can vary by host (size seems to be variable by one byte); fix code vs test and re-enable\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_main_basic() {\n    // -c is no color mode - This makes testing much simpler\n    exact_stdout_test(&[\"-c\", \"-B\", \"/tmp/test_dir/\"], main_output());\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_main_multi_arg() {\n    let command_args = [\n        \"-c\",\n        \"-B\",\n        \"/tmp/test_dir/many/\",\n        \"/tmp/test_dir\",\n        \"/tmp/test_dir\",\n    ];\n    exact_stdout_test(&command_args, main_output());\n}\n\nfn main_output() -> Vec<String> {\n    // Some linux currently thought to be Manjaro, Arch\n    // Although probably depends on how drive is formatted\n    let mac_and_some_linux = r#\"\n  0B     ┌── a_file    │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█ │   0%\n4.0K     ├── hello_file│█████████████████████████████████████████████████ │ 100%\n4.0K   ┌─┴ many        │█████████████████████████████████████████████████ │ 100%\n4.0K ┌─┴ test_dir      │█████████████████████████████████████████████████ │ 100%\n\"#\n    .trim()\n    .to_string();\n\n    let ubuntu = r#\"\n  0B     ┌── a_file    │                ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█ │   0%\n4.0K     ├── hello_file│                ░░░░░░░░░░░░░░░░█████████████████ │  33%\n8.0K   ┌─┴ many        │                █████████████████████████████████ │  67%\n 12K ┌─┴ test_dir      │█████████████████████████████████████████████████ │ 100%\n  \"#\n    .trim()\n    .to_string();\n\n    vec![mac_and_some_linux, ubuntu]\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_main_long_paths() {\n    let command_args = [\"-c\", \"-p\", \"-B\", \"/tmp/test_dir/\"];\n    exact_stdout_test(&command_args, main_output_long_paths());\n}\n\nfn main_output_long_paths() -> Vec<String> {\n    let mac_and_some_linux = r#\"\n  0B     ┌── /tmp/test_dir/many/a_file    │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█ │   0%\n4.0K     ├── /tmp/test_dir/many/hello_file│██████████████████████████████ │ 100%\n4.0K   ┌─┴ /tmp/test_dir/many             │██████████████████████████████ │ 100%\n4.0K ┌─┴ /tmp/test_dir                    │██████████████████████████████ │ 100%\n\"#\n    .trim()\n    .to_string();\n    let ubuntu = r#\"\n  0B     ┌── /tmp/test_dir/many/a_file    │         ░░░░░░░░░░░░░░░░░░░░█ │   0%\n4.0K     ├── /tmp/test_dir/many/hello_file│         ░░░░░░░░░░███████████ │  33%\n8.0K   ┌─┴ /tmp/test_dir/many             │         █████████████████████ │  67%\n 12K ┌─┴ /tmp/test_dir                    │██████████████████████████████ │ 100%\n\"#\n    .trim()\n    .to_string();\n    vec![mac_and_some_linux, ubuntu]\n}\n\n// Check against directories and files whose names are substrings of each other\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_substring_of_names_and_long_names() {\n    let command_args = [\"-c\", \"-B\", \"/tmp/test_dir2\"];\n    exact_stdout_test(&command_args, no_substring_of_names_output());\n}\n\nfn no_substring_of_names_output() -> Vec<String> {\n    let ubuntu = \"\n  0B   ┌── long_dir_name_what_a_very_long_dir_name_what_happens_when_this_goes..\n4.0K   ├── dir_name_clash\n4.0K   │ ┌── hello\n8.0K   ├─┴ dir\n4.0K   │ ┌── hello\n8.0K   ├─┴ dir_substring\n 24K ┌─┴ test_dir2\n    \"\n    .trim()\n    .into();\n\n    let mac_and_some_linux = \"\n  0B   ┌── long_dir_name_what_a_very_long_dir_name_what_happens_when_this_goes..\n4.0K   │ ┌── hello\n4.0K   ├─┴ dir\n4.0K   ├── dir_name_clash\n4.0K   │ ┌── hello\n4.0K   ├─┴ dir_substring\n 12K ┌─┴ test_dir2\n  \"\n    .trim()\n    .into();\n    vec![mac_and_some_linux, ubuntu]\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_unicode_directories() {\n    let command_args = [\"-c\", \"-B\", \"/tmp/test_dir_unicode\"];\n    exact_stdout_test(&command_args, unicode_dir());\n}\n\nfn unicode_dir() -> Vec<String> {\n    // The way unicode & asian characters are rendered on the terminal should make this line up\n    let ubuntu = \"\n  0B   ┌── ラウトは難しいです！.japan│                                  █ │   0%\n  0B   ├── 👩.unicode                │                                  █ │   0%\n4.0K ┌─┴ test_dir_unicode            │███████████████████████████████████ │ 100%\n    \"\n    .trim()\n    .into();\n\n    let mac_and_some_linux = \"\n0B   ┌── ラウトは難しいです！.japan│                                    █ │   0%\n0B   ├── 👩.unicode                │                                    █ │   0%\n0B ┌─┴ test_dir_unicode            │                                    █ │   0%\n    \"\n    .trim()\n    .into();\n    vec![mac_and_some_linux, ubuntu]\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_apparent_size() {\n    let command_args = [\"-c\", \"-s\", \"-b\", \"/tmp/test_dir\"];\n    exact_stdout_test(&command_args, apparent_size_output());\n}\n\nfn apparent_size_output() -> Vec<String> {\n    // The apparent directory sizes are too unpredictable and system dependent to try and match\n    let one_space_before = r#\"\n 0B     ┌── a_file\n 6B     ├── hello_file\n \"#\n    .trim()\n    .to_string();\n\n    let two_space_before = r#\"\n  0B     ┌── a_file\n  6B     ├── hello_file\n \"#\n    .trim()\n    .to_string();\n\n    vec![one_space_before, two_space_before]\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_permission_normal() {\n    let command_args = [UNREADABLE_DIR_PATH];\n    let permission_msg =\n        r#\"Did not have permissions for all directories (add --print-errors to see errors)\"#\n            .trim()\n            .to_string();\n    exact_stderr_test(&command_args, permission_msg);\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_permission_flag() {\n    // add the flag to CLI\n    let command_args = [\"--print-errors\", UNREADABLE_DIR_PATH];\n    let permission_msg = format!(\n        \"Did not have permissions for directories: {}\",\n        UNREADABLE_DIR_PATH\n    );\n    exact_stderr_test(&command_args, permission_msg);\n}\n"
  },
  {
    "path": "tests/test_flags.rs",
    "content": "use assert_cmd::cargo_bin_cmd;\nuse std::ffi::OsStr;\nuse std::str;\n\n/**\n * This file contains tests that test a substring of the output using '.contains'\n *\n * These tests should be the same cross platform\n */\n\nfn build_command<T: AsRef<OsStr>>(command_args: Vec<T>) -> String {\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n\n    // Hide progress bar\n    cmd.arg(\"-P\");\n\n    for p in command_args {\n        cmd.arg(p);\n    }\n    let finished = &cmd.unwrap();\n    assert_eq!(str::from_utf8(&finished.stderr).unwrap(), \"\");\n    str::from_utf8(&finished.stdout).unwrap().into()\n}\n\n// We can at least test the file names are there\n#[test]\npub fn test_basic_output() {\n    let output = build_command(vec![\"tests/test_dir/\"]);\n\n    assert!(output.contains(\" ┌─┴ \"));\n    assert!(output.contains(\"test_dir \"));\n    assert!(output.contains(\"  ┌─┴ \"));\n    assert!(output.contains(\"many \"));\n    assert!(output.contains(\"    ├── \"));\n    assert!(output.contains(\"hello_file\"));\n    assert!(output.contains(\"     ┌── \"));\n    assert!(output.contains(\"a_file \"));\n}\n\n#[test]\npub fn test_output_no_bars_means_no_excess_spaces() {\n    let output = build_command(vec![\"-b\", \"tests/test_dir/\"]);\n    // If bars are not being shown we don't need to pad the output with spaces\n    assert!(output.contains(\"many\"));\n    assert!(!output.contains(\"many    \"));\n}\n\n#[test]\npub fn test_reverse_flag() {\n    let output = build_command(vec![\"-r\", \"-c\", \"tests/test_dir/\"]);\n    assert!(output.contains(\" └─┬ test_dir \"));\n    assert!(output.contains(\"  └─┬ many \"));\n    assert!(output.contains(\"    ├── hello_file\"));\n    assert!(output.contains(\"    └── a_file \"));\n}\n\n#[test]\npub fn test_d_flag_works() {\n    // We should see the top level directory but not the sub dirs / files:\n    let output = build_command(vec![\"-d\", \"1\", \"tests/test_dir/\"]);\n    assert!(!output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_d0_works_on_multiple() {\n    // We should see the top level directory but not the sub dirs / files:\n    let output = build_command(vec![\"-d\", \"0\", \"tests/test_dir/\", \"tests/test_dir2\"]);\n    assert!(output.contains(\"test_dir \"));\n    assert!(output.contains(\"test_dir2\"));\n}\n\n#[test]\npub fn test_threads_flag_works() {\n    let output = build_command(vec![\"-T\", \"1\", \"tests/test_dir/\"]);\n    assert!(output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_d_flag_works_and_still_recurses_down() {\n    // We had a bug where running with '-d 1' would stop at the first directory and the code\n    // would fail to recurse down\n    let output = build_command(vec![\"-d\", \"1\", \"-f\", \"-c\", \"tests/test_dir2/\"]);\n    assert!(output.contains(\"1   ┌── dir\"));\n    assert!(output.contains(\"4 ┌─┴ test_dir2\"));\n}\n\n// Check against directories and files whose names are substrings of each other\n#[test]\npub fn test_ignore_dir() {\n    let output = build_command(vec![\"-c\", \"-X\", \"dir_substring\", \"tests/test_dir2/\"]);\n    assert!(!output.contains(\"dir_substring\"));\n}\n\n#[test]\npub fn test_ignore_all_in_file() {\n    let output = build_command(vec![\n        \"-c\",\n        \"-I\",\n        \"tests/test_dir_hidden_entries/.hidden_file\",\n        \"tests/test_dir_hidden_entries/\",\n    ]);\n    assert!(output.contains(\" test_dir_hidden_entries\"));\n    assert!(!output.contains(\".secret\"));\n}\n\n#[test]\npub fn test_files_from_flag_file() {\n    let output = build_command(vec![\n        \"--files-from\",\n        \"tests/test_dir_files_from/files_from.txt\",\n    ]);\n    assert!(output.contains(\"a_file\"));\n    assert!(output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_files0_from_flag_file() {\n    let output = build_command(vec![\n        \"--files0-from\",\n        \"tests/test_dir_files_from/files0_from.txt\",\n    ]);\n    assert!(output.contains(\"a_file\"));\n    assert!(output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_files_from_flag_stdin() {\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    cmd.arg(\"-P\").arg(\"--files-from\").arg(\"-\");\n    let input = b\"tests/test_dir_files_from/a_file\\ntests/test_dir_files_from/hello_file\\n\";\n    cmd.write_stdin(input.as_ref());\n    let finished = &cmd.unwrap();\n    let stderr = std::str::from_utf8(&finished.stderr).unwrap();\n    assert_eq!(stderr, \"\");\n    let output = std::str::from_utf8(&finished.stdout).unwrap();\n    assert!(output.contains(\"a_file\"));\n    assert!(output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_files0_from_flag_stdin() {\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    cmd.arg(\"-P\").arg(\"--files0-from\").arg(\"-\");\n    let input = b\"tests/test_dir_files_from/a_file\\0tests/test_dir_files_from/hello_file\\0\";\n    cmd.write_stdin(input.as_ref());\n    let finished = &cmd.unwrap();\n    let stderr = std::str::from_utf8(&finished.stderr).unwrap();\n    assert_eq!(stderr, \"\");\n    let output = std::str::from_utf8(&finished.stdout).unwrap();\n    assert!(output.contains(\"a_file\"));\n    assert!(output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_with_bad_param() {\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    cmd.arg(\"-P\").arg(\"bad_place\");\n    let output_error = cmd.unwrap_err();\n    let result = output_error.as_output().unwrap();\n    let stderr = str::from_utf8(&result.stderr).unwrap();\n    assert!(stderr.contains(\"No such file or directory\"));\n}\n\n#[test]\npub fn test_hidden_flag() {\n    // Check we can see the hidden file normally\n    let output = build_command(vec![\"-c\", \"tests/test_dir_hidden_entries/\"]);\n    assert!(output.contains(\".hidden_file\"));\n    assert!(output.contains(\"┌─┴ test_dir_hidden_entries\"));\n\n    // Check that adding the '-h' flag causes us to not see hidden files\n    let output = build_command(vec![\"-c\", \"-i\", \"tests/test_dir_hidden_entries/\"]);\n    assert!(!output.contains(\".hidden_file\"));\n    assert!(output.contains(\"┌── test_dir_hidden_entries\"));\n}\n\n#[test]\npub fn test_number_of_files() {\n    // Check we can see the hidden file normally\n    let output = build_command(vec![\"-c\", \"-f\", \"tests/test_dir\"]);\n    assert!(output.contains(\"1     ┌── a_file \"));\n    assert!(output.contains(\"1     ├── hello_file\"));\n    assert!(output.contains(\"2   ┌─┴ many\"));\n    assert!(output.contains(\"2 ┌─┴ test_dir\"));\n}\n\n#[test]\npub fn test_show_files_by_type() {\n    // Check we can list files by type\n    let output = build_command(vec![\"-c\", \"-t\", \"tests\"]);\n    assert!(output.contains(\" .unicode\"));\n    assert!(output.contains(\" .japan\"));\n    assert!(output.contains(\" .rs\"));\n    assert!(output.contains(\" (no extension)\"));\n    assert!(output.contains(\"┌─┴ (total)\"));\n}\n\n#[test]\n#[cfg(target_family = \"unix\")]\npub fn test_show_files_only() {\n    let output = build_command(vec![\"-c\", \"-F\", \"tests/test_dir\"]);\n    assert!(output.contains(\"a_file\"));\n    assert!(output.contains(\"hello_file\"));\n    assert!(!output.contains(\"many\"));\n}\n\n#[test]\npub fn test_output_skip_total() {\n    let output = build_command(vec![\n        \"--skip-total\",\n        \"tests/test_dir/many/hello_file\",\n        \"tests/test_dir/many/a_file\",\n    ]);\n    assert!(output.contains(\"hello_file\"));\n    assert!(!output.contains(\"(total)\"));\n}\n\n#[test]\npub fn test_output_screen_reader() {\n    let output = build_command(vec![\"--screen-reader\", \"-c\", \"tests/test_dir/\"]);\n    println!(\"{}\", output);\n    assert!(output.contains(\"test_dir   0\"));\n    assert!(output.contains(\"many       1\"));\n    assert!(output.contains(\"hello_file 2\"));\n    assert!(output.contains(\"a_file     2\"));\n\n    // Verify no 'symbols' reported by screen reader\n    assert!(!output.contains('│'));\n\n    for block in ['█', '▓', '▒', '░'] {\n        assert!(!output.contains(block));\n    }\n}\n\n#[test]\npub fn test_show_files_by_regex_match_lots() {\n    // Check we can see '.rs' files in the tests directory\n    let output = build_command(vec![\"-c\", \"-e\", \"\\\\.rs$\", \"tests\"]);\n    assert!(output.contains(\" ┌─┴ tests\"));\n    assert!(!output.contains(\"0B ┌── tests\"));\n    assert!(!output.contains(\"0B ┌─┴ tests\"));\n}\n\n#[test]\npub fn test_show_files_by_regex_match_nothing() {\n    // Check there are no files named: '.match_nothing' in the tests directory\n    let output = build_command(vec![\"-c\", \"-e\", \"match_nothing$\", \"tests\"]);\n    assert!(output.contains(\"0B ┌── tests\"));\n}\n\n#[test]\npub fn test_show_files_by_regex_match_multiple() {\n    let output = build_command(vec![\n        \"-c\",\n        \"-e\",\n        \"test_dir_hidden\",\n        \"-e\",\n        \"test_dir2\",\n        \"-n\",\n        \"100\",\n        \"tests\",\n    ]);\n    assert!(output.contains(\"test_dir2\"));\n    assert!(output.contains(\"test_dir_hidden\"));\n    assert!(!output.contains(\"many\")); // We do not find the 'many' folder in the 'test_dir' folder\n}\n\n#[test]\npub fn test_show_files_by_invert_regex() {\n    let output = build_command(vec![\"-c\", \"-f\", \"-v\", \"e\", \"tests/test_dir2\"]);\n    // There are 0 files without 'e' in the name\n    assert!(output.contains(\"0 ┌── test_dir2\"));\n\n    let output = build_command(vec![\"-c\", \"-f\", \"-v\", \"a\", \"tests/test_dir2\"]);\n    // There are 2 files without 'a' in the name\n    assert!(output.contains(\"2 ┌─┴ test_dir2\"));\n\n    // There are 4 files in the test_dir2 hierarchy\n    let output = build_command(vec![\"-c\", \"-f\", \"-v\", \"match_nothing$\", \"tests/test_dir2\"]);\n    assert!(output.contains(\"4 ┌─┴ test_dir2\"));\n}\n\n#[test]\npub fn test_show_files_by_invert_regex_match_multiple() {\n    // We ignore test_dir2 & test_dir_unicode, leaving the test_dir folder\n    // which has the 'many' folder inside\n    let output = build_command(vec![\n        \"-c\",\n        \"-v\",\n        \"test_dir2\",\n        \"-v\",\n        \"test_dir_unicode\",\n        \"-n\",\n        \"100\",\n        \"tests\",\n    ]);\n    assert!(!output.contains(\"test_dir2\"));\n    assert!(!output.contains(\"test_dir_unicode\"));\n    assert!(output.contains(\"many\"));\n}\n\n#[test]\npub fn test_no_color() {\n    let output = build_command(vec![\"-c\"]);\n    // Red is 31\n    assert!(!output.contains(\"\\x1B[31m\"));\n    assert!(!output.contains(\"\\x1B[0m\"));\n}\n\n#[test]\npub fn test_force_color() {\n    let output = build_command(vec![\"-C\"]);\n    // Red is 31\n    assert!(output.contains(\"\\x1B[31m\"));\n    assert!(output.contains(\"\\x1B[0m\"));\n}\n\n#[test]\npub fn test_collapse() {\n    let output = build_command(vec![\"--collapse\", \"many\", \"tests/test_dir/\"]);\n    assert!(output.contains(\"many\"));\n    assert!(!output.contains(\"hello_file\"));\n}\n\n#[test]\npub fn test_handle_duplicate_names() {\n    // Check that even if we run on a multiple directories with the same name\n    // we still show the distinct parent dir in the output\n    let output = build_command(vec![\n        \"tests/test_dir_matching/dave/dup_name\",\n        \"tests/test_dir_matching/andy/dup_name\",\n        \"ci\",\n    ]);\n    assert!(output.contains(\"andy\"));\n    assert!(output.contains(\"dave\"));\n    assert!(output.contains(\"ci\"));\n    assert!(output.contains(\"dup_name\"));\n    assert!(!output.contains(\"test_dir_matching\"));\n}\n"
  },
  {
    "path": "tests/tests.rs",
    "content": "\n"
  },
  {
    "path": "tests/tests_symlinks.rs",
    "content": "use assert_cmd::{Command, cargo_bin_cmd};\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::PathBuf;\nuse std::str;\n\nuse tempfile::Builder;\nuse tempfile::TempDir;\n\n// File sizes differ on both platform and on the format of the disk.\n// Windows: `ln` is not usually an available command; creation of symbolic links requires special enhanced permissions\n\nfn build_temp_file(dir: &TempDir) -> PathBuf {\n    let file_path = dir.path().join(\"notes.txt\");\n    let mut file = File::create(&file_path).unwrap();\n    writeln!(file, \"I am a temp file\").unwrap();\n    file_path\n}\n\nfn link_it(link_path: PathBuf, file_path_s: &str, is_soft: bool) -> String {\n    let link_name_s = link_path.to_str().unwrap();\n    let mut c = Command::new(\"ln\");\n    if is_soft {\n        c.arg(\"-s\");\n    }\n    c.arg(file_path_s);\n    c.arg(link_name_s);\n    assert!(c.output().is_ok());\n    link_name_s.into()\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_soft_sym_link() {\n    let dir = Builder::new().tempdir().unwrap();\n    let file = build_temp_file(&dir);\n    let dir_s = dir.path().to_str().unwrap();\n    let file_path_s = file.to_str().unwrap();\n\n    let link_name = dir.path().join(\"the_link\");\n    let link_name_s = link_it(link_name, file_path_s, true);\n\n    let c = format!(\" ├── {}\", link_name_s);\n    let b = format!(\" ┌── {}\", file_path_s);\n    let a = format!(\"─┴ {}\", dir_s);\n\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    // Mac test runners create long filenames in tmp directories\n    let output = cmd\n        .args([\"-p\", \"-c\", \"-s\", \"-w\", \"999\", dir_s])\n        .unwrap()\n        .stdout;\n\n    let output = str::from_utf8(&output).unwrap();\n\n    assert!(output.contains(a.as_str()));\n    assert!(output.contains(b.as_str()));\n    assert!(output.contains(c.as_str()));\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_hard_sym_link() {\n    let dir = Builder::new().tempdir().unwrap();\n    let file = build_temp_file(&dir);\n    let dir_s = dir.path().to_str().unwrap();\n    let file_path_s = file.to_str().unwrap();\n\n    let link_name = dir.path().join(\"the_link\");\n    link_it(link_name, file_path_s, false);\n\n    let file_output = format!(\" ┌── {}\", file_path_s);\n    let dirs_output = format!(\"─┴ {}\", dir_s);\n\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    // Mac test runners create long filenames in tmp directories\n    let output = cmd.args([\"-p\", \"-c\", \"-w\", \"999\", dir_s]).unwrap().stdout;\n\n    // The link should not appear in the output because multiple inodes are now ordered\n    // then filtered.\n    let output = str::from_utf8(&output).unwrap();\n    assert!(output.contains(dirs_output.as_str()));\n    assert!(output.contains(file_output.as_str()));\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_hard_sym_link_no_dup_multi_arg() {\n    let dir = Builder::new().tempdir().unwrap();\n    let dir_link = Builder::new().tempdir().unwrap();\n    let file = build_temp_file(&dir);\n    let dir_s = dir.path().to_str().unwrap();\n    let dir_link_s = dir_link.path().to_str().unwrap();\n    let file_path_s = file.to_str().unwrap();\n\n    let link_name = dir_link.path().join(\"the_link\");\n    let link_name_s = link_it(link_name, file_path_s, false);\n\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n\n    // Mac test runners create long filenames in tmp directories\n    let output = cmd\n        .args([\"-p\", \"-c\", \"-w\", \"999\", \"-b\", dir_link_s, dir_s])\n        .unwrap()\n        .stdout;\n\n    // The link or the file should appear but not both\n    let output = str::from_utf8(&output).unwrap();\n    let has_file_only = output.contains(file_path_s) && !output.contains(&link_name_s);\n    let has_link_only = !output.contains(file_path_s) && output.contains(&link_name_s);\n    assert!(has_file_only || has_link_only);\n}\n\n#[cfg_attr(target_os = \"windows\", ignore)]\n#[test]\npub fn test_recursive_sym_link() {\n    let dir = Builder::new().tempdir().unwrap();\n    let dir_s = dir.path().to_str().unwrap();\n\n    let link_name = dir.path().join(\"the_link\");\n    let link_name_s = link_it(link_name, dir_s, true);\n\n    let a = format!(\"─┬ {}\", dir_s);\n    let b = format!(\" └── {}\", link_name_s);\n\n    let mut cmd = cargo_bin_cmd!(\"dust\");\n    let output = cmd\n        .arg(\"-p\")\n        .arg(\"-c\")\n        .arg(\"-r\")\n        .arg(\"-s\")\n        .arg(\"-w\")\n        .arg(\"999\")\n        .arg(dir_s)\n        .unwrap()\n        .stdout;\n    let output = str::from_utf8(&output).unwrap();\n\n    assert!(output.contains(a.as_str()));\n    assert!(output.contains(b.as_str()));\n}\n"
  }
]