just-1.40.0/.cargo_vcs_info.json0000644000000001360000000000100121030ustar { "git": { "sha1": "679a9403ac29d7fc9045285453e58e2534d98d8d" }, "path_in_vcs": "" }just-1.40.0/.editorconfig000064400000000000000000000005461046102023000133550ustar 00000000000000# EditorConfig is awesome: https://EditorConfig.org # top-most EditorConfig file root = true [*] # Text is UTF-8 charset = utf-8 # Unix-style newlines end_of_line = lf # Newline ending every file insert_final_newline = true # Soft tabs indent_style = space # Two-space indentation indent_size = 2 # Trim trailing whitespace trim_trailing_whitespace = true just-1.40.0/.gitattributes000064400000000000000000000000101046102023000135550ustar 00000000000000* -text just-1.40.0/.github/dependabot.yml000064400000000000000000000003301046102023000150570ustar 00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / groups: GitHub_Actions: patterns: - "*" # open a single pull request to update all actions schedule: interval: weekly just-1.40.0/.github/workflows/ci.yaml000064400000000000000000000037521046102023000155560ustar 00000000000000name: CI on: pull_request: branches: - '*' push: branches: - master defaults: run: shell: bash env: RUSTFLAGS: --deny warnings jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - name: Clippy run: cargo clippy --all --all-targets - name: Format run: cargo fmt --all -- --check - name: Install Dependencies run: | sudo apt-get update sudo apt-get install ripgrep shellcheck - name: Check for Forbidden Words run: ./bin/forbid - name: Check Install Script run: shellcheck www/install.sh pages: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - name: Install `mdbook` run: cargo install mdbook - name: Install `mdbook-linkcheck` run: | mkdir -p mdbook-linkcheck cd mdbook-linkcheck wget https://github.com/Michael-F-Bryan/mdbook-linkcheck/releases/latest/download/mdbook-linkcheck.x86_64-unknown-linux-gnu.zip unzip mdbook-linkcheck.x86_64-unknown-linux-gnu.zip chmod +x mdbook-linkcheck pwd >> $GITHUB_PATH - name: Build book run: | cargo run --package generate-book mdbook build book/en mdbook build book/zh test: strategy: matrix: os: - ubuntu-latest - macos-latest - windows-latest runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v4 - name: Remove Broken WSL bash executable if: ${{ matrix.os == 'windows-latest' }} shell: cmd run: | takeown /F C:\Windows\System32\bash.exe icacls C:\Windows\System32\bash.exe /grant administrators:F del C:\Windows\System32\bash.exe - uses: Swatinem/rust-cache@v2 - name: Test run: cargo test --all - name: Test install.sh run: | bash www/install.sh --to /tmp --tag 1.25.0 /tmp/just --version just-1.40.0/.github/workflows/release.yaml000064400000000000000000000126041046102023000165770ustar 00000000000000name: Release on: push: tags: - '*' defaults: run: shell: bash env: RUSTFLAGS: --deny warnings jobs: prerelease: runs-on: ubuntu-latest outputs: value: ${{ steps.prerelease.outputs.value }} steps: - name: Prerelease Check id: prerelease run: | if [[ ${{ github.ref_name }} =~ ^[0-9]+[.][0-9]+[.][0-9]+$ ]]; then echo value=false >> $GITHUB_OUTPUT else echo value=true >> $GITHUB_OUTPUT fi package: strategy: matrix: target: - aarch64-apple-darwin - aarch64-unknown-linux-musl - arm-unknown-linux-musleabihf - armv7-unknown-linux-musleabihf - x86_64-apple-darwin - x86_64-pc-windows-msvc - aarch64-pc-windows-msvc - x86_64-unknown-linux-musl include: - target: aarch64-apple-darwin os: macos-latest target_rustflags: '' - target: aarch64-unknown-linux-musl os: ubuntu-latest target_rustflags: '--codegen linker=aarch64-linux-gnu-gcc' - target: arm-unknown-linux-musleabihf os: ubuntu-latest target_rustflags: '--codegen linker=arm-linux-gnueabihf-gcc' - target: armv7-unknown-linux-musleabihf os: ubuntu-latest target_rustflags: '--codegen linker=arm-linux-gnueabihf-gcc' - target: x86_64-apple-darwin os: macos-latest target_rustflags: '' - target: x86_64-pc-windows-msvc os: windows-latest - target: aarch64-pc-windows-msvc os: windows-latest target_rustflags: '' - target: x86_64-unknown-linux-musl os: ubuntu-latest target_rustflags: '' runs-on: ${{matrix.os}} needs: - prerelease steps: - uses: actions/checkout@v4 - name: Install AArch64 Toolchain if: ${{ matrix.target == 'aarch64-unknown-linux-musl' }} run: | sudo apt-get update sudo apt-get install gcc-aarch64-linux-gnu libc6-dev-i386 - name: Install ARM Toolchain if: ${{ matrix.target == 'arm-unknown-linux-musleabihf' || matrix.target == 'armv7-unknown-linux-musleabihf' }} run: | sudo apt-get update sudo apt-get install gcc-arm-linux-gnueabihf - name: Install AArch64 Toolchain (Windows) if: ${{ matrix.target == 'aarch64-pc-windows-msvc' }} run: | rustup target add aarch64-pc-windows-msvc - name: Generate Completion Scripts and Manpage run: | set -euxo pipefail cargo build mkdir -p completions for shell in bash elvish fish nu powershell zsh; do ./target/debug/just --completions $shell > completions/just.$shell done mkdir -p man ./target/debug/just --man > man/just.1 - name: Package id: package env: TARGET: ${{ matrix.target }} REF: ${{ github.ref }} OS: ${{ matrix.os }} TARGET_RUSTFLAGS: ${{ matrix.target_rustflags }} run: ./bin/package shell: bash - name: Publish Archive uses: softprops/action-gh-release@v2.2.1 if: ${{ startsWith(github.ref, 'refs/tags/') }} with: draft: false files: ${{ steps.package.outputs.archive }} prerelease: ${{ needs.prerelease.outputs.value }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Publish Changelog uses: softprops/action-gh-release@v2.2.1 if: >- ${{ startsWith(github.ref, 'refs/tags/') && matrix.target == 'x86_64-unknown-linux-musl' }} with: draft: false files: CHANGELOG.md prerelease: ${{ needs.prerelease.outputs.value }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} checksum: runs-on: ubuntu-latest needs: - package - prerelease steps: - name: Download Release Archives env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: >- gh release download --repo casey/just --pattern '*' --dir release ${{ github.ref_name }} - name: Create Checksums run: | cd release shasum -a 256 * > ../SHA256SUMS - name: Publish Checksums uses: softprops/action-gh-release@v2.2.1 with: draft: false files: SHA256SUMS prerelease: ${{ needs.prerelease.outputs.value }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} pages: runs-on: ubuntu-latest needs: - prerelease permissions: contents: write steps: - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - name: Install `mdbook` run: cargo install mdbook - name: Install `mdbook-linkcheck` run: | mkdir -p mdbook-linkcheck cd mdbook-linkcheck wget https://github.com/Michael-F-Bryan/mdbook-linkcheck/releases/latest/download/mdbook-linkcheck.x86_64-unknown-linux-gnu.zip unzip mdbook-linkcheck.x86_64-unknown-linux-gnu.zip chmod +x mdbook-linkcheck pwd >> $GITHUB_PATH - name: Build book run: | cargo run --package generate-book mdbook build book/en mdbook build book/zh - name: Deploy Pages uses: peaceiris/actions-gh-pages@v4 if: ${{ needs.prerelease.outputs.value }} with: github_token: ${{secrets.GITHUB_TOKEN}} publish_branch: gh-pages publish_dir: www just-1.40.0/.gitignore000064400000000000000000000003261046102023000126640ustar 00000000000000.DS_Store .idea /.vagrant /.vscode /README.html /book/en/build /book/en/src /book/zh/build /book/zh/src /fuzz/artifacts /fuzz/corpus /fuzz/target /man /target /test-utilities/Cargo.lock /test-utilities/target /tmp just-1.40.0/CHANGELOG.md000064400000000000000000004147631046102023000125230ustar 00000000000000Changelog ========= [1.40.0](https://github.com/casey/just/releases/tag/1.40.0) - 2025-03-09 ------------------------------------------------------------------------ ### Added - Allow the target of aliases to be recipes in submodules ([#2632](https://github.com/casey/just/pull/2632) by [corvusrabus](https://github.com/corvusrabus)) - Make `--list-submodules` require `--list` ([#2622](https://github.com/casey/just/pull/2622) by [casey](https://github.com/casey)) ### Fixed - Star parameters may follow default parameters ([#2660](https://github.com/casey/just/pull/2660) by [casey](https://github.com/casey)) ### Misc - Remove `test!` macro from readme ([#2648](https://github.com/casey/just/pull/2648) by [casey](https://github.com/casey)) - Sort enum variant, struct member, and trait members alphabetically ([#2646](https://github.com/casey/just/pull/2646) by [casey](https://github.com/casey)) - Add Zed extension to readme ([#2640](https://github.com/casey/just/pull/2640) by [sectore](https://github.com/sectore)) - Refactor error checking in choose function ([#2643](https://github.com/casey/just/pull/2643) by [casey](https://github.com/casey)) - Use `Test` struct instead of `test!` macro ([#2642](https://github.com/casey/just/pull/2642) by [casey](https://github.com/casey)) - Include unicode codepoint in unknown start of token error ([#2637](https://github.com/casey/just/pull/2637) by [CramBL](https://github.com/CramBL)) - Ignore broken pipe error from chooser ([#2639](https://github.com/casey/just/pull/2639) by [casey](https://github.com/casey)) - Guarantee that `Namepath`s are non-empty ([#2638](https://github.com/casey/just/pull/2638) by [casey](https://github.com/casey)) - Remove unnecessary binding modifiers ([#2636](https://github.com/casey/just/pull/2636) by [casey](https://github.com/casey)) - Document Vim and Neovim built-in syntax highlighting ([#2619](https://github.com/casey/just/pull/2619) by [laniakea64](https://github.com/laniakea64)) - Remove rust:just Repology badge ([#2614](https://github.com/casey/just/pull/2614) by [laniakea64](https://github.com/laniakea64)) - Clarify --list argument ([#2609](https://github.com/casey/just/pull/2609) by [casey](https://github.com/casey)) - Expand Windows path documentation ([#2602](https://github.com/casey/just/pull/2602) by [casey](https://github.com/casey)) - Fix readme typos ([#2596](https://github.com/casey/just/pull/2596) by [CramBL](https://github.com/CramBL)) [1.39.0](https://github.com/casey/just/releases/tag/1.39.0) - 2025-01-22 ------------------------------------------------------------------------ ### Added - Add `which()` and `require()` for finding executables ([#2440](https://github.com/casey/just/pull/2440) by [0xzhzh](https://github.com/0xzhzh)) - Add `no-exit-message` Setting and `[exit-message]` attribute ([#2568](https://github.com/casey/just/pull/2568) by [ArchieAtkinson](https://github.com/ArchieAtkinson)) - Configure alias style in `--list` with `--alias-style` ([#2342](https://github.com/casey/just/pull/2342) by [marcaddeo](https://github.com/marcaddeo)) - Add regex mismatch conditional operator ([#2490](https://github.com/casey/just/pull/2490) by [laniakea64](https://github.com/laniakea64)) - Add `read_to_string(path)` function ([#2507](https://github.com/casey/just/pull/2507) by [begoon](https://github.com/begoon)) ### Changed - Rename `read_to_string()` to `read()` ([#2518](https://github.com/casey/just/pull/2518) by [casey](https://github.com/casey)) ### Fixed - Keep `[private]` attribute when formatting assignments ([#2592](https://github.com/casey/just/pull/2592) by [casey](https://github.com/casey)) - Format `if … else if …` without superfluous braces ([#2573](https://github.com/casey/just/pull/2573) by [casey](https://github.com/casey)) - Fix error when lexing `!` at end-of-file ([#2520](https://github.com/casey/just/pull/2520) by [casey](https://github.com/casey)) - Handle recipes in submodules in fish completion script ([#2514](https://github.com/casey/just/pull/2514) by [senekor](https://github.com/senekor)) ### Misc - Add tests for `require()` ([#2594](https://github.com/casey/just/pull/2594) by [casey](https://github.com/casey)) - Evaluate concatenations and joins from left to right ([#2593](https://github.com/casey/just/pull/2593) by [casey](https://github.com/casey)) - Disable links to empty chapters in book ([#2589](https://github.com/casey/just/pull/2589) by [casey](https://github.com/casey)) - Link to CI workflow in readme ([#2586](https://github.com/casey/just/pull/2586) by [bravesasha](https://github.com/bravesasha)) - Clarify that `trim_*_match` functions take subtrings ([#2574](https://github.com/casey/just/pull/2574) by [xavdid](https://github.com/xavdid)) - Update `softprops/action-gh-release` from 2.2.0 to 2.2.1 ([#2570](https://github.com/casey/just/pull/2570) by [app/dependabot](https://github.com/app/dependabot)) - Check attributes in parser instead of analyzer ([#2560](https://github.com/casey/just/pull/2560) by [casey](https://github.com/casey)) - Ignore I/O errors when writing changelog to stdout ([#2558](https://github.com/casey/just/pull/2558) by [casey](https://github.com/casey)) - Add `quiet` setting and fix typos in readme ([#2549](https://github.com/casey/just/pull/2549) by [unennhexium](https://github.com/unennhexium)) - Update readme to use `env()` instead of `env_var*()` ([#2546](https://github.com/casey/just/pull/2546) by [laniakea64](https://github.com/laniakea64)) - Document using `||` to provide default for empty environment variable ([#2545](https://github.com/casey/just/pull/2545) by [casey](https://github.com/casey)) - Refactor `Line` predicates ([#2543](https://github.com/casey/just/pull/2543) by [casey](https://github.com/casey)) - Fix typos in README.md ([#2542](https://github.com/casey/just/pull/2542) by [laniakea64](https://github.com/laniakea64)) - Add full example getting XDG user directory to readme ([#2536](https://github.com/casey/just/pull/2536) by [laniakea64](https://github.com/laniakea64)) - Document weird behavior of duplicate definitions in imports ([#2541](https://github.com/casey/just/pull/2541) by [casey](https://github.com/casey)) - Update readme to reflect actual behavior of user directory functions ([#2535](https://github.com/casey/just/pull/2535) by [casey](https://github.com/casey)) - Update softprops/action-gh-release to 2.2.0 ([#2530](https://github.com/casey/just/pull/2530) by [app/dependabot](https://github.com/app/dependabot)) - Document running python recipes with `uv` ([#2526](https://github.com/casey/just/pull/2526) by [casey](https://github.com/casey)) - Sort functions alphabetically ([#2525](https://github.com/casey/just/pull/2525) by [casey](https://github.com/casey)) - Fix truncated bang operator error message ([#2522](https://github.com/casey/just/pull/2522) by [casey](https://github.com/casey)) - Include source path in dump JSON ([#2466](https://github.com/casey/just/pull/2466) by [psibi](https://github.com/psibi)) - Add attribute set ([#2419](https://github.com/casey/just/pull/2419) by [neunenak](https://github.com/neunenak)) [1.38.0](https://github.com/casey/just/releases/tag/1.38.0) - 2024-12-10 ------------------------------------------------------------------------ ### Added - Add `[openbsd]` recipe attribute ([#2497](https://github.com/casey/just/pull/2497) by [vtamara](https://github.com/vtamara)) - Add `[working-directory]` recipe attribute ([#2438](https://github.com/casey/just/pull/2438) by [bcheidemann](https://github.com/bcheidemann)) - Add `--allow-missing` to ignore missing recipe and submodule errors ([#2460](https://github.com/casey/just/pull/2460) by [R3ZV](https://github.com/R3ZV)) ### Changed - Add snap package back to readme ([#2506](https://github.com/casey/just/pull/2506) by [casey](https://github.com/casey)) - Forbid duplicate non-repeatable attributes ([#2483](https://github.com/casey/just/pull/2483) by [casey](https://github.com/casey)) ### Misc - Publish docs to GitHub pages on release only ([#2516](https://github.com/casey/just/pull/2516) by [casey](https://github.com/casey)) - Note lack of support for string interpolation ([#2515](https://github.com/casey/just/pull/2515) by [casey](https://github.com/casey)) - Embolden help text errors ([#2502](https://github.com/casey/just/pull/2502) by [casey](https://github.com/casey)) - Style help text ([#2501](https://github.com/casey/just/pull/2501) by [casey](https://github.com/casey)) - Add `--request` subcommand for testing ([#2498](https://github.com/casey/just/pull/2498) by [casey](https://github.com/casey)) - [bin/forbid] Improve error message if ripgrep is missing ([#2493](https://github.com/casey/just/pull/2493) by [casey](https://github.com/casey)) - Fix Rust 1.83 clippy warnings ([#2487](https://github.com/casey/just/pull/2487) by [casey](https://github.com/casey)) - Refactor JSON tests ([#2484](https://github.com/casey/just/pull/2484) by [casey](https://github.com/casey)) - Get `Config` from `ExecutionContext` instead of passing separately ([#2481](https://github.com/casey/just/pull/2481) by [casey](https://github.com/casey)) - Don't write justfiles unchanged by formatting ([#2479](https://github.com/casey/just/pull/2479) by [casey](https://github.com/casey)) [1.37.0](https://github.com/casey/just/releases/tag/1.37.0) - 2024-11-20 ------------------------------------------------------------------------ ### Added - Add `style()` function ([#2462](https://github.com/casey/just/pull/2462) by [casey](https://github.com/casey)) - Terminal escape sequence constants ([#2461](https://github.com/casey/just/pull/2461) by [casey](https://github.com/casey)) - Add `&&` and `||` operators ([#2444](https://github.com/casey/just/pull/2444) by [casey](https://github.com/casey)) ### Changed - Make recipe doc attribute override comment ([#2470](https://github.com/casey/just/pull/2470) by [casey](https://github.com/casey)) - Don't export constants ([#2449](https://github.com/casey/just/pull/2449) by [casey](https://github.com/casey)) - Allow duplicate imports ([#2437](https://github.com/casey/just/pull/2437) by [casey](https://github.com/casey)) - Publish single SHA256SUM file with releases ([#2417](https://github.com/casey/just/pull/2417) by [casey](https://github.com/casey)) - Mark recipes with private attribute as private in JSON dump ([#2415](https://github.com/casey/just/pull/2415) by [casey](https://github.com/casey)) - Forbid invalid attributes on assignments ([#2412](https://github.com/casey/just/pull/2412) by [casey](https://github.com/casey)) ### Misc - Update `softprops/action-gh-release` ([#2471](https://github.com/casey/just/pull/2471) by [app/dependabot](https://github.com/app/dependabot)) - Add `-g` to `rust-just` install instructions ([#2459](https://github.com/casey/just/pull/2459) by [gnpaone](https://github.com/gnpaone)) - Change doc backtick color to cyan ([#2469](https://github.com/casey/just/pull/2469) by [casey](https://github.com/casey)) - Note that `set shell` is not used for `[script]` recipes ([#2468](https://github.com/casey/just/pull/2468) by [iloveitaly](https://github.com/iloveitaly)) - Replace `derivative` with `derive-where` ([#2465](https://github.com/casey/just/pull/2465) by [laniakea64](https://github.com/laniakea64)) - Highlight backticks in docs when listing recipes ([#2423](https://github.com/casey/just/pull/2423) by [neunenak](https://github.com/neunenak)) - Update setup-just version in README ([#2456](https://github.com/casey/just/pull/2456) by [Julian](https://github.com/Julian)) - Fix shell function example in readme ([#2454](https://github.com/casey/just/pull/2454) by [casey](https://github.com/casey)) - Update softprops/action-gh-release ([#2450](https://github.com/casey/just/pull/2450) by [app/dependabot](https://github.com/app/dependabot)) - Use `justfile` instead of `mf` on invalid examples in readme ([#2447](https://github.com/casey/just/pull/2447) by [casey](https://github.com/casey)) - Add advice on printing complex strings ([#2446](https://github.com/casey/just/pull/2446) by [casey](https://github.com/casey)) - Document using functions in variable assignments ([#2431](https://github.com/casey/just/pull/2431) by [offby1](https://github.com/offby1)) - Use prettier string comparison in tests ([#2435](https://github.com/casey/just/pull/2435) by [neunenak](https://github.com/neunenak)) - Note `shell(…)` as an alternative to backticks ([#2430](https://github.com/casey/just/pull/2430) by [offby1](https://github.com/offby1)) - Update nix package links ([#2441](https://github.com/casey/just/pull/2441) by [yunusey](https://github.com/yunusey)) - Update README.中文.md ([#2424](https://github.com/casey/just/pull/2424) by [Jannchie](https://github.com/Jannchie)) - Add Recipe::subsequents ([#2428](https://github.com/casey/just/pull/2428) by [casey](https://github.com/casey)) - Add subsequents to grammar ([#2427](https://github.com/casey/just/pull/2427) by [casey](https://github.com/casey)) - Document checking releases hashes ([#2418](https://github.com/casey/just/pull/2418) by [casey](https://github.com/casey)) - Show how to access positional arguments with powershell ([#2405](https://github.com/casey/just/pull/2405) by [casey](https://github.com/casey)) - Use `-CommandWithArgs` instead of `-cwa` ([#2404](https://github.com/casey/just/pull/2404) by [casey](https://github.com/casey)) - Document `-cwa` flag for PowerShell positional arguments ([#2403](https://github.com/casey/just/pull/2403) by [casey](https://github.com/casey)) - Use `unwrap_or` when creating relative path in loader ([#2400](https://github.com/casey/just/pull/2400) by [casey](https://github.com/casey)) [1.36.0](https://github.com/casey/just/releases/tag/1.36.0) - 2024-09-30 ------------------------------------------------------------------------ ### Changed - Allow default values to use earlier recipe arguments ([#2382](https://github.com/casey/just/pull/2382) by [casey](https://github.com/casey)) ### Added - Add `--one` flag to forbid multiple recipes from being invoked on the command line ([#2374](https://github.com/casey/just/pull/2374) by [casey](https://github.com/casey)) - Allow including arbitrary characters in strings with `\u{…}` ([#2360](https://github.com/casey/just/pull/2360) by [laniakea64](https://github.com/laniakea64)) - Print recipe doc string when`--explain` flag is passed ([#2319](https://github.com/casey/just/pull/2319) by [neunenak](https://github.com/neunenak)) ### Misc - Use unwrap_or_default() when getting default color and verbosity ([#2397](https://github.com/casey/just/pull/2397) by [casey](https://github.com/casey)) - De-duplicate suggestion methods ([#2392](https://github.com/casey/just/pull/2392) by [neunenak](https://github.com/neunenak)) - Refactor analyzer ([#2378](https://github.com/casey/just/pull/2378) by [neunenak](https://github.com/neunenak)) - Use `console` codeblocks in readme ([#2388](https://github.com/casey/just/pull/2388) by [casey](https://github.com/casey)) - Split packages table by platform ([#2385](https://github.com/casey/just/pull/2385) by [casey](https://github.com/casey)) - Document npm package ([#2384](https://github.com/casey/just/pull/2384) by [casey](https://github.com/casey)) - Add PyPI install instructions ([#2383](https://github.com/casey/just/pull/2383) by [casey](https://github.com/casey)) - Remove alias shadows recipe error ([#2375](https://github.com/casey/just/pull/2375) by [neunenak](https://github.com/neunenak)) - Name instead of number book chapter files ([#2372](https://github.com/casey/just/pull/2372) by [casey](https://github.com/casey)) - Add groups to project justfile ([#2351](https://github.com/casey/just/pull/2351) by [neunenak](https://github.com/neunenak)) - Document `\u{...}` ([#2371](https://github.com/casey/just/pull/2371) by [laniakea64](https://github.com/laniakea64)) - Remove old recipes from project justfile ([#2367](https://github.com/casey/just/pull/2367) by [casey](https://github.com/casey)) - Document `--dotenv-path` in readme ([#2366](https://github.com/casey/just/pull/2366) by [willie](https://github.com/willie)) - Remove ref-type crate ([#2364](https://github.com/casey/just/pull/2364) by [casey](https://github.com/casey)) - Fix type names in redefinition error message ([#2353](https://github.com/casey/just/pull/2353) by [marcaddeo](https://github.com/marcaddeo)) - Use relative in `.sha256sum` files ([#2358](https://github.com/casey/just/pull/2358) by [casey](https://github.com/casey)) - Link to readme in CONTRIBUTING.md ([#2348](https://github.com/casey/just/pull/2348) by [casey](https://github.com/casey)) - Fix clippy lints ([#2347](https://github.com/casey/just/pull/2347) by [casey](https://github.com/casey)) - Simplify `Subcommand::run` ([#2336](https://github.com/casey/just/pull/2336) by [neunenak](https://github.com/neunenak)) - Update module issue link in readme ([#2345](https://github.com/casey/just/pull/2345) by [casey](https://github.com/casey)) - Add blank line between CI workflow jobs ([#2343](https://github.com/casey/just/pull/2343) by [casey](https://github.com/casey)) - Color groups in `--list` output ([#2340](https://github.com/casey/just/pull/2340) by [casey](https://github.com/casey)) - Refactor and document subcommand and search ([#2335](https://github.com/casey/just/pull/2335) by [neunenak](https://github.com/neunenak)) - Document private variables ([#2331](https://github.com/casey/just/pull/2331) by [Jasha10](https://github.com/Jasha10)) [1.35.0](https://github.com/casey/just/releases/tag/1.35.0) - 2024-08-28 ------------------------------------------------------------------------ ### Changed - Allow fallback with recipes in submodules ([#2329](https://github.com/casey/just/pull/2329) by [casey](https://github.com/casey)) - Allow `[private]` attribute on assignments ([#2300](https://github.com/casey/just/pull/2300) by [adsnaider](https://github.com/adsnaider)) ### Misc - Generate `.sha256sum` files for release artifacts ([#2323](https://github.com/casey/just/pull/2323) by [twm](https://github.com/twm)) - Clarify that subsequent dependencies run immediately after recipe ([#2326](https://github.com/casey/just/pull/2326) by [casey](https://github.com/casey)) - Fix readme typo ([#2321](https://github.com/casey/just/pull/2321) by [arminius-smh](https://github.com/arminius-smh)) - Remove Config::run ([#2320](https://github.com/casey/just/pull/2320) by [neunenak](https://github.com/neunenak)) - Bump MSRV to 1.74 ([#2306](https://github.com/casey/just/pull/2306) by [casey](https://github.com/casey)) - Remove logging ([#2305](https://github.com/casey/just/pull/2305) by [casey](https://github.com/casey)) - Group commands under dedicated heading in `--help` output ([#2302](https://github.com/casey/just/pull/2302) by [casey](https://github.com/casey)) - Fix readme typo ([#2297](https://github.com/casey/just/pull/2297) by [nyurik](https://github.com/nyurik)) [1.34.0](https://github.com/casey/just/releases/tag/1.34.0) - 2024-08-02 ------------------------------------------------------------------------ ### Fixed - Make function paths relative to correct working directory ([#2294](https://github.com/casey/just/pull/2294) by [casey](https://github.com/casey)) ### Changed - Keep multi-line shebangs together ([#2276](https://github.com/casey/just/pull/2276) by [vkstrm](https://github.com/vkstrm)) ### Misc - Document `set working-directory` ([#2288](https://github.com/casey/just/pull/2288) by [nyurik](https://github.com/nyurik)) - Fix readme typos ([#2289](https://github.com/casey/just/pull/2289) by [casey](https://github.com/casey)) [1.33.0](https://github.com/casey/just/releases/tag/1.33.0) - 2024-07-30 ------------------------------------------------------------------------ ### Fixed - Use correct backtick and `shell()` expression working directory in submodules ([#2285](https://github.com/casey/just/pull/2285) by [casey](https://github.com/casey)) ### Added - Add `working-directory` setting ([#2283](https://github.com/casey/just/pull/2283) by [nyurik](https://github.com/nyurik)) - Allow `[group]` attribute on submodules ([#2263](https://github.com/casey/just/pull/2263) by [jmwoliver](https://github.com/jmwoliver)) - Allow empty `[script]` attribute and add `set script-interpreter` ([#2264](https://github.com/casey/just/pull/2264) by [casey](https://github.com/casey)) ### Misc - Document which attributes apply to which items ([#2282](https://github.com/casey/just/pull/2282) by [casey](https://github.com/casey)) - Add missing productions ([#2280](https://github.com/casey/just/pull/2280) by [poliorcetics](https://github.com/poliorcetics)) - Fix Rust 1.80.0 warnings ([#2281](https://github.com/casey/just/pull/2281) by [casey](https://github.com/casey)) - Update softprops/action-gh-release ([#2269](https://github.com/casey/just/pull/2269) by [app/dependabot](https://github.com/app/dependabot)) - Remove `(no group)` header before ungrouped recipes ([#2268](https://github.com/casey/just/pull/2268) by [casey](https://github.com/casey)) - Document `script-interpreter` setting ([#2265](https://github.com/casey/just/pull/2265) by [casey](https://github.com/casey)) - `set dotenv-path` does not override `set dotenv-filename` ([#2262](https://github.com/casey/just/pull/2262) by [casey](https://github.com/casey)) [1.32.0](https://github.com/casey/just/releases/tag/1.32.0) - 2024-07-17 ------------------------------------------------------------------------ ### Added - Add unstable `[script(…)]` attribute ([#2259](https://github.com/casey/just/pull/2259) by [casey](https://github.com/casey)) - Add `[extension: 'EXT']` attribute to set shebang recipe script file extension ([#2256](https://github.com/casey/just/pull/2256) by [casey](https://github.com/casey)) - Suppress mod doc comment with empty `[doc]` attribute ([#2254](https://github.com/casey/just/pull/2254) by [casey](https://github.com/casey)) - Allow `[doc]` annotation on modules ([#2247](https://github.com/casey/just/pull/2247) by [neunenak](https://github.com/neunenak)) [1.31.0](https://github.com/casey/just/releases/tag/1.31.0) - 2024-07-14 ------------------------------------------------------------------------ ### Stabilized - Stabilize modules ([#2250](https://github.com/casey/just/pull/2250) by [casey](https://github.com/casey)) ### Added - Allow `mod` path to be directory containing module source ([#2238](https://github.com/casey/just/pull/2238) by [casey](https://github.com/casey)) - Allow enabling unstable features with `set unstable` ([#2237](https://github.com/casey/just/pull/2237) by [casey](https://github.com/casey)) - Allow abbreviating functions ending in `_directory` to `_dir` ([#2235](https://github.com/casey/just/pull/2235) by [casey](https://github.com/casey)) ### Fixed - Lexiclean search directory so `..` does not check the current directory ([#2236](https://github.com/casey/just/pull/2236) by [casey](https://github.com/casey)) ### Misc - Print space before submodules in `--list` with groups ([#2244](https://github.com/casey/just/pull/2244) by [casey](https://github.com/casey)) [1.30.1](https://github.com/casey/just/releases/tag/1.30.1) - 2024-07-06 ------------------------------------------------------------------------ ### Fixed - Fix function argument count mismatch error message ([#2231](https://github.com/casey/just/pull/2231) by [casey](https://github.com/casey)) [1.30.0](https://github.com/casey/just/releases/tag/1.30.0) - 2024-07-06 ------------------------------------------------------------------------ ### Fixed - Allow comments after `mod` statements ([#2201](https://github.com/casey/just/pull/2201) by [casey](https://github.com/casey)) ### Changed - Allow unstable features with `--summary` ([#2210](https://github.com/casey/just/pull/2210) by [casey](https://github.com/casey)) - Don't analyze comments when `ignore-comments` is set ([#2180](https://github.com/casey/just/pull/2180) by [casey](https://github.com/casey)) - List recipes by group in group justfile order with `just --list --unsorted` ([#2164](https://github.com/casey/just/pull/2164) by [casey](https://github.com/casey)) - List groups in source order with `just --groups --unsorted` ([#2160](https://github.com/casey/just/pull/2160) by [casey](https://github.com/casey)) ### Added - Avoid `install` and add 32-bit arm targets to `install.sh` ([#2214](https://github.com/casey/just/pull/2214) by [CramBL](https://github.com/CramBL)) - Give modules doc comments for `--list` ([#2199](https://github.com/casey/just/pull/2199) by [Spatenheinz](https://github.com/Spatenheinz)) - Add `datetime()` and `datetime_utc()` functions ([#2167](https://github.com/casey/just/pull/2167) by [casey](https://github.com/casey)) - Allow setting more command-line options with environment variables ([#2161](https://github.com/casey/just/pull/2161) by [casey](https://github.com/casey)) ### Library - Don't exit process in `run()` on argument parse error ([#2176](https://github.com/casey/just/pull/2176) by [casey](https://github.com/casey)) - Allow passing command-line arguments into `run()` ([#2173](https://github.com/casey/just/pull/2173) by [casey](https://github.com/casey)) - Ignore env_logger initialization errors ([#2170](https://github.com/casey/just/pull/2170) by [EnigmaCurry](https://github.com/EnigmaCurry)) ### Misc - Tweak readme ([#2227](https://github.com/casey/just/pull/2227) by [casey](https://github.com/casey)) - Add development guide to readme ([#2226](https://github.com/casey/just/pull/2226) by [casey](https://github.com/casey)) - Add shell-expanded string syntax to grammar ([#2223](https://github.com/casey/just/pull/2223) by [casey](https://github.com/casey)) - Add recipe for testing bash completion script ([#2221](https://github.com/casey/just/pull/2221) by [casey](https://github.com/casey)) - Fix use of `justfile_directory()` in readme ([#2219](https://github.com/casey/just/pull/2219) by [casey](https://github.com/casey)) - Use default values for `--list-heading` and `--list-prefix` ([#2213](https://github.com/casey/just/pull/2213) by [casey](https://github.com/casey)) - Use `clap::ValueParser` ([#2211](https://github.com/casey/just/pull/2211) by [neunenak](https://github.com/neunenak)) - Document module doc comments in readme ([#2208](https://github.com/casey/just/pull/2208) by [casey](https://github.com/casey)) - Use `-and` instead of `&&` in PowerShell completion script ([#2204](https://github.com/casey/just/pull/2204) by [casey](https://github.com/casey)) - Fix readme formatting ([#2203](https://github.com/casey/just/pull/2203) by [casey](https://github.com/casey)) - Link to justfiles on GitHub in readme ([#2198](https://github.com/casey/just/pull/2198) by [bukowa](https://github.com/bukowa)) - Link to modules when first introduced in readme ([#2193](https://github.com/casey/just/pull/2193) by [casey](https://github.com/casey)) - Update `softprops/action-gh-release` ([#2183](https://github.com/casey/just/pull/2183) by [app/dependabot](https://github.com/app/dependabot)) - Document remote justfile workaround ([#2175](https://github.com/casey/just/pull/2175) by [casey](https://github.com/casey)) - Document library interface ([#2174](https://github.com/casey/just/pull/2174) by [casey](https://github.com/casey)) - Remove dependency on cradle ([#2169](https://github.com/casey/just/pull/2169) by [nc7s](https://github.com/nc7s)) - Add note to readme about quoting paths on Windows ([#2166](https://github.com/casey/just/pull/2166) by [casey](https://github.com/casey)) - Add missing changelog credits ([#2163](https://github.com/casey/just/pull/2163) by [casey](https://github.com/casey)) - Credit myself in changelog ([#2162](https://github.com/casey/just/pull/2162) by [casey](https://github.com/casey)) [1.29.1](https://github.com/casey/just/releases/tag/1.29.1) - 2024-06-14 ------------------------------------------------------------------------ ### Fixed - Fix unexport syntax conflicts ([#2158](https://github.com/casey/just/pull/2158) by [casey](https://github.com/casey)) [1.29.0](https://github.com/casey/just/releases/tag/1.29.0) - 2024-06-13 ------------------------------------------------------------------------ ### Added - Add [positional-arguments] attribute ([#2151](https://github.com/casey/just/pull/2151) by [casey](https://github.com/casey)) - Use `--justfile` in Fish shell completions ([#2148](https://github.com/casey/just/pull/2148) by [rubot](https://github.com/rubot)) - Add `is_dependency()` function ([#2139](https://github.com/casey/just/pull/2139) by [neunenak](https://github.com/neunenak)) - Allow printing nu completion script with `just --completions nushell` ([#2140](https://github.com/casey/just/pull/2140) by [casey](https://github.com/casey)) - Add `[ATTRIBUTE: VALUE]` shorthand ([#2136](https://github.com/casey/just/pull/2136) by [neunenak](https://github.com/neunenak)) - Allow unexporting environment variables ([#2098](https://github.com/casey/just/pull/2098) by [neunenak](https://github.com/neunenak)) ### Fixed - Load environment file from dotenv-path relative to working directory ([#2152](https://github.com/casey/just/pull/2152) by [casey](https://github.com/casey)) - Fix `fzf` chooser preview with space-separated module paths ([#2141](https://github.com/casey/just/pull/2141) by [casey](https://github.com/casey)) ### Misc - Improve argument parsing and error handling for submodules ([#2154](https://github.com/casey/just/pull/2154) by [casey](https://github.com/casey)) - Document shell expanded string defaults ([#2153](https://github.com/casey/just/pull/2153) by [casey](https://github.com/casey)) - Test bare bash path in shebang on windows ([#2144](https://github.com/casey/just/pull/2144) by [casey](https://github.com/casey)) - Test shell not found error messages ([#2145](https://github.com/casey/just/pull/2145) by [casey](https://github.com/casey)) - Refactor evaluator ([#2138](https://github.com/casey/just/pull/2138) by [neunenak](https://github.com/neunenak)) - Fix man page generation in release workflow ([#2132](https://github.com/casey/just/pull/2132) by [casey](https://github.com/casey)) [1.28.0](https://github.com/casey/just/releases/tag/1.28.0) - 2024-06-05 ------------------------------------------------------------------------ ### Changed - Write shebang recipes to $XDG_RUNTIME_DIR ([#2128](https://github.com/casey/just/pull/2128) by [casey](https://github.com/casey)) - Add `set dotenv-required` to require an environment file ([#2116](https://github.com/casey/just/pull/2116) by [casey](https://github.com/casey)) - Don't display submodule recipes in `--list` ([#2112](https://github.com/casey/just/pull/2112) by [casey](https://github.com/casey)) ### Added - Allow listing recipes in submodules with `--list-submodules` ([#2113](https://github.com/casey/just/pull/2113) by [casey](https://github.com/casey)) - Show recipes in submodules with `--show RECIPE::PATH` ([#2111](https://github.com/casey/just/pull/2111) by [casey](https://github.com/casey)) - Add `--timestamp-format` ([#2106](https://github.com/casey/just/pull/2106) by [neunenak](https://github.com/neunenak)) - Allow listing submodule recipes with `--list PATH` ([#2108](https://github.com/casey/just/pull/2108) by [casey](https://github.com/casey)) - Print recipe command timestamps with `--timestamps` ([#2084](https://github.com/casey/just/pull/2084) by [neunenak](https://github.com/neunenak)) - Add `module_file()` and `module_directory()` functions ([#2105](https://github.com/casey/just/pull/2105) by [casey](https://github.com/casey)) ### Fixed - Use space-separated recipe paths in `--choose` ([#2115](https://github.com/casey/just/pull/2115) by [casey](https://github.com/casey)) - Fix bash completion for aliases ([#2104](https://github.com/casey/just/pull/2104) by [laniakea64](https://github.com/laniakea64)) ### Misc - Don't check in manpage ([#2130](https://github.com/casey/just/pull/2130) by [casey](https://github.com/casey)) - Document default shell ([#2129](https://github.com/casey/just/pull/2129) by [casey](https://github.com/casey)) - Remove duplicate section in Chinese readme ([#2127](https://github.com/casey/just/pull/2127) by [potterxu](https://github.com/potterxu)) - Update Chinese readme ([#2124](https://github.com/casey/just/pull/2124) by [potterxu](https://github.com/potterxu)) - Fix typo in readme ([#2122](https://github.com/casey/just/pull/2122) by [potterxu](https://github.com/potterxu)) - Don't check in auto-generated completion scripts ([#2120](https://github.com/casey/just/pull/2120) by [casey](https://github.com/casey)) - Document when dependencies run in readme ([#2103](https://github.com/casey/just/pull/2103) by [casey](https://github.com/casey)) - Build aarch64-pc-windows-msvc release binaries ([#2100](https://github.com/casey/just/pull/2100) by [alshdavid](https://github.com/alshdavid)) - Clarify that `dotenv-path`-given env file is required ([#2099](https://github.com/casey/just/pull/2099) by [casey](https://github.com/casey)) - Print multi-line doc comments before recipe in `--list` ([#2090](https://github.com/casey/just/pull/2090) by [casey](https://github.com/casey)) - List unsorted imported recipes by import depth and offset ([#2092](https://github.com/casey/just/pull/2092) by [casey](https://github.com/casey)) - Update README.md ([#2091](https://github.com/casey/just/pull/2091) by [laniakea64](https://github.com/laniakea64)) [1.27.0](https://github.com/casey/just/releases/tag/1.27.0) - 2024-05-25 ------------------------------------------------------------------------ ### Changed - Use cache dir for temporary files ([#2067](https://github.com/casey/just/pull/2067) by [casey](https://github.com/casey)) ### Added - Add `[doc]` attribute to set and suppress documentation comments ([#2050](https://github.com/casey/just/pull/2050) by [neunenak](https://github.com/neunenak)) - Add source_file() and source_directory() functions ([#2088](https://github.com/casey/just/pull/2088) by [casey](https://github.com/casey)) - Add recipe groups ([#1842](https://github.com/casey/just/pull/1842) by [neunenak](https://github.com/neunenak)) - Add shell() function for running external commands ([#2047](https://github.com/casey/just/pull/2047) by [gyreas](https://github.com/gyreas)) - Add `--global-justfile` flag ([#1846](https://github.com/casey/just/pull/1846) by [neunenak](https://github.com/neunenak)) - Add shell-expanded strings ([#2055](https://github.com/casey/just/pull/2055) by [casey](https://github.com/casey)) - Add `encode_uri_component` function ([#2052](https://github.com/casey/just/pull/2052) by [laniakea64](https://github.com/laniakea64)) - Add `choose` function for generating random strings ([#2049](https://github.com/casey/just/pull/2049) by [laniakea64](https://github.com/laniakea64)) - Add predefined constants ([#2054](https://github.com/casey/just/pull/2054) by [casey](https://github.com/casey)) - Allow setting some command-line options with environment variables ([#2044](https://github.com/casey/just/pull/2044) by [neunenak](https://github.com/neunenak)) - Add prepend() function ([#2045](https://github.com/casey/just/pull/2045) by [gyreas](https://github.com/gyreas)) - Add append() function ([#2046](https://github.com/casey/just/pull/2046) by [gyreas](https://github.com/gyreas)) - Add --man subcommand ([#2041](https://github.com/casey/just/pull/2041) by [casey](https://github.com/casey)) - Make `dotenv-path` relative to working directory ([#2040](https://github.com/casey/just/pull/2040) by [casey](https://github.com/casey)) - Add `assert` expression ([#1845](https://github.com/casey/just/pull/1845) by [de1iza](https://github.com/de1iza)) - Add 'allow-duplicate-variables' setting ([#1922](https://github.com/casey/just/pull/1922) by [Mijago](https://github.com/Mijago)) ### Fixed - List modules in source order with `--unsorted` ([#2085](https://github.com/casey/just/pull/2085) by [casey](https://github.com/casey)) - Show submodule recipes in --choose ([#2069](https://github.com/casey/just/pull/2069) by [casey](https://github.com/casey)) - Allow multiple imports of the same file in different modules ([#2065](https://github.com/casey/just/pull/2065) by [casey](https://github.com/casey)) - Fix submodule recipe listing indentation ([#2063](https://github.com/casey/just/pull/2063) by [casey](https://github.com/casey)) - Pass command as first argument to `shell` ([#2061](https://github.com/casey/just/pull/2061) by [casey](https://github.com/casey)) - Allow shell expanded strings in mod and import paths ([#2059](https://github.com/casey/just/pull/2059) by [casey](https://github.com/casey)) - Run imported recipes in root justfile with correct working directory ([#2056](https://github.com/casey/just/pull/2056) by [casey](https://github.com/casey)) - Fix output `\r\n` stripping ([#2035](https://github.com/casey/just/pull/2035) by [casey](https://github.com/casey)) ### Misc - Forbid whitespace in shell-expanded string prefixes ([#2083](https://github.com/casey/just/pull/2083) by [casey](https://github.com/casey)) - Add Debian and Ubuntu install instructions to readme ([#2072](https://github.com/casey/just/pull/2072) by [casey](https://github.com/casey)) - Remove snap installation instructions from readme ([#2070](https://github.com/casey/just/pull/2070) by [casey](https://github.com/casey)) - Fallback to wget in install script if curl isn't available([#1913](https://github.com/casey/just/pull/1913) by [tgross35](https://github.com/tgross35)) - Use std::io::IsTerminal instead of atty crate ([#2066](https://github.com/casey/just/pull/2066) by [casey](https://github.com/casey)) - Improve `shell()` documentation ([#2060](https://github.com/casey/just/pull/2060) by [laniakea64](https://github.com/laniakea64)) - Add bash completion for snap ([#2058](https://github.com/casey/just/pull/2058) by [albertodonato](https://github.com/albertodonato)) - Refactor list subcommand ([#2062](https://github.com/casey/just/pull/2062) by [casey](https://github.com/casey)) - Document working directory ([#2053](https://github.com/casey/just/pull/2053) by [casey](https://github.com/casey)) - Replace FunctionContext with Evaluator ([#2048](https://github.com/casey/just/pull/2048) by [casey](https://github.com/casey)) - Update clap to version 4 ([#1924](https://github.com/casey/just/pull/1924) by [poliorcetics](https://github.com/poliorcetics)) - Cleanup ([#2026](https://github.com/casey/just/pull/2026) by [adamnemecek](https://github.com/adamnemecek)) - Increase --list maximum alignable width from 30 to 50 ([#2039](https://github.com/casey/just/pull/2039) by [casey](https://github.com/casey)) - Document using `env -S` ([#2038](https://github.com/casey/just/pull/2038) by [casey](https://github.com/casey)) - Update line continuation documentation ([#1998](https://github.com/casey/just/pull/1998) by [laniakea64](https://github.com/laniakea64)) - Add example using GNU parallel to run tasks in concurrently ([#1915](https://github.com/casey/just/pull/1915) by [amarao](https://github.com/amarao)) - Placate clippy: use `clone_into` ([#2037](https://github.com/casey/just/pull/2037) by [casey](https://github.com/casey)) - Use --command-color when printing shebang recipe commands ([#1911](https://github.com/casey/just/pull/1911) by [avi-cenna](https://github.com/avi-cenna)) - Document how to use watchexec to re-run recipes when files change ([#2036](https://github.com/casey/just/pull/2036) by [casey](https://github.com/casey)) - Update VS Code extensions in readme ([#2034](https://github.com/casey/just/pull/2034) by [casey](https://github.com/casey)) - Add rust:just repology package table to readme ([#2032](https://github.com/casey/just/pull/2032) by [casey](https://github.com/casey)) [1.26.0](https://github.com/casey/just/releases/tag/1.26.0) - 2024-05-13 ------------------------------------------------------------------------ ### Added - Add --no-aliases to hide aliases in --list ([#1961](https://github.com/casey/just/pull/1961) by [WJehee](https://github.com/WJehee)) - Add -E as alias for --dotenv-path ([#1910](https://github.com/casey/just/pull/1910) by [amarao](https://github.com/amarao)) ### Misc - Update softprops/action-gh-release ([#2029](https://github.com/casey/just/pull/2029) by [app/dependabot](https://github.com/app/dependabot)) - Update dependencies ([#1999](https://github.com/casey/just/pull/1999) by [neunenak](https://github.com/neunenak)) - Bump peaceiris/actions-gh-pages to version 4 ([#2005](https://github.com/casey/just/pull/2005) by [app/dependabot](https://github.com/app/dependabot)) - Clarify that janus operates on public justfiles only ([#2021](https://github.com/casey/just/pull/2021) by [casey](https://github.com/casey)) - Fix Error::TmpdirIo error message ([#1987](https://github.com/casey/just/pull/1987) by [casey](https://github.com/casey)) - Update softprops/action-gh-release ([#1973](https://github.com/casey/just/pull/1973) by [app/dependabot](https://github.com/app/dependabot)) - Rename `delete` example recipe to `delete-all` ([#1966](https://github.com/casey/just/pull/1966) by [aarmn](https://github.com/aarmn)) - Update softprops/action-gh-release ([#1954](https://github.com/casey/just/pull/1954) by [app/dependabot](https://github.com/app/dependabot)) - Fix function name typo ([#1953](https://github.com/casey/just/pull/1953) by [racerole](https://github.com/racerole)) [1.25.2](https://github.com/casey/just/releases/tag/1.25.2) - 2024-03-10 ------------------------------------------------------------------------ - Unpin ctrlc ([#1951](https://github.com/casey/just/pull/1951) by [casey](https://github.com/casey)) [1.25.1](https://github.com/casey/just/releases/tag/1.25.1) - 2024-03-09 ------------------------------------------------------------------------ ### Misc - Pin ctrlc to version 3.1.1 ([#1945](https://github.com/casey/just/pull/1945) by [casey](https://github.com/casey)) - Fix AArch64 release build error ([#1942](https://github.com/casey/just/pull/1942) by [casey](https://github.com/casey)) [1.25.0](https://github.com/casey/just/releases/tag/1.25.0) - 2024-03-07 ------------------------------------------------------------------------ ### Added - Add `blake3` and `blake3_file` functions ([#1860](https://github.com/casey/just/pull/1860) by [tgross35](https://github.com/tgross35)) ### Misc - Fix readme typo ([#1936](https://github.com/casey/just/pull/1936) by [Justintime50](https://github.com/Justintime50)) - Use unwrap_or_default ([#1928](https://github.com/casey/just/pull/1928) by [casey](https://github.com/casey)) - Set codegen-units to 1 reduce release binary size ([#1920](https://github.com/casey/just/pull/1920) by [amarao](https://github.com/amarao)) - Document openSUSE package ([#1918](https://github.com/casey/just/pull/1918) by [sfalken](https://github.com/sfalken)) - Fix install.sh shellcheck warnings ([#1912](https://github.com/casey/just/pull/1912) by [tgross35](https://github.com/tgross35)) [1.24.0](https://github.com/casey/just/releases/tag/1.24.0) - 2024-02-11 ------------------------------------------------------------------------ ### Added - Support recipe paths containing `::` in Bash completion script ([#1863](https://github.com/casey/just/pull/1863) by [crdx](https://github.com/crdx)) - Add function to canonicalize paths ([#1859](https://github.com/casey/just/pull/1859) by [casey](https://github.com/casey)) ### Misc - Document installing just on Github Actions in readme ([#1867](https://github.com/casey/just/pull/1867) by [cclauss](https://github.com/cclauss)) - Use unlikely-to-be-set variable name in env tests ([#1882](https://github.com/casey/just/pull/1882) by [casey](https://github.com/casey)) - Skip write_error test if running as root ([#1881](https://github.com/casey/just/pull/1881) by [casey](https://github.com/casey)) - Convert run_shebang into integration test ([#1880](https://github.com/casey/just/pull/1880) by [casey](https://github.com/casey)) - Install mdbook with cargo in CI workflow ([#1877](https://github.com/casey/just/pull/1877) by [casey](https://github.com/casey)) - Remove deprecated actions-rs/toolchain ([#1874](https://github.com/casey/just/pull/1874) by [cclauss](https://github.com/cclauss)) - Fix Gentoo package link ([#1875](https://github.com/casey/just/pull/1875) by [vozbu](https://github.com/vozbu)) - Fix typos found by codespell ([#1872](https://github.com/casey/just/pull/1872) by [cclauss](https://github.com/cclauss)) - Replace deprecated set-output command in Github Actions workflows ([#1869](https://github.com/casey/just/pull/1869) by [cclauss](https://github.com/cclauss)) - Update `actions/checkout` and `softprops/action-gh-release` ([#1871](https://github.com/casey/just/pull/1871) by [app/dependabot](https://github.com/app/dependabot)) - Keep GitHub Actions up to date with Dependabot ([#1868](https://github.com/casey/just/pull/1868) by [cclauss](https://github.com/cclauss)) - Add contrib directory ([#1870](https://github.com/casey/just/pull/1870) by [casey](https://github.com/casey)) - Fix install script ([#1844](https://github.com/casey/just/pull/1844) by [casey](https://github.com/casey)) [1.23.0](https://github.com/casey/just/releases/tag/1.23.0) - 2024-01-12 ------------------------------------------------------------------------ ### Added - Allow setting custom confirm prompt ([#1834](https://github.com/casey/just/pull/1834) by [CramBL](https://github.com/CramBL)) - Add `set quiet` and `[no-quiet]` ([#1704](https://github.com/casey/just/pull/1704) by [dharrigan](https://github.com/dharrigan)) - Add `just_pid` function ([#1833](https://github.com/casey/just/pull/1833) by [Swordelf2](https://github.com/Swordelf2)) - Add functions to return XDG base directories ([#1822](https://github.com/casey/just/pull/1822) by [tgross35](https://github.com/tgross35)) - Add `--no-deps` to skip running recipe dependencies ([#1819](https://github.com/casey/just/pull/1819) by [ngharrington](https://github.com/ngharrington)) ### Fixed - Run imports in working directory of importer ([#1817](https://github.com/casey/just/pull/1817) by [casey](https://github.com/casey)) ### Misc - Include completion scripts in releases ([#1837](https://github.com/casey/just/pull/1837) by [casey](https://github.com/casey)) - Tweak readme table formatting ([#1836](https://github.com/casey/just/pull/1836) by [casey](https://github.com/casey)) - Don't abbreviate just in README ([#1831](https://github.com/casey/just/pull/1831) by [thled](https://github.com/thled)) - Ignore [private] recipes in just --list ([#1816](https://github.com/casey/just/pull/1816) by [crdx](https://github.com/crdx)) - Add a dash to tempdir prefix ([#1828](https://github.com/casey/just/pull/1828) by [casey](https://github.com/casey)) [1.22.1](https://github.com/casey/just/releases/tag/1.22.1) - 2024-01-08 ------------------------------------------------------------------------ ### Fixed - Don't conflate recipes with the same name in different modules ([#1825](https://github.com/casey/just/pull/1825) by [casey](https://github.com/casey)) ### Misc - Clarify that UUID is version 4 ([#1821](https://github.com/casey/just/pull/1821) by [tgross35](https://github.com/tgross35)) - Make sigil stripping from recipe lines less incomprehensible ([#1812](https://github.com/casey/just/pull/1812) by [casey](https://github.com/casey)) - Refactor invalid path argument check ([#1811](https://github.com/casey/just/pull/1811) by [casey](https://github.com/casey)) [1.22.0](https://github.com/casey/just/releases/tag/1.22.0) - 2023-12-31 ------------------------------------------------------------------------ ### Added - Recipes can be invoked with path syntax ([#1809](https://github.com/casey/just/pull/1809) by [casey](https://github.com/casey)) - Add `--format` and `--initialize` as aliases for `--fmt` and `--init` ([#1802](https://github.com/casey/just/pull/1802) by [casey](https://github.com/casey)) ### Misc - Move table of contents pointer to right ([#1806](https://github.com/casey/just/pull/1806) by [casey](https://github.com/casey)) [1.21.0](https://github.com/casey/just/releases/tag/1.21.0) - 2023-12-29 ------------------------------------------------------------------------ ### Added - Optional modules and imports ([#1797](https://github.com/casey/just/pull/1797) by [casey](https://github.com/casey)) - Print submodule recipes in --summary ([#1794](https://github.com/casey/just/pull/1794) by [casey](https://github.com/casey)) ### Misc - Use box-drawing characters in error messages ([#1798](https://github.com/casey/just/pull/1798) by [casey](https://github.com/casey)) - Use Self ([#1795](https://github.com/casey/just/pull/1795) by [casey](https://github.com/casey)) [1.20.0](https://github.com/casey/just/releases/tag/1.20.0) - 2023-12-28 ------------------------------------------------------------------------ ### Added - Allow mod statements with path to source file ([#1786](https://github.com/casey/just/pull/1786) by [casey](https://github.com/casey)) ### Changed - Expand tilde in import and module paths ([#1792](https://github.com/casey/just/pull/1792) by [casey](https://github.com/casey)) - Override imported recipes ([#1790](https://github.com/casey/just/pull/1790) by [casey](https://github.com/casey)) - Run recipes with working directory set to submodule directory ([#1788](https://github.com/casey/just/pull/1788) by [casey](https://github.com/casey)) ### Misc - Document import override behavior ([#1791](https://github.com/casey/just/pull/1791) by [casey](https://github.com/casey)) - Document submodule working directory ([#1789](https://github.com/casey/just/pull/1789) by [casey](https://github.com/casey)) [1.19.0](https://github.com/casey/just/releases/tag/1.19.0) - 2023-12-27 ------------------------------------------------------------------------ ### Added - Add modules ([#1782](https://github.com/casey/just/pull/1782) by [casey](https://github.com/casey)) [1.18.1](https://github.com/casey/just/releases/tag/1.18.1) - 2023-12-24 ------------------------------------------------------------------------ ### Added - Display a descriptive error for `!include` directives ([#1779](https://github.com/casey/just/pull/1779) by [casey](https://github.com/casey)) [1.18.0](https://github.com/casey/just/releases/tag/1.18.0) - 2023-12-24 ------------------------------------------------------------------------ ### Added - Stabilize `!include path` as `import 'path'` ([#1771](https://github.com/casey/just/pull/1771) by [casey](https://github.com/casey)) ### Misc - Tweak readme ([#1775](https://github.com/casey/just/pull/1775) by [casey](https://github.com/casey)) [1.17.0](https://github.com/casey/just/releases/tag/1.17.0) - 2023-12-20 ------------------------------------------------------------------------ ### Added - Add `[confirm]` attribute ([#1723](https://github.com/casey/just/pull/1723) by [Hwatwasthat](https://github.com/Hwatwasthat)) ### Changed - Don't default to included recipes ([#1740](https://github.com/casey/just/pull/1740) by [casey](https://github.com/casey)) ### Fixed - Pass justfile path to default chooser ([#1759](https://github.com/casey/just/pull/1759) by [Qeole](https://github.com/Qeole)) - Pass `--unstable` and `--color always` to default chooser ([#1758](https://github.com/casey/just/pull/1758) by [Qeole](https://github.com/Qeole)) ### Misc - Update Gentoo package repository ([#1757](https://github.com/casey/just/pull/1757) by [paul-jewell](https://github.com/paul-jewell)) - Fix readme header level ([#1752](https://github.com/casey/just/pull/1752) by [laniakea64](https://github.com/laniakea64)) - Document line continuations ([#1751](https://github.com/casey/just/pull/1751) by [laniakea64](https://github.com/laniakea64)) - List included recipes in load order ([#1745](https://github.com/casey/just/pull/1745) by [casey](https://github.com/casey)) - Fix build badge in zh readme ([#1743](https://github.com/casey/just/pull/1743) by [chenrui333](https://github.com/chenrui333)) - Rename Justfile::first → Justfile::default ([#1741](https://github.com/casey/just/pull/1741) by [casey](https://github.com/casey)) - Add file paths to error messages ([#1737](https://github.com/casey/just/pull/1737) by [casey](https://github.com/casey)) - Move !include processing into compiler ([#1618](https://github.com/casey/just/pull/1618) by [neunenak](https://github.com/neunenak)) - Update Arch Linux package URL in readme ([#1733](https://github.com/casey/just/pull/1733) by [felixonmars](https://github.com/felixonmars)) - Clarify that aliases can only be used on the command line ([#1726](https://github.com/casey/just/pull/1726) by [laniakea64](https://github.com/laniakea64)) - Remove VALID_ALIAS_ATTRIBUTES array ([#1731](https://github.com/casey/just/pull/1731) by [casey](https://github.com/casey)) - Fix justfile search link in Chinese docs ([#1730](https://github.com/casey/just/pull/1730) by [oluceps](https://github.com/oluceps)) - Add example of Windows shebang handling ([#1709](https://github.com/casey/just/pull/1709) by [pfmoore](https://github.com/pfmoore)) - Fix CI ([#1728](https://github.com/casey/just/pull/1728) by [casey](https://github.com/casey)) [1.16.0](https://github.com/casey/just/releases/tag/1.16.0) - 2023-11-08 ------------------------------------------------------------------------ ### Added - Add ARMv6 release target ([#1715](https://github.com/casey/just/pull/1715) by [ragazenta](https://github.com/ragazenta)) - Add `semver_matches` function ([#1713](https://github.com/casey/just/pull/1713) by [t3hmrman](https://github.com/t3hmrman)) - Add `dotenv-filename` and `dotenv-path` settings ([#1692](https://github.com/casey/just/pull/1692) by [ltfourrier](https://github.com/ltfourrier)) - Allow setting echoed recipe line color ([#1670](https://github.com/casey/just/pull/1670) by [avi-cenna](https://github.com/avi-cenna)) ### Fixed - Fix Fish completion script ([#1710](https://github.com/casey/just/pull/1710) by [l4zygreed](https://github.com/l4zygreed)) ### Misc - Fix readme typo ([#1717](https://github.com/casey/just/pull/1717) by [barraponto](https://github.com/barraponto)) - Clean up error display ([#1699](https://github.com/casey/just/pull/1699) by [nyurik](https://github.com/nyurik)) - Misc fixes ([#1700](https://github.com/casey/just/pull/1700) by [nyurik](https://github.com/nyurik)) - Fix readme build badge ([#1697](https://github.com/casey/just/pull/1697) by [casey](https://github.com/casey)) - Fix set tempdir grammar ([#1695](https://github.com/casey/just/pull/1695) by [casey](https://github.com/casey)) - Add version to attributes ([#1694](https://github.com/casey/just/pull/1694) by [JoeyTeng](https://github.com/JoeyTeng)) - Update README.md ([#1691](https://github.com/casey/just/pull/1691) by [laniakea64](https://github.com/laniakea64)) [1.15.0](https://github.com/casey/just/releases/tag/1.15.0) - 2023-10-09 ------------------------------------------------------------------------ ### Added - Add Nushell completion script ([#1571](https://github.com/casey/just/pull/1571) by [presidento](https://github.com/presidento)) - Allow unstable features to be enabled with environment variable ([#1588](https://github.com/casey/just/pull/1588) by [neunenak](https://github.com/neunenak)) - Add num_cpus() function ([#1568](https://github.com/casey/just/pull/1568) by [schultetwin1](https://github.com/schultetwin1)) - Allow escaping newlines ([#1551](https://github.com/casey/just/pull/1551) by [ids1024](https://github.com/ids1024)) - Stabilize JSON dump format ([#1633](https://github.com/casey/just/pull/1633) by [casey](https://github.com/casey)) - Add env() function ([#1613](https://github.com/casey/just/pull/1613) by [kykyi](https://github.com/kykyi)) ### Changed - Allow selecting multiple recipes with default chooser ([#1547](https://github.com/casey/just/pull/1547) by [fzdwx](https://github.com/fzdwx)) ### Misc - Don't recommend `vim-polyglot` in readme ([#1644](https://github.com/casey/just/pull/1644) by [laniakea64](https://github.com/laniakea64)) - Note Micro support in readme ([#1316](https://github.com/casey/just/pull/1316) by [tomodachi94](https://github.com/tomodachi94)) - Update Indentation Documentation ([#1600](https://github.com/casey/just/pull/1600) by [GinoMan](https://github.com/GinoMan)) - Fix triple-quoted string example in readme ([#1620](https://github.com/casey/just/pull/1620) by [avi-cenna](https://github.com/avi-cenna)) - README fix: the -d in `mktemp -d` is required to created folders. ([#1688](https://github.com/casey/just/pull/1688) by [gl-yziquel](https://github.com/gl-yziquel)) - Placate clippy ([#1689](https://github.com/casey/just/pull/1689) by [casey](https://github.com/casey)) - Fix README typos ([#1660](https://github.com/casey/just/pull/1660) by [akuhnregnier](https://github.com/akuhnregnier)) - Document Windows Package Manager install instructions ([#1656](https://github.com/casey/just/pull/1656) by [casey](https://github.com/casey)) - Test unpaired escaped carriage return error ([#1650](https://github.com/casey/just/pull/1650) by [casey](https://github.com/casey)) - Avoid grep aliases in bash completions ([#1622](https://github.com/casey/just/pull/1622) by [BojanStipic](https://github.com/BojanStipic)) - Clarify [unix] attribute in readme ([#1619](https://github.com/casey/just/pull/1619) by [neunenak](https://github.com/neunenak)) - Add descriptions to fish recipe completions ([#1578](https://github.com/casey/just/pull/1578) by [patricksjackson](https://github.com/patricksjackson)) - Add better documentation for --dump and --fmt ([#1603](https://github.com/casey/just/pull/1603) by [neunenak](https://github.com/neunenak)) - Cleanup ([#1566](https://github.com/casey/just/pull/1566) by [nyurik](https://github.com/nyurik)) - Document Helix editor support in readme ([#1604](https://github.com/casey/just/pull/1604) by [kenden](https://github.com/kenden)) [1.14.0](https://github.com/casey/just/releases/tag/1.14.0) - 2023-06-02 ------------------------------------------------------------------------ ### Changed - Use `just --show` in default chooser ([#1539](https://github.com/casey/just/pull/1539) by [fzdwx](https://github.com/fzdwx)) ### Misc - Fix justfile search link ([#1607](https://github.com/casey/just/pull/1607) by [jbaber](https://github.com/jbaber)) - Ignore clippy::let_underscore_untyped ([#1609](https://github.com/casey/just/pull/1609) by [casey](https://github.com/casey)) - Link to private recipes section in readme ([#1542](https://github.com/casey/just/pull/1542) by [quad](https://github.com/quad)) - Update README to reflect new attribute syntax ([#1538](https://github.com/casey/just/pull/1538) by [neunenak](https://github.com/neunenak)) - Allow multiple attributes on one line ([#1537](https://github.com/casey/just/pull/1537) by [neunenak](https://github.com/neunenak)) - Analyze and Compiler tweaks ([#1534](https://github.com/casey/just/pull/1534) by [neunenak](https://github.com/neunenak)) - Downgrade to TLS 1.2 in install script ([#1536](https://github.com/casey/just/pull/1536) by [casey](https://github.com/casey)) [1.13.0](https://github.com/casey/just/releases/tag/1.13.0) - 2023-01-24 ------------------------------------------------------------------------ ### Added - Add -n as a short flag for --for dry-run ([#1524](https://github.com/casey/just/pull/1524) by [maiha](https://github.com/maiha)) - Add invocation_directory_native() ([#1507](https://github.com/casey/just/pull/1507) by [casey](https://github.com/casey)) ### Changed - Ignore additional search path arguments ([#1528](https://github.com/casey/just/pull/1528) by [neunenak](https://github.com/neunenak)) - Only print fallback message when verbose ([#1510](https://github.com/casey/just/pull/1510) by [casey](https://github.com/casey)) - Print format diff to stdout ([#1506](https://github.com/casey/just/pull/1506) by [casey](https://github.com/casey)) ### Fixed - Test passing dot as argument between justfiles ([#1530](https://github.com/casey/just/pull/1530) by [casey](https://github.com/casey)) - Fix install script default directory ([#1525](https://github.com/casey/just/pull/1525) by [casey](https://github.com/casey)) ### Misc - Note that justfiles are order-insensitive ([#1529](https://github.com/casey/just/pull/1529) by [casey](https://github.com/casey)) - Borrow Ast in Analyser ([#1527](https://github.com/casey/just/pull/1527) by [neunenak](https://github.com/neunenak)) - Ignore chooser tests ([#1513](https://github.com/casey/just/pull/1513) by [casey](https://github.com/casey)) - Put default setting values in backticks ([#1512](https://github.com/casey/just/pull/1512) by [s1ck](https://github.com/s1ck)) - Use lowercase boolean literals in readme ([#1511](https://github.com/casey/just/pull/1511) by [s1ck](https://github.com/s1ck)) - Document invocation_directory_native() ([#1508](https://github.com/casey/just/pull/1508) by [casey](https://github.com/casey)) - Fix interrupt tests ([#1505](https://github.com/casey/just/pull/1505) by [casey](https://github.com/casey)) [1.12.0](https://github.com/casey/just/releases/tag/1.12.0) - 2023-01-12 ------------------------------------------------------------------------ ### Added - Add `!include` directives ([#1470](https://github.com/casey/just/pull/1470) by [neunenak](https://github.com/neunenak)) ### Changed - Allow matching search path arguments ([#1475](https://github.com/casey/just/pull/1475) by [neunenak](https://github.com/neunenak)) - Allow recipe parameters to shadow variables ([#1480](https://github.com/casey/just/pull/1480) by [casey](https://github.com/casey)) ### Misc - Remove --unstable from fallback example in readme ([#1502](https://github.com/casey/just/pull/1502) by [casey](https://github.com/casey)) - Specify minimum rust version ([#1496](https://github.com/casey/just/pull/1496) by [benmoss](https://github.com/benmoss)) - Note that install.sh may fail on GitHub actions ([#1499](https://github.com/casey/just/pull/1499) by [casey](https://github.com/casey)) - Fix readme typo ([#1489](https://github.com/casey/just/pull/1489) by [auberisky](https://github.com/auberisky)) - Update install script and readmes to use tls v1.3 ([#1481](https://github.com/casey/just/pull/1481) by [casey](https://github.com/casey)) - Re-enable install.sh test on CI([#1478](https://github.com/casey/just/pull/1478) by [casey](https://github.com/casey)) - Don't test install.sh on CI ([#1477](https://github.com/casey/just/pull/1477) by [casey](https://github.com/casey)) - Update Chinese translation of readme ([#1476](https://github.com/casey/just/pull/1476) by [hustcer](https://github.com/hustcer)) - Fix install.sh for Windows ([#1474](https://github.com/casey/just/pull/1474) by [bloodearnest](https://github.com/bloodearnest)) [1.11.0](https://github.com/casey/just/releases/tag/1.11.0) - 2023-01-03 ------------------------------------------------------------------------ ### Added - Stabilize fallback ([#1471](https://github.com/casey/just/pull/1471) by [casey](https://github.com/casey)) ### Misc - Update Sublime syntax instructions ([#1455](https://github.com/casey/just/pull/1455) by [nk9](https://github.com/nk9)) [1.10.0](https://github.com/casey/just/releases/tag/1.10.0) - 2023-01-01 ------------------------------------------------------------------------ ### Added - Allow private attribute on aliases ([#1434](https://github.com/casey/just/pull/1434) by [neunenak](https://github.com/neunenak)) ### Changed - Suppress --fmt --check diff if --quiet is passed ([#1457](https://github.com/casey/just/pull/1457) by [casey](https://github.com/casey)) ### Fixed - Format exported variadic parameters correctly ([#1451](https://github.com/casey/just/pull/1451) by [casey](https://github.com/casey)) ### Misc - Fix section title grammar ([#1466](https://github.com/casey/just/pull/1466) by [brettcannon](https://github.com/brettcannon)) - Give pages job write permissions([#1464](https://github.com/casey/just/pull/1464) by [jsoref](https://github.com/jsoref)) - Fix spelling ([#1463](https://github.com/casey/just/pull/1463) by [jsoref](https://github.com/jsoref)) - Merge imports ([#1462](https://github.com/casey/just/pull/1462) by [casey](https://github.com/casey)) - Add instructions for taiki-e/install-action ([#1459](https://github.com/casey/just/pull/1459) by [azzamsa](https://github.com/azzamsa)) - Differentiate between shell and nushell example ([#1427](https://github.com/casey/just/pull/1427) by [Dialga](https://github.com/Dialga)) - Link regex docs in readme ([#1454](https://github.com/casey/just/pull/1454) by [casey](https://github.com/casey)) - Linkify changelog PRs and usernames ([#1440](https://github.com/casey/just/pull/1440) by [nk9](https://github.com/nk9)) - Eliminate lazy_static ([#1442](https://github.com/casey/just/pull/1442) by [camsteffen](https://github.com/camsteffen)) - Add attributes to sublime syntax file ([#1452](https://github.com/casey/just/pull/1452) by [crdx](https://github.com/crdx)) - Fix homepage style ([#1453](https://github.com/casey/just/pull/1453) by [casey](https://github.com/casey)) - Linkify homepage letters ([#1448](https://github.com/casey/just/pull/1448) by [nk9](https://github.com/nk9)) - Use `just` in readme codeblocks ([#1447](https://github.com/casey/just/pull/1447) by [nicochatzi](https://github.com/nicochatzi)) - Update MSRV in readme ([#1446](https://github.com/casey/just/pull/1446) by [casey](https://github.com/casey)) - Merge CI workflows ([#1444](https://github.com/casey/just/pull/1444) by [casey](https://github.com/casey)) - Use dotenvy instead of dotenv ([#1443](https://github.com/casey/just/pull/1443) by [mike-burns](https://github.com/mike-burns)) - Update Chinese translation of readme ([#1428](https://github.com/casey/just/pull/1428) by [hustcer](https://github.com/hustcer)) [1.9.0](https://github.com/casey/just/releases/tag/1.9.0) - 2022-11-25 ---------------------------------------------------------------------- ### Breaking Changes to Unstable Features - Change `fallback` setting default to false ([#1425](https://github.com/casey/just/pull/1425) by [casey](https://github.com/casey)) ### Added - Hide recipes with `[private]` attribute ([#1422](https://github.com/casey/just/pull/1422) by [casey](https://github.com/casey)) - Add replace_regex function ([#1393](https://github.com/casey/just/pull/1393) by [miles170](https://github.com/miles170)) - Add [no-cd] attribute ([#1400](https://github.com/casey/just/pull/1400) by [casey](https://github.com/casey)) ### Changed - Omit shebang lines on Windows ([#1417](https://github.com/casey/just/pull/1417) by [casey](https://github.com/casey)) ### Misc - Placate clippy ([#1423](https://github.com/casey/just/pull/1423) by [casey](https://github.com/casey)) - Make include_shebang_line clearer ([#1418](https://github.com/casey/just/pull/1418) by [casey](https://github.com/casey)) - Use more secure cURL options in install.sh ([#1416](https://github.com/casey/just/pull/1416) by [casey](https://github.com/casey)) - Document how shebang recipes are executed ([#1412](https://github.com/casey/just/pull/1412) by [casey](https://github.com/casey)) - Fix typo: regec → regex ([#1409](https://github.com/casey/just/pull/1409) by [casey](https://github.com/casey)) - Use powershell.exe instead of pwsh.exe in readme ([#1394](https://github.com/casey/just/pull/1394) by [asdf8dfafjk](https://github.com/asdf8dfafjk)) - Expand alternatives and prior art in readme ([#1401](https://github.com/casey/just/pull/1401) by [casey](https://github.com/casey)) - Split up CI workflow ([#1399](https://github.com/casey/just/pull/1399) by [casey](https://github.com/casey)) [1.8.0](https://github.com/casey/just/releases/tag/1.8.0) - 2022-11-02 ---------------------------------------------------------------------- ### Added - Add OS Configuration Attributes ([#1387](https://github.com/casey/just/pull/1387) by [casey](https://github.com/casey)) ### Misc - Link to sclu1034/vscode-just in readme ([#1396](https://github.com/casey/just/pull/1396) by [casey](https://github.com/casey)) [1.7.0](https://github.com/casey/just/releases/tag/1.7.0) - 2022-10-26 ---------------------------------------------------------------------- ### Breaking Changes to Unstable Features - Make `fallback` setting default to true ([#1384](https://github.com/casey/just/pull/1384) by [casey](https://github.com/casey)) ### Added - Add more case-conversion functions ([#1383](https://github.com/casey/just/pull/1383) by [gVirtu](https://github.com/gVirtu)) - Add `tempdir` setting ([#1369](https://github.com/casey/just/pull/1369) by [dmatos2012](https://github.com/dmatos2012)) - Add [no-exit-message] recipe annotation ([#1354](https://github.com/casey/just/pull/1354) by [gokhanettin](https://github.com/gokhanettin)) - Add `capitalize(s)` function ([#1375](https://github.com/casey/just/pull/1375) by [femnad](https://github.com/femnad)) ### Misc - Credit contributors in changelog ([#1385](https://github.com/casey/just/pull/1385) by [casey](https://github.com/casey)) - Update asdf just plugin repository ([#1380](https://github.com/casey/just/pull/1380) by [kachick](https://github.com/kachick)) - Prepend commit messages with `- ` in changelog ([#1379](https://github.com/casey/just/pull/1379) by [casey](https://github.com/casey)) - Fail publish if `master` is found in README.md ([#1378](https://github.com/casey/just/pull/1378) by [casey](https://github.com/casey)) - Use for loop in capitalize implementation ([#1377](https://github.com/casey/just/pull/1377) by [casey](https://github.com/casey)) [1.6.0](https://github.com/casey/just/releases/tag/1.6.0) - 2022-10-19 ---------------------------------------------------------------------- ### Breaking Changes to Unstable Features - Require `set fallback := true` to enable recipe fallback ([#1368](https://github.com/casey/just/pull/1368) by [casey](https://github.com/casey)) ### Changed - Allow fallback with search directory ([#1348](https://github.com/casey/just/pull/1348) by [casey](https://github.com/casey)) ### Added - Don't evaluate comments ([#1358](https://github.com/casey/just/pull/1358) by [casey](https://github.com/casey)) - Add skip-comments setting ([#1333](https://github.com/casey/just/pull/1333) by [neunenak](https://github.com/neunenak)) - Allow bash completion to complete tasks in other directories ([#1303](https://github.com/casey/just/pull/1303) by [jpbochi](https://github.com/jpbochi)) ### Misc - Restore www/CNAME ([#1364](https://github.com/casey/just/pull/1364) by [casey](https://github.com/casey)) - Improve book config ([#1363](https://github.com/casey/just/pull/1363) by [casey](https://github.com/casey)) - Add kitchen sink justfile to test syntax highlighting ([#1362](https://github.com/casey/just/pull/1362) by [nk9](https://github.com/nk9)) - Note version in which absolute path construction was added ([#1361](https://github.com/casey/just/pull/1361) by [casey](https://github.com/casey)) - Inline setup and cleanup functions in completion script test ([#1352](https://github.com/casey/just/pull/1352) by [casey](https://github.com/casey)) [1.5.0](https://github.com/casey/just/releases/tag/1.5.0) - 2022-9-11 --------------------------------------------------------------------- ### Changed - Allow constructing absolute paths with `/` operator ([#1320](https://github.com/casey/just/pull/1320) by [erikkrieg](https://github.com/erikkrieg)) ### Misc - Allow fewer lints ([#1340](https://github.com/casey/just/pull/1340) by [casey](https://github.com/casey)) - Fix issues reported by nightly clippy ([#1336](https://github.com/casey/just/pull/1336) by [neunenak](https://github.com/neunenak)) - Refactor run.rs ([#1335](https://github.com/casey/just/pull/1335) by [neunenak](https://github.com/neunenak)) - Allow comments on same line as settings ([#1339](https://github.com/casey/just/pull/1339) by [casey](https://github.com/casey)) - Fix justfile env shebang on Linux ([#1330](https://github.com/casey/just/pull/1330) by [casey](https://github.com/casey)) - Update Chinese translation of README.md ([#1325](https://github.com/casey/just/pull/1325) by [hustcer](https://github.com/hustcer)) - Add additional settings to grammar ([#1321](https://github.com/casey/just/pull/1321) by [psibi](https://github.com/psibi)) - Add an example of using a variable in a recipe parameter ([#1311](https://github.com/casey/just/pull/1311) by [papertigers](https://github.com/papertigers)) [1.4.0](https://github.com/casey/just/releases/tag/1.4.0) - 2022-8-08 --------------------------------------------------------------------- ### Fixed - Fix shell setting precedence ([#1306](https://github.com/casey/just/pull/1306) by [casey](https://github.com/casey)) ### Misc - Don't hardcode homebrew prefix ([#1295](https://github.com/casey/just/pull/1295) by [casey](https://github.com/casey)) - Exclude files from cargo package ([#1283](https://github.com/casey/just/pull/1283) by [casey](https://github.com/casey)) - Add usage note to default list recipe ([#1296](https://github.com/casey/just/pull/1296) by [jpbochi](https://github.com/jpbochi)) - Add MPR/Prebuilt-MPR installation instructions to README.md ([#1280](https://github.com/casey/just/pull/1280) by [hwittenborn](https://github.com/hwittenborn)) - Add make and makesure to readme ([#1299](https://github.com/casey/just/pull/1299) by [casey](https://github.com/casey)) - Document how to configure zsh completions on MacOS ([#1285](https://github.com/casey/just/pull/1285) by [nk9](https://github.com/nk9)) - Convert package table to HTML ([#1291](https://github.com/casey/just/pull/1291) by [casey](https://github.com/casey)) [1.3.0](https://github.com/casey/just/releases/tag/1.3.0) - 2022-7-25 --------------------------------------------------------------------- ### Added - Add `/` operator ([#1237](https://github.com/casey/just/pull/1237) by [casey](https://github.com/casey)) ### Fixed - Fix multibyte codepoint crash ([#1243](https://github.com/casey/just/pull/1243) by [casey](https://github.com/casey)) ### Misc - Update just-install reference on README.md ([#1275](https://github.com/casey/just/pull/1275) by [0xradical](https://github.com/0xradical)) - Split Recipe::run into Recipe::{run_shebang,run_linewise} ([#1270](https://github.com/casey/just/pull/1270) by [casey](https://github.com/casey)) - Add asdf package to readme([#1264](https://github.com/casey/just/pull/1264) by [jaacko-torus](https://github.com/jaacko-torus)) - Add mdbook deps for build-book recipe ([#1259](https://github.com/casey/just/pull/1259) by [TopherIsSwell](https://github.com/TopherIsSwell)) - Fix typo: argumant -> argument ([#1257](https://github.com/casey/just/pull/1257) by [kianmeng](https://github.com/kianmeng)) - Improve error message if `if` is missing the `else` ([#1252](https://github.com/casey/just/pull/1252) by [nk9](https://github.com/nk9)) - Explain how to pass arguments of a command to a dependency ([#1254](https://github.com/casey/just/pull/1254) by [heavelock](https://github.com/heavelock)) - Update Chinese translation of README.md ([#1253](https://github.com/casey/just/pull/1253) by [hustcer](https://github.com/hustcer)) - Improvements to Sublime syntax file ([#1250](https://github.com/casey/just/pull/1250) by [nk9](https://github.com/nk9)) - Prevent unbounded recursion when parsing expressions ([#1248](https://github.com/casey/just/pull/1248) by [evanrichter](https://github.com/evanrichter)) - Publish to snap store ([#1245](https://github.com/casey/just/pull/1245) by [casey](https://github.com/casey)) - Restore fuzz test harness ([#1246](https://github.com/casey/just/pull/1246) by [evanrichter](https://github.com/evanrichter)) - Add just-install to README file ([#1241](https://github.com/casey/just/pull/1241) by [brombal](https://github.com/brombal)) - Fix dead readme link ([#1240](https://github.com/casey/just/pull/1240) by [wdroz](https://github.com/wdroz)) - Do `use super::*;` instead of `use crate::common::*;` ([#1239](https://github.com/casey/just/pull/1239) by [casey](https://github.com/casey)) - Fix readme punctuation ([#1235](https://github.com/casey/just/pull/1235) by [casey](https://github.com/casey)) - Add argument splitting section to readme ([#1230](https://github.com/casey/just/pull/1230) by [casey](https://github.com/casey)) - Add notes about environment variables to readme ([#1229](https://github.com/casey/just/pull/1229) by [casey](https://github.com/casey)) - Fix book links ([#1227](https://github.com/casey/just/pull/1227) by [casey](https://github.com/casey)) - Add nushell README.md ([#1224](https://github.com/casey/just/pull/1224) by [hustcer](https://github.com/hustcer)) - Use absolute links in readme ([#1223](https://github.com/casey/just/pull/1223) by [casey](https://github.com/casey)) - Copy changelog into manual ([#1222](https://github.com/casey/just/pull/1222) by [casey](https://github.com/casey)) - Translate Chinese manual introduction and title ([#1220](https://github.com/casey/just/pull/1220) by [hustcer](https://github.com/hustcer)) - Build Chinese language user manual ([#1219](https://github.com/casey/just/pull/1219) by [casey](https://github.com/casey)) - Update Chinese translation of README.md ([#1218](https://github.com/casey/just/pull/1218) by [hustcer](https://github.com/hustcer)) - Translate all of README.md into Chinese ([#1217](https://github.com/casey/just/pull/1217) by [hustcer](https://github.com/hustcer)) - Translate all of features in README into Chinese ([#1215](https://github.com/casey/just/pull/1215) by [hustcer](https://github.com/hustcer)) - Make link to examples directory absolute ([#1213](https://github.com/casey/just/pull/1213) by [casey](https://github.com/casey)) - Translate part of features in README into Chinese ([#1211](https://github.com/casey/just/pull/1211) by [hustcer](https://github.com/hustcer)) - Add JetBrains IDE plugin to readme ([#1209](https://github.com/casey/just/pull/1209) by [linux-china](https://github.com/linux-china)) - Translate features chapter of readme to Chinese ([#1208](https://github.com/casey/just/pull/1208) by [hustcer](https://github.com/hustcer)) [1.2.0](https://github.com/casey/just/releases/tag/1.2.0) - 2022-5-31 --------------------------------------------------------------------- ### Added - Add `windows-shell` setting ([#1198](https://github.com/casey/just/pull/1198) by [casey](https://github.com/casey)) - SHA-256 and UUID functions ([#1170](https://github.com/casey/just/pull/1170) by [mbodmer](https://github.com/mbodmer)) ### Misc - Translate editor support and quick start to Chinese ([#1206](https://github.com/casey/just/pull/1206) by [hustcer](https://github.com/hustcer)) - Translate first section of readme into Chinese ([#1205](https://github.com/casey/just/pull/1205) by [hustcer](https://github.com/hustcer)) - Fix a bunch of typos ([#1204](https://github.com/casey/just/pull/1204) by [casey](https://github.com/casey)) - Remove cargo-limit usage from justfile ([#1199](https://github.com/casey/just/pull/1199) by [casey](https://github.com/casey)) - Add nix package manager install instructions ([#1194](https://github.com/casey/just/pull/1194) by [risingBirdSong](https://github.com/risingBirdSong)) - Fix broken link in readme ([#1183](https://github.com/casey/just/pull/1183) by [Vlad-Shcherbina](https://github.com/Vlad-Shcherbina)) - Add screenshot to manual ([#1181](https://github.com/casey/just/pull/1181) by [casey](https://github.com/casey)) - Style homepage ([#1180](https://github.com/casey/just/pull/1180) by [casey](https://github.com/casey)) - Center readme ([#1178](https://github.com/casey/just/pull/1178) by [casey](https://github.com/casey)) - Style and add links to homepage ([#1177](https://github.com/casey/just/pull/1177) by [casey](https://github.com/casey)) - Fix readme badge links ([#1176](https://github.com/casey/just/pull/1176) by [casey](https://github.com/casey)) - Generate book from readme ([#1155](https://github.com/casey/just/pull/1155) by [casey](https://github.com/casey)) [1.1.3](https://github.com/casey/just/releases/tag/1.1.3) - 2022-5-3 -------------------------------------------------------------------- ### Fixed - Skip duplicate recipe arguments ([#1174](https://github.com/casey/just/pull/1174) by [casey](https://github.com/casey)) ### Misc - Fix install script ([#1172](https://github.com/casey/just/pull/1172) by [casey](https://github.com/casey)) - Document that `invocation_directory()` returns an absolute path ([#1162](https://github.com/casey/just/pull/1162) by [casey](https://github.com/casey)) - Fix absolute_path documentation ([#1160](https://github.com/casey/just/pull/1160) by [casey](https://github.com/casey)) - Add cross-platform justfile example ([#1152](https://github.com/casey/just/pull/1152) by [presidento](https://github.com/presidento)) [1.1.2](https://github.com/casey/just/releases/tag/1.1.2) - 2022-3-30 --------------------------------------------------------------------- ### Misc - Document indentation rules ([#1142](https://github.com/casey/just/pull/1142) by [casey](https://github.com/casey)) - Remove stale link from readme ([#1141](https://github.com/casey/just/pull/1141) by [casey](https://github.com/casey)) ### Unstable - Search for missing recipes in parent directory justfiles ([#1149](https://github.com/casey/just/pull/1149) by [casey](https://github.com/casey)) [1.1.1](https://github.com/casey/just/releases/tag/1.1.1) - 2022-3-22 --------------------------------------------------------------------- ### Misc - Build MacOS ARM release binaries ([#1138](https://github.com/casey/just/pull/1138) by [casey](https://github.com/casey)) - Upgrade Windows Actions runners to windows-latest ([#1137](https://github.com/casey/just/pull/1137) by [casey](https://github.com/casey)) [1.1.0](https://github.com/casey/just/releases/tag/1.1.0) - 2022-3-10 --------------------------------------------------------------------- ### Added - Add `error()` function ([#1118](https://github.com/casey/just/pull/1118) by [chamons](https://github.com/chamons)) - Add `absolute_path` function ([#1121](https://github.com/casey/just/pull/1121) by [Laura7089](https://github.com/Laura7089)) [1.0.1](https://github.com/casey/just/releases/tag/1.0.1) - 2022-2-28 --------------------------------------------------------------------- ### Fixed - Make path_exists() relative to current directory ([#1122](https://github.com/casey/just/pull/1122) by [casey](https://github.com/casey)) ### Misc - Detail environment variable usage in readme ([#1086](https://github.com/casey/just/pull/1086) by [kenden](https://github.com/kenden)) - Format --init justfile ([#1116](https://github.com/casey/just/pull/1116) by [TheLocehiliosan](https://github.com/TheLocehiliosan)) - Add hint for Node.js script compatibility ([#1113](https://github.com/casey/just/pull/1113) by [casey](https://github.com/casey)) [1.0.0](https://github.com/casey/just/releases/tag/1.0.0) - 2022-2-22 --------------------------------------------------------------------- ### Added - Add path_exists() function ([#1106](https://github.com/casey/just/pull/1106) by [heavelock](https://github.com/heavelock)) ### Misc - Note that `pipefail` isn't normally set ([#1108](https://github.com/casey/just/pull/1108) by [casey](https://github.com/casey)) [0.11.2](https://github.com/casey/just/releases/tag/0.11.2) - 2022-2-15 ----------------------------------------------------------------------- ### Misc - Fix dotenv-load documentation ([#1104](https://github.com/casey/just/pull/1104) by [casey](https://github.com/casey)) - Fixup broken release package script ([#1100](https://github.com/casey/just/pull/1100) by [lutostag](https://github.com/lutostag)) [0.11.1](https://github.com/casey/just/releases/tag/0.11.1) - 2022-2-14 ----------------------------------------------------------------------- ### Added - Allow duplicate recipes ([#1095](https://github.com/casey/just/pull/1095) by [lutostag](https://github.com/lutostag)) ### Misc - Add arrow pointing to table of contents button ([#1096](https://github.com/casey/just/pull/1096) by [casey](https://github.com/casey)) - Improve readme ([#1093](https://github.com/casey/just/pull/1093) by [halostatue](https://github.com/halostatue)) - Remove asciidoc readme ([#1092](https://github.com/casey/just/pull/1092) by [casey](https://github.com/casey)) - Convert README.adoc to markdown ([#1091](https://github.com/casey/just/pull/1091) by [casey](https://github.com/casey)) - Add choco package to README ([#1090](https://github.com/casey/just/pull/1090) by [michidk](https://github.com/michidk)) [0.11.0](https://github.com/casey/just/releases/tag/0.11.0) - 2022-2-3 ---------------------------------------------------------------------- ### Breaking - Change dotenv-load default to false ([#1082](https://github.com/casey/just/pull/1082) by [casey](https://github.com/casey)) [0.10.7](https://github.com/casey/just/releases/tag/0.10.7) - 2022-1-30 ----------------------------------------------------------------------- ### Misc - Don't run tests in release workflow ([#1080](https://github.com/casey/just/pull/1080) by [casey](https://github.com/casey)) - Fix windows chooser invocation error message test ([#1079](https://github.com/casey/just/pull/1079) by [casey](https://github.com/casey)) - Remove call to sed in justfile ([#1078](https://github.com/casey/just/pull/1078) by [casey](https://github.com/casey)) [0.10.6](https://github.com/casey/just/releases/tag/0.10.6) - 2022-1-29 ----------------------------------------------------------------------- ### Added - Add windows-powershell setting ([#1057](https://github.com/casey/just/pull/1057) by [michidk](https://github.com/michidk)) ### Changed - Allow using `-` and `@` in any order ([#1063](https://github.com/casey/just/pull/1063) by [casey](https://github.com/casey)) ### Misc - Use `Context` suffix for snafu error contexts ([#1068](https://github.com/casey/just/pull/1068) by [casey](https://github.com/casey)) - Upgrade snafu to 0.7 ([#1067](https://github.com/casey/just/pull/1067) by [shepmaster](https://github.com/shepmaster)) - Mention "$@" in the README ([#1064](https://github.com/casey/just/pull/1064) by [mpdude](https://github.com/mpdude)) - Note how to use PowerShell with CLI in readme ([#1056](https://github.com/casey/just/pull/1056) by [michidk](https://github.com/michidk)) - Link to cheatsheet from readme ([#1053](https://github.com/casey/just/pull/1053) by [casey](https://github.com/casey)) - Link to Homebrew installation docs in readme ([#1049](https://github.com/casey/just/pull/1049) by [michidk](https://github.com/michidk)) - Workflow tweaks ([#1045](https://github.com/casey/just/pull/1045) by [casey](https://github.com/casey)) - Push to correct origin in publish recipe ([#1044](https://github.com/casey/just/pull/1044) by [casey](https://github.com/casey)) [0.10.5](https://github.com/casey/just/releases/tag/0.10.5) - 2021-12-4 ----------------------------------------------------------------------- ### Changed - Use musl libc for ARM binaries ([#1037](https://github.com/casey/just/pull/1037) by [casey](https://github.com/casey)) ### Misc - Make completions work with Bash alias ([#1035](https://github.com/casey/just/pull/1035) by [kurtbuilds](https://github.com/kurtbuilds)) - Run tests on PRs ([#1040](https://github.com/casey/just/pull/1040) by [casey](https://github.com/casey)) - Improve GitHub Actions workflow triggers ([#1033](https://github.com/casey/just/pull/1033) by [casey](https://github.com/casey)) - Publish from GitHub master branch instead of local master ([#1032](https://github.com/casey/just/pull/1032) by [casey](https://github.com/casey)) [0.10.4](https://github.com/casey/just/releases/tag/0.10.4) - 2021-11-21 ------------------------------------------------------------------------ ### Added - Add `--dump-format json` ([#992](https://github.com/casey/just/pull/992) by [casey](https://github.com/casey)) - Add `quote(s)` function for escaping strings ([#1022](https://github.com/casey/just/pull/1022) by [casey](https://github.com/casey)) - fmt: check formatting with `--check` ([#1001](https://github.com/casey/just/pull/1001) by [hdhoang](https://github.com/hdhoang)) ### Misc - Refactor github actions ([#1028](https://github.com/casey/just/pull/1028) by [casey](https://github.com/casey)) - Fix readme formatting ([#1030](https://github.com/casey/just/pull/1030) by [soenkehahn](https://github.com/soenkehahn)) - Use ps1 extension for pwsh shebangs ([#1027](https://github.com/casey/just/pull/1027) by [dmringo](https://github.com/dmringo)) - Ignore leading byte order mark in source files ([#1021](https://github.com/casey/just/pull/1021) by [casey](https://github.com/casey)) - Add color to `just --fmt --check` diff ([#1015](https://github.com/casey/just/pull/1015) by [casey](https://github.com/casey)) [0.10.3](https://github.com/casey/just/releases/tag/0.10.3) - 2021-10-30 ------------------------------------------------------------------------ ### Added - Add `trim_end(s)` and `trim_start(s)` functions ([#999](https://github.com/casey/just/pull/999) by [casey](https://github.com/casey)) - Add more string manipulation functions ([#998](https://github.com/casey/just/pull/998) by [casey](https://github.com/casey)) ### Changed - Make `join` accept two or more arguments ([#1000](https://github.com/casey/just/pull/1000) by [casey](https://github.com/casey)) ### Misc - Add alternatives and prior art section to readme ([#1008](https://github.com/casey/just/pull/1008) by [casey](https://github.com/casey)) - Fix readme `make`'s not correctly displayed ([#1007](https://github.com/casey/just/pull/1007) by [peter50216](https://github.com/peter50216)) - Document the default recipe ([#1006](https://github.com/casey/just/pull/1006) by [casey](https://github.com/casey)) - Document creating user justfile recipe aliases ([#1005](https://github.com/casey/just/pull/1005) by [casey](https://github.com/casey)) - Fix readme typo ([#1004](https://github.com/casey/just/pull/1004) by [0xflotus](https://github.com/0xflotus)) - Add packaging status table to readme ([#1003](https://github.com/casey/just/pull/1003) by [casey](https://github.com/casey)) - Reword `sh` not found error messages ([#1002](https://github.com/casey/just/pull/1002) by [hdhoang](https://github.com/hdhoang)) - Only pass +crt-static to cargo build ([#997](https://github.com/casey/just/pull/997) by [casey](https://github.com/casey)) - Stop using tabs in justfile in editorconfig ([#996](https://github.com/casey/just/pull/996) by [casey](https://github.com/casey)) - Use consistent rustflags formatting ([#994](https://github.com/casey/just/pull/994) by [casey](https://github.com/casey)) - Use `cargo build` instead of `cargo rustc` ([#993](https://github.com/casey/just/pull/993) by [casey](https://github.com/casey)) - Don't skip variables in variable iterator ([#991](https://github.com/casey/just/pull/991) by [casey](https://github.com/casey)) - Remove deprecated equals error ([#985](https://github.com/casey/just/pull/985) by [casey](https://github.com/casey)) [0.10.2](https://github.com/casey/just/releases/tag/0.10.2) - 2021-9-26 ----------------------------------------------------------------------- ### Added - Implement regular expression match conditionals ([#970](https://github.com/casey/just/pull/970) by [casey](https://github.com/casey)) ### Misc - Add detailed instructions for installing prebuilt binaries ([#978](https://github.com/casey/just/pull/978) by [casey](https://github.com/casey)) - Improve readme package table formatting ([#977](https://github.com/casey/just/pull/977) by [casey](https://github.com/casey)) - Add conda package to README ([#976](https://github.com/casey/just/pull/976) by [kellpossible](https://github.com/kellpossible)) - Change MSRV to 1.46.0 ([#968](https://github.com/casey/just/pull/968) by [casey](https://github.com/casey)) - Use stable rustfmt instead of nightly ([#967](https://github.com/casey/just/pull/967) by [casey](https://github.com/casey)) - Fix readme typo: FOO → WORLD ([#964](https://github.com/casey/just/pull/964) by [casey](https://github.com/casey)) - Reword Emacs section in readme ([#962](https://github.com/casey/just/pull/962) by [casey](https://github.com/casey)) - Mention justl mode for Emacs ([#961](https://github.com/casey/just/pull/961) by [psibi](https://github.com/psibi)) [0.10.1](https://github.com/casey/just/releases/tag/0.10.1) - 2021-8-27 ----------------------------------------------------------------------- ### Added - Add flags for specifying name and path to environment file ([#941](https://github.com/casey/just/pull/941) by [Celeo](https://github.com/Celeo)) ### Misc - Fix error message tests for Alpine Linux ([#956](https://github.com/casey/just/pull/956) by [casey](https://github.com/casey)) - Bump `target` version to 2.0 ([#957](https://github.com/casey/just/pull/957) by [casey](https://github.com/casey)) - Mention `tree-sitter-just` in readme ([#951](https://github.com/casey/just/pull/951) by [casey](https://github.com/casey)) - Document release RSS feed in readme ([#950](https://github.com/casey/just/pull/950) by [casey](https://github.com/casey)) - Add installation instructions for Gentoo Linux ([#946](https://github.com/casey/just/pull/946) by [dm9pZCAq](https://github.com/dm9pZCAq)) - Make GitHub Actions instructions more prominent ([#944](https://github.com/casey/just/pull/944) by [casey](https://github.com/casey)) - Wrap `--help` text to terminal width ([#940](https://github.com/casey/just/pull/940) by [casey](https://github.com/casey)) - Add `.justfile` to sublime syntax file_extensions ([#938](https://github.com/casey/just/pull/938) by [casey](https://github.com/casey)) - Suggest using `~/.global.justfile` instead of `~/.justfile` ([#937](https://github.com/casey/just/pull/937) by [casey](https://github.com/casey)) - Update man page ([#935](https://github.com/casey/just/pull/935) by [casey](https://github.com/casey)) [0.10.0](https://github.com/casey/just/releases/tag/0.10.0) - 2021-8-2 ---------------------------------------------------------------------- ### Changed - Warn if `.env` file is loaded in `dotenv-load` isn't explicitly set ([#925](https://github.com/casey/just/pull/925) by [casey](https://github.com/casey)) ### Added - Add `--changelog` subcommand ([#932](https://github.com/casey/just/pull/932) by [casey](https://github.com/casey)) - Support `.justfile` as an alternative to `justfile` ([#931](https://github.com/casey/just/pull/931) by [casey](https://github.com/casey)) ### Misc - Use cargo-limit for all recipes ([#928](https://github.com/casey/just/pull/928) by [casey](https://github.com/casey)) - Fix colors ([#927](https://github.com/casey/just/pull/927) by [casey](https://github.com/casey)) - Use ColorDisplay trait to print objects to the terminal ([#926](https://github.com/casey/just/pull/926) by [casey](https://github.com/casey)) - Deduplicate recipe parsing ([#923](https://github.com/casey/just/pull/923) by [casey](https://github.com/casey)) - Move subcommand functions into Subcommand ([#918](https://github.com/casey/just/pull/918) by [casey](https://github.com/casey)) - Check GitHub Actions workflow with actionlint ([#921](https://github.com/casey/just/pull/921) by [casey](https://github.com/casey)) - Add loader and refactor errors ([#917](https://github.com/casey/just/pull/917) by [casey](https://github.com/casey)) - Rename: Module → Ast ([#915](https://github.com/casey/just/pull/915) by [casey](https://github.com/casey)) [0.9.9](https://github.com/casey/just/releases/tag/0.9.9) - 2021-7-22 --------------------------------------------------------------------- ### Added - Add subsequent dependencies ([#820](https://github.com/casey/just/pull/820) by [casey](https://github.com/casey)) - Implement `else if` chaining ([#910](https://github.com/casey/just/pull/910) by [casey](https://github.com/casey)) ### Fixed - Fix circular variable dependency error message ([#909](https://github.com/casey/just/pull/909) by [casey](https://github.com/casey)) ### Misc - Improve readme ([#904](https://github.com/casey/just/pull/904) by [mtsknn](https://github.com/mtsknn)) - Add screenshot to readme ([#911](https://github.com/casey/just/pull/911) by [casey](https://github.com/casey)) - Add install instructions for Fedora Linux ([#898](https://github.com/casey/just/pull/898) by [olivierlemasle](https://github.com/olivierlemasle)) - Fix readme typos ([#903](https://github.com/casey/just/pull/903) by [rokf](https://github.com/rokf)) - Actually fix release tagging and publish changelog with releases ([#901](https://github.com/casey/just/pull/901) by [casey](https://github.com/casey)) - Fix broken prerelease tagging ([#900](https://github.com/casey/just/pull/900) by [casey](https://github.com/casey)) - Use string value for ref-type check ([#897](https://github.com/casey/just/pull/897) by [casey](https://github.com/casey)) [0.9.8](https://github.com/casey/just/releases/tag/0.9.8) - 2021-7-3 -------------------------------------------------------------------- ### Misc - Fix changelog formatting ([#894](https://github.com/casey/just/pull/894) by [casey](https://github.com/casey)) - Only run install script on CI for non-releases ([#895](https://github.com/casey/just/pull/895) by [casey](https://github.com/casey)) [0.9.7](https://github.com/casey/just/releases/tag/0.9.7) - 2021-7-3 -------------------------------------------------------------------- ### Added - Add string manipulation functions ([#888](https://github.com/casey/just/pull/888) by [terror](https://github.com/terror)) ### Misc - Remove test-utilities crate ([#892](https://github.com/casey/just/pull/892) by [casey](https://github.com/casey)) - Remove outdated note in `Cargo.toml` ([#891](https://github.com/casey/just/pull/891) by [casey](https://github.com/casey)) - Link to GitHub release pages in changelog ([#886](https://github.com/casey/just/pull/886) by [casey](https://github.com/casey)) [0.9.6](https://github.com/casey/just/releases/tag/0.9.6) - 2021-6-24 --------------------------------------------------------------------- ### Added - Add `clean` function for simplifying paths ([#883](https://github.com/casey/just/pull/883) by [casey](https://github.com/casey)) - Add `join` function for joining paths ([#882](https://github.com/casey/just/pull/882) by [casey](https://github.com/casey)) - Add path manipulation functions ([#872](https://github.com/casey/just/pull/872) by [TonioGela](https://github.com/TonioGela)) ### Misc - Add `file_extensions` to Sublime syntax file ([#878](https://github.com/casey/just/pull/878) by [Frederick888](https://github.com/Frederick888)) - Document path manipulation functions in readme ([#877](https://github.com/casey/just/pull/877) by [casey](https://github.com/casey)) [0.9.5](https://github.com/casey/just/releases/tag/0.9.5) - 2021-6-12 --------------------------------------------------------------------- ### Added - Add `--unstable` flag ([#869](https://github.com/casey/just/pull/869) by [casey](https://github.com/casey)) - Add Sublime Text syntax file ([#864](https://github.com/casey/just/pull/864) by [casey](https://github.com/casey)) - Add `--fmt` subcommand ([#837](https://github.com/casey/just/pull/837) by [vglfr](https://github.com/vglfr)) ### Misc - Mention doniogela.dev/just/ in readme ([#866](https://github.com/casey/just/pull/866) by [casey](https://github.com/casey)) - Mention that vim-just is now available from vim-polyglot ([#865](https://github.com/casey/just/pull/865) by [casey](https://github.com/casey)) - Mention `--list-heading` newline behavior ([#860](https://github.com/casey/just/pull/860) by [casey](https://github.com/casey)) - Check for `rg` in `bin/forbid` ([#859](https://github.com/casey/just/pull/859) by [casey](https://github.com/casey)) - Document that variables are not exported to backticks in the same scope ([#856](https://github.com/casey/just/pull/856) by [casey](https://github.com/casey)) - Remove `dotenv_load` from tests ([#853](https://github.com/casey/just/pull/853) by [casey](https://github.com/casey)) - Remove `v` prefix from version ([#850](https://github.com/casey/just/pull/850) by [casey](https://github.com/casey)) - Improve install script ([#847](https://github.com/casey/just/pull/847) by [casey](https://github.com/casey)) - Move pages assets back to `docs` ([#846](https://github.com/casey/just/pull/846) by [casey](https://github.com/casey)) - Move pages assets to `www` ([#845](https://github.com/casey/just/pull/845) by [casey](https://github.com/casey)) [0.9.4](https://github.com/casey/just/releases/tag/v0.9.4) - 2021-5-27 ---------------------------------------------------------------------- ### Misc - Release `aarch64-unknown-linux-gnu` binaries ([#843](https://github.com/casey/just/pull/843) by [casey](https://github.com/casey)) - Add `$` to non-default parameter grammar ([#839](https://github.com/casey/just/pull/839) by [casey](https://github.com/casey)) - Add `$` to parameter grammar ([#838](https://github.com/casey/just/pull/838) by [NoahTheDuke](https://github.com/NoahTheDuke)) - Fix readme links ([#836](https://github.com/casey/just/pull/836) by [casey](https://github.com/casey)) - Add `vim-just` installation instructions to readme ([#835](https://github.com/casey/just/pull/835) by [casey](https://github.com/casey)) - Refactor shebang handling ([#833](https://github.com/casey/just/pull/833) by [casey](https://github.com/casey)) [0.9.3](https://github.com/casey/just/releases/tag/v0.9.3) - 2021-5-16 ---------------------------------------------------------------------- ### Added - Add shebang support for 'cmd.exe' ([#828](https://github.com/casey/just/pull/828) by [pansila](https://github.com/pansila)) - Add `.exe` to powershell scripts ([#826](https://github.com/casey/just/pull/826) by [sigoden](https://github.com/sigoden)) - Add the `--command` subcommand ([#824](https://github.com/casey/just/pull/824) by [casey](https://github.com/casey)) ### Fixed - Fix bang lexing and placate clippy ([#821](https://github.com/casey/just/pull/821) by [casey](https://github.com/casey)) ### Misc - Fixed missing close apostrophe in GRAMMAR.md ([#830](https://github.com/casey/just/pull/830) by [SOF3](https://github.com/SOF3)) - Make 'else' keyword in grammar ([#829](https://github.com/casey/just/pull/829) by [SOF3](https://github.com/SOF3)) - Add forbid script ([#827](https://github.com/casey/just/pull/827) by [casey](https://github.com/casey)) - Remove `summary` feature ([#823](https://github.com/casey/just/pull/823) by [casey](https://github.com/casey)) - Document that just is now in Arch official repo ([#814](https://github.com/casey/just/pull/814) by [svenstaro](https://github.com/svenstaro)) - Fix changelog years ([#813](https://github.com/casey/just/pull/813) by [casey](https://github.com/casey)) [0.9.2](https://github.com/casey/just/releases/tag/v0.9.2) - 2021-5-02 ---------------------------------------------------------------------- ### Fixed - Pass evaluated arguments as positional arguments ([#810](https://github.com/casey/just/pull/810) by [casey](https://github.com/casey)) [0.9.1](https://github.com/casey/just/releases/tag/v0.9.1) - 2021-4-24 ---------------------------------------------------------------------- ### Added - Change `--eval` to print variable value only ([#806](https://github.com/casey/just/pull/806) by [casey](https://github.com/casey)) - Add `positional-arguments` setting ([#804](https://github.com/casey/just/pull/804) by [casey](https://github.com/casey)) - Allow filtering variables to evaluate ([#795](https://github.com/casey/just/pull/795) by [casey](https://github.com/casey)) ### Changed - Reform and improve string literals ([#793](https://github.com/casey/just/pull/793) by [casey](https://github.com/casey)) - Allow evaluating justfiles with no recipes ([#794](https://github.com/casey/just/pull/794) by [casey](https://github.com/casey)) - Unify string lexing ([#790](https://github.com/casey/just/pull/790) by [casey](https://github.com/casey)) ### Misc - Test multi-line strings in interpolation ([#789](https://github.com/casey/just/pull/789) by [casey](https://github.com/casey)) - Add shell setting examples to README ([#787](https://github.com/casey/just/pull/787) by [casey](https://github.com/casey)) - Disable .env warning for now ([#786](https://github.com/casey/just/pull/786) by [casey](https://github.com/casey)) - Warn if `.env` file loaded and `dotenv-load` unset ([#784](https://github.com/casey/just/pull/784) by [casey](https://github.com/casey)) [0.9.0](https://github.com/casey/just/releases/tag/v0.9.0) - 2021-3-28 ---------------------------------------------------------------------- ### Changed - Turn `=` deprecation warning into a hard error ([#780](https://github.com/casey/just/pull/780) by [casey](https://github.com/casey)) [0.8.7](https://github.com/casey/just/releases/tag/v0.8.7) - 2021-3-28 ---------------------------------------------------------------------- ### Added - Add `dotenv-load` setting ([#778](https://github.com/casey/just/pull/778) by [casey](https://github.com/casey)) ### Misc - Change publish recipe to use stable rust ([#777](https://github.com/casey/just/pull/777) by [casey](https://github.com/casey)) [0.8.6](https://github.com/casey/just/releases/tag/v0.8.6) - 2021-3-28 ---------------------------------------------------------------------- ### Added - Add just_executable() function ([#775](https://github.com/casey/just/pull/775) by [bew](https://github.com/bew)) - Prefix parameters with `$` to export to environment ([#773](https://github.com/casey/just/pull/773) by [casey](https://github.com/casey)) - Add `set export` to export all variables as environment variables ([#767](https://github.com/casey/just/pull/767) by [casey](https://github.com/casey)) ### Changed - Suppress all output to stderr when `--quiet` ([#771](https://github.com/casey/just/pull/771) by [casey](https://github.com/casey)) ### Misc - Improve chooser invocation error message ([#772](https://github.com/casey/just/pull/772) by [casey](https://github.com/casey)) - De-emphasize cmd.exe in readme ([#768](https://github.com/casey/just/pull/768) by [casey](https://github.com/casey)) - Fix warnings ([#770](https://github.com/casey/just/pull/770) by [casey](https://github.com/casey)) [0.8.5](https://github.com/casey/just/releases/tag/v0.8.5) - 2021-3-24 ---------------------------------------------------------------------- ### Added - Allow escaping double braces with `{{{{` ([#765](https://github.com/casey/just/pull/765) by [casey](https://github.com/casey)) ### Misc - Reorganize readme to highlight editor support ([#764](https://github.com/casey/just/pull/764) by [casey](https://github.com/casey)) - Add categories and keywords to Cargo manifest ([#763](https://github.com/casey/just/pull/763) by [casey](https://github.com/casey)) - Fix command output in readme ([#760](https://github.com/casey/just/pull/760) by [vvv](https://github.com/vvv)) - Note Emacs package `just-mode` in readme ([#759](https://github.com/casey/just/pull/759) by [leon-barrett](https://github.com/leon-barrett)) - Note shebang line splitting inconsistency in readme ([#757](https://github.com/casey/just/pull/757) by [casey](https://github.com/casey)) [0.8.4](https://github.com/casey/just/releases/tag/v0.8.4) - 2021-2-9 --------------------------------------------------------------------- ### Added - Add options to control list formatting ([#753](https://github.com/casey/just/pull/753) by [casey](https://github.com/casey)) ### Misc - Document how to change the working directory in a recipe ([#752](https://github.com/casey/just/pull/752) by [casey](https://github.com/casey)) - Implement `Default` for `Table` ([#748](https://github.com/casey/just/pull/748) by [casey](https://github.com/casey)) - Add Alpine Linux package to readme ([#736](https://github.com/casey/just/pull/736) by [jirutka](https://github.com/jirutka)) - Update to actions/cache@v2 ([#742](https://github.com/casey/just/pull/742) by [zyctree](https://github.com/zyctree)) - Add link in readme to GitHub Action ([#729](https://github.com/casey/just/pull/729) by [rossmacarthur](https://github.com/rossmacarthur)) - Add docs for justfile() and justfile_directory() ([#726](https://github.com/casey/just/pull/726) by [rminderhoud](https://github.com/rminderhoud)) - Fix CI ([#727](https://github.com/casey/just/pull/727) by [casey](https://github.com/casey)) - Improve readme ([#725](https://github.com/casey/just/pull/725) by [casey](https://github.com/casey)) - Replace saythanks.io link with malto: link ([#723](https://github.com/casey/just/pull/723) by [casey](https://github.com/casey)) - Update man page to v0.8.3 ([#720](https://github.com/casey/just/pull/720) by [casey](https://github.com/casey)) [0.8.3](https://github.com/casey/just/releases/tag/v0.8.3) - 2020-10-27 ----------------------------------------------------------------------- ### Added - Allow ignoring line endings inside delimiters ([#717](https://github.com/casey/just/pull/717) by [casey](https://github.com/casey)) [0.8.2](https://github.com/casey/just/releases/tag/v0.8.2) - 2020-10-26 ----------------------------------------------------------------------- ### Added - Add conditional expressions ([#714](https://github.com/casey/just/pull/714) by [casey](https://github.com/casey)) ### Fixed - Allow completing variables and recipes after `--set` in zsh completion script ([#697](https://github.com/casey/just/pull/697) by [heyrict](https://github.com/heyrict)) ### Misc - Add Parser::forbid ([#712](https://github.com/casey/just/pull/712) by [casey](https://github.com/casey)) - Automatically track expected tokens while parsing ([#711](https://github.com/casey/just/pull/711) by [casey](https://github.com/casey)) - Document feature flags in Cargo.toml ([#709](https://github.com/casey/just/pull/709) by [casey](https://github.com/casey)) [0.8.1](https://github.com/casey/just/releases/tag/v0.8.1) - 2020-10-15 ----------------------------------------------------------------------- ### Changed - Allow choosing multiple recipes to run ([#700](https://github.com/casey/just/pull/700) by [casey](https://github.com/casey)) - Complete recipes in bash completion script ([#685](https://github.com/casey/just/pull/685) by [vikesh-raj](https://github.com/vikesh-raj)) - Complete recipes names in PowerShell completion script ([#651](https://github.com/casey/just/pull/651) by [Insomniak47](https://github.com/Insomniak47)) ### Misc - Add FreeBSD port to readme ([#705](https://github.com/casey/just/pull/705) by [casey](https://github.com/casey)) - Placate clippy ([#698](https://github.com/casey/just/pull/698) by [casey](https://github.com/casey)) - Fix build fix ([#693](https://github.com/casey/just/pull/693) by [casey](https://github.com/casey)) - Fix readme documentation for ignoring errors ([#692](https://github.com/casey/just/pull/692) by [kenden](https://github.com/kenden)) [0.8.0](https://github.com/casey/just/releases/tag/v0.8.0) - 2020-10-3 ---------------------------------------------------------------------- ### Breaking - Allow suppressing failures with `-` prefix ([#687](https://github.com/casey/just/pull/687) by [iwillspeak](https://github.com/iwillspeak)) ### Misc - Document how to ignore errors with `-` in readme ([#690](https://github.com/casey/just/pull/690) by [casey](https://github.com/casey)) - Install BSD Tar on GitHub Actions to fix CI errors ([#689](https://github.com/casey/just/pull/689) by [casey](https://github.com/casey)) - Move separate quiet config value to verbosity ([#686](https://github.com/casey/just/pull/686) by [Celeo](https://github.com/Celeo)) [0.7.3](https://github.com/casey/just/releases/tag/v0.7.3) - 2020-9-17 ---------------------------------------------------------------------- ### Added - Add the `--choose` subcommand ([#680](https://github.com/casey/just/pull/680) by [casey](https://github.com/casey)) ### Misc - Combine integration tests into single binary ([#679](https://github.com/casey/just/pull/679) by [casey](https://github.com/casey)) - Document `--unsorted` flag in readme ([#672](https://github.com/casey/just/pull/672) by [casey](https://github.com/casey)) [0.7.2](https://github.com/casey/just/releases/tag/v0.7.2) - 2020-8-23 ---------------------------------------------------------------------- ### Added - Add option to print recipes in source order ([#669](https://github.com/casey/just/pull/669) by [casey](https://github.com/casey)) ### Misc - Mention Linux, MacOS and Windows support in readme ([#666](https://github.com/casey/just/pull/666) by [casey](https://github.com/casey)) - Add list highlighting nice features to readme ([#664](https://github.com/casey/just/pull/664) by [casey](https://github.com/casey)) [0.7.1](https://github.com/casey/just/releases/tag/v0.7.1) - 2020-7-19 ---------------------------------------------------------------------- ### Fixed - Search for `.env` file from working directory ([#661](https://github.com/casey/just/pull/661) by [casey](https://github.com/casey)) ### Misc - Move link-time optimization config into `Cargo.toml` ([#658](https://github.com/casey/just/pull/658) by [casey](https://github.com/casey)) [0.7.0](https://github.com/casey/just/releases/tag/v0.7.0) - 2020-7-16 ---------------------------------------------------------------------- ### Breaking - Skip `.env` items which are set in environment ([#656](https://github.com/casey/just/pull/656) by [casey](https://github.com/casey)) ### Misc - Mark tags that start with `v` as releases ([#654](https://github.com/casey/just/pull/654) by [casey](https://github.com/casey)) [0.6.1](https://github.com/casey/just/releases/tag/v0.6.1) - 2020-6-28 ---------------------------------------------------------------------- ### Changed - Only use `cygpath` on shebang if it contains `/` ([#652](https://github.com/casey/just/pull/652) by [casey](https://github.com/casey)) [0.6.0](https://github.com/casey/just/releases/tag/v0.6.0) - 2020-6-18 ---------------------------------------------------------------------- ### Changed - Ignore '@' returned from interpolation evaluation ([#636](https://github.com/casey/just/pull/636) by [rjsberry](https://github.com/rjsberry)) - Strip leading spaces after line continuation ([#635](https://github.com/casey/just/pull/635) by [casey](https://github.com/casey)) ### Added - Add variadic parameters that accept zero or more arguments ([#645](https://github.com/casey/just/pull/645) by [rjsberry](https://github.com/rjsberry)) ### Misc - Clarify variadic parameter default values ([#646](https://github.com/casey/just/pull/646) by [rjsberry](https://github.com/rjsberry)) - Add keybase example justfile ([#640](https://github.com/casey/just/pull/640) by [blaggacao](https://github.com/blaggacao)) - Strip trailing whitespace in `examples/pre-commit.just` ([#644](https://github.com/casey/just/pull/644) by [casey](https://github.com/casey)) - Test that example justfiles successfully parse ([#643](https://github.com/casey/just/pull/643) by [casey](https://github.com/casey)) - Link example justfiles in readme ([#641](https://github.com/casey/just/pull/641) by [casey](https://github.com/casey)) - Add example justfile ([#639](https://github.com/casey/just/pull/639) by [blaggacao](https://github.com/blaggacao)) - Document how to run recipes after another recipe ([#630](https://github.com/casey/just/pull/630) by [casey](https://github.com/casey)) [0.5.11](https://github.com/casey/just/releases/tag/v0.5.11) - 2020-5-23 ------------------------------------------------------------------------ ### Added - Don't load `.env` file when `--no-dotenv` is passed ([#627](https://github.com/casey/just/pull/627) by [casey](https://github.com/casey)) ### Changed - Complete recipe names in fish completion script ([#625](https://github.com/casey/just/pull/625) by [tyehle](https://github.com/tyehle)) - Suggest aliases for unknown recipes ([#624](https://github.com/casey/just/pull/624) by [Celeo](https://github.com/Celeo)) [0.5.10](https://github.com/casey/just/releases/tag/v0.5.10) - 2020-3-18 ------------------------------------------------------------------------ [0.5.9](https://github.com/casey/just/releases/tag/v0.5.9) - 2020-3-18 ---------------------------------------------------------------------- ### Added - Update zsh completion file ([#606](https://github.com/casey/just/pull/606) by [heyrict](https://github.com/heyrict)) - Add `--variables` subcommand that prints variable names ([#608](https://github.com/casey/just/pull/608) by [casey](https://github.com/casey)) - Add github pages site with improved install script ([#597](https://github.com/casey/just/pull/597) by [casey](https://github.com/casey)) ### Fixed - Don't require justfile to print completions ([#596](https://github.com/casey/just/pull/596) by [casey](https://github.com/casey)) ### Misc - Only build for linux on docs.rs ([#611](https://github.com/casey/just/pull/611) by [casey](https://github.com/casey)) - Trim completions and ensure final newline ([#609](https://github.com/casey/just/pull/609) by [casey](https://github.com/casey)) - Trigger build on pushes and pull requests ([#607](https://github.com/casey/just/pull/607) by [casey](https://github.com/casey)) - Document behavior of `@` on shebang recipes ([#602](https://github.com/casey/just/pull/602) by [casey](https://github.com/casey)) - Add `.nojekyll` file to github pages site ([#599](https://github.com/casey/just/pull/599) by [casey](https://github.com/casey)) - Add `:` favicon ([#598](https://github.com/casey/just/pull/598) by [casey](https://github.com/casey)) - Delete old CI configuration and update build badge ([#595](https://github.com/casey/just/pull/595) by [casey](https://github.com/casey)) - Add download count badge to readme ([#594](https://github.com/casey/just/pull/594) by [casey](https://github.com/casey)) - Wrap comments at 80 characters ([#593](https://github.com/casey/just/pull/593) by [casey](https://github.com/casey)) - Use unstable rustfmt configuration options ([#592](https://github.com/casey/just/pull/592) by [casey](https://github.com/casey)) [0.5.8](https://github.com/casey/just/releases/tag/v0.5.8) - 2020-1-28 ---------------------------------------------------------------------- ### Changed - Only use `cygpath` on windows if present ([#586](https://github.com/casey/just/pull/586) by [casey](https://github.com/casey)) ### Misc - Improve comments in justfile ([#588](https://github.com/casey/just/pull/588) by [casey](https://github.com/casey)) - Remove unused dependencies ([#587](https://github.com/casey/just/pull/587) by [casey](https://github.com/casey)) [0.5.7](https://github.com/casey/just/releases/tag/v0.5.7) - 2020-1-28 ---------------------------------------------------------------------- ### Misc - Don't include directories in release archive ([#583](https://github.com/casey/just/pull/583) by [casey](https://github.com/casey)) [0.5.6](https://github.com/casey/just/releases/tag/v0.5.6) - 2020-1-28 ---------------------------------------------------------------------- ### Misc - Build and upload release artifacts from GitHub Actions ([#581](https://github.com/casey/just/pull/581) by [casey](https://github.com/casey)) - List solus package in readme ([#579](https://github.com/casey/just/pull/579) by [casey](https://github.com/casey)) - Expand use of GitHub Actions ([#580](https://github.com/casey/just/pull/580) by [casey](https://github.com/casey)) - Fix readme typo: interpetation -> interpretation ([#578](https://github.com/casey/just/pull/578) by [Plommonsorbet](https://github.com/Plommonsorbet)) [0.5.5](https://github.com/casey/just/releases/tag/v0.5.5) - 2020-1-15 ---------------------------------------------------------------------- ### Added - Generate shell completion scripts with `--completions` ([#572](https://github.com/casey/just/pull/572) by [casey](https://github.com/casey)) ### Misc - Check long lines and FIXME/TODO on CI ([#575](https://github.com/casey/just/pull/575) by [casey](https://github.com/casey)) - Add additional continuous integration checks ([#574](https://github.com/casey/just/pull/574) by [casey](https://github.com/casey)) [0.5.4](https://github.com/casey/just/releases/tag/v0.5.4) - 2019-12-25 ----------------------------------------------------------------------- ### Added - Add `justfile_directory()` and `justfile()` ([#569](https://github.com/casey/just/pull/569) by [casey](https://github.com/casey)) ### Misc - Add table of package managers that include just to readme ([#568](https://github.com/casey/just/pull/568) by [casey](https://github.com/casey)) - Remove yaourt AUR helper from readme ([#567](https://github.com/casey/just/pull/567) by [ky0n](https://github.com/ky0n)) - Fix regression in error message color printing ([#566](https://github.com/casey/just/pull/566) by [casey](https://github.com/casey)) - Reform indentation handling ([#565](https://github.com/casey/just/pull/565) by [casey](https://github.com/casey)) - Update Cargo.lock with new version ([#564](https://github.com/casey/just/pull/564) by [casey](https://github.com/casey)) [0.5.3](https://github.com/casey/just/releases/tag/v0.5.3) - 2019-12-11 ----------------------------------------------------------------------- ### Misc - Assert that lexer advances over entire input ([#560](https://github.com/casey/just/pull/560) by [casey](https://github.com/casey)) - Fix typo: `chracter` -> `character` ([#561](https://github.com/casey/just/pull/561) by [casey](https://github.com/casey)) - Improve pre-publish check ([#562](https://github.com/casey/just/pull/562) by [casey](https://github.com/casey)) [0.5.2](https://github.com/casey/just/releases/tag/v0.5.2) - 2019-12-7 ---------------------------------------------------------------------- ### Added - Add flags to set and clear shell arguments ([#551](https://github.com/casey/just/pull/551) by [casey](https://github.com/casey)) - Allow passing arguments to dependencies ([#555](https://github.com/casey/just/pull/555) by [casey](https://github.com/casey)) ### Misc - Un-implement Deref for Table ([#546](https://github.com/casey/just/pull/546) by [casey](https://github.com/casey)) - Resolve recipe dependencies ([#547](https://github.com/casey/just/pull/547) by [casey](https://github.com/casey)) - Resolve alias targets ([#548](https://github.com/casey/just/pull/548) by [casey](https://github.com/casey)) - Remove unnecessary type argument to Alias ([#549](https://github.com/casey/just/pull/549) by [casey](https://github.com/casey)) - Resolve functions ([#550](https://github.com/casey/just/pull/550) by [casey](https://github.com/casey)) - Reform scope and binding ([#556](https://github.com/casey/just/pull/556) by [casey](https://github.com/casey)) [0.5.1](https://github.com/casey/just/releases/tag/v0.5.1) - 2019-11-20 ----------------------------------------------------------------------- ### Added - Add `--init` subcommand ([#541](https://github.com/casey/just/pull/541) by [casey](https://github.com/casey)) ### Changed - Avoid fs::canonicalize ([#539](https://github.com/casey/just/pull/539) by [casey](https://github.com/casey)) ### Misc - Mention `set shell` as alternative to installing `sh` ([#533](https://github.com/casey/just/pull/533) by [casey](https://github.com/casey)) - Refactor Compilation error to contain a Token ([#535](https://github.com/casey/just/pull/535) by [casey](https://github.com/casey)) - Move lexer comment ([#536](https://github.com/casey/just/pull/536) by [casey](https://github.com/casey)) - Add missing `--init` test ([#543](https://github.com/casey/just/pull/543) by [casey](https://github.com/casey)) [0.5.0](https://github.com/casey/just/releases/tag/v0.5.0) - 2019-11-12 ----------------------------------------------------------------------- ### Added - Add `set shell := [...]` to grammar ([#526](https://github.com/casey/just/pull/526) by [casey](https://github.com/casey)) - Add `shell` setting ([#525](https://github.com/casey/just/pull/525) by [casey](https://github.com/casey)) - Document settings in readme ([#527](https://github.com/casey/just/pull/527) by [casey](https://github.com/casey)) ### Changed - Reform positional argument parsing ([#523](https://github.com/casey/just/pull/523) by [casey](https://github.com/casey)) - Highlight echoed recipe lines in bold by default ([#512](https://github.com/casey/just/pull/512) by [casey](https://github.com/casey)) ### Misc - Gargantuan refactor ([#522](https://github.com/casey/just/pull/522) by [casey](https://github.com/casey)) - Move subcommand execution into Subcommand ([#514](https://github.com/casey/just/pull/514) by [casey](https://github.com/casey)) - Move `cd` out of Config::from_matches ([#513](https://github.com/casey/just/pull/513) by [casey](https://github.com/casey)) - Remove now-unnecessary borrow checker appeasement ([#511](https://github.com/casey/just/pull/511) by [casey](https://github.com/casey)) - Reform Parser ([#509](https://github.com/casey/just/pull/509) by [casey](https://github.com/casey)) - Note need to publish with nightly cargo ([#506](https://github.com/casey/just/pull/506) by [casey](https://github.com/casey)) [0.4.5](https://github.com/casey/just/releases/tag/v0.4.5) - 2019-10-31 ----------------------------------------------------------------------- ### User-visible ### Changed - Display alias with `--show NAME` if one exists ([#466](https://github.com/casey/just/pull/466) by [casey](https://github.com/casey)) ### Documented - Document multi-line constructs (for/if/while) ([#453](https://github.com/casey/just/pull/453) by [casey](https://github.com/casey)) - Generate man page with help2man ([#463](https://github.com/casey/just/pull/463) by [casey](https://github.com/casey)) - Add context to deprecation warnings ([#473](https://github.com/casey/just/pull/473) by [casey](https://github.com/casey)) - Improve messages for alias error messages ([#500](https://github.com/casey/just/pull/500) by [casey](https://github.com/casey)) ### Misc ### Cleanup - Update deprecated rust range patterns and clippy config ([#450](https://github.com/casey/just/pull/450) by [light4](https://github.com/light4)) - Make comments in common.rs lowercase ([#470](https://github.com/casey/just/pull/470) by [casey](https://github.com/casey)) - Use `pub(crate)` instead of `pub` ([#471](https://github.com/casey/just/pull/471) by [casey](https://github.com/casey)) - Hide summary functionality behind feature flag ([#472](https://github.com/casey/just/pull/472) by [casey](https://github.com/casey)) - Fix `summary` feature conditional compilation ([#475](https://github.com/casey/just/pull/475) by [casey](https://github.com/casey)) - Allow integration test cases to omit common values ([#480](https://github.com/casey/just/pull/480) by [casey](https://github.com/casey)) - Add `unindent()` for nicer integration test strings ([#481](https://github.com/casey/just/pull/481) by [casey](https://github.com/casey)) - Start pulling argument parsing out of run::run() ([#483](https://github.com/casey/just/pull/483) by [casey](https://github.com/casey)) - Add explicit `Subcommand` enum ([#484](https://github.com/casey/just/pull/484) by [casey](https://github.com/casey)) - Avoid using error code `1` in integration tests ([#486](https://github.com/casey/just/pull/486) by [casey](https://github.com/casey)) - Use more indented strings in integration tests ([#489](https://github.com/casey/just/pull/489) by [casey](https://github.com/casey)) - Refactor `run::run` and Config ([#490](https://github.com/casey/just/pull/490) by [casey](https://github.com/casey)) - Remove `misc.rs` ([#491](https://github.com/casey/just/pull/491) by [casey](https://github.com/casey)) - Remove unused `use` statements ([#497](https://github.com/casey/just/pull/497) by [casey](https://github.com/casey)) - Refactor lexer tests ([#498](https://github.com/casey/just/pull/498) by [casey](https://github.com/casey)) - Use constants instead of literals in arg parser ([#504](https://github.com/casey/just/pull/504) by [casey](https://github.com/casey)) ### Infrastructure - Add repository attribute to Cargo.toml ([#493](https://github.com/casey/just/pull/493) by [SOF3](https://github.com/SOF3)) - Check minimal version compatibility before publishing ([#487](https://github.com/casey/just/pull/487) by [casey](https://github.com/casey)) ### Continuous Integration - Disable FreeBSD builds ([#474](https://github.com/casey/just/pull/474) by [casey](https://github.com/casey)) - Use `bash` as shell for all integration tests ([#479](https://github.com/casey/just/pull/479) by [casey](https://github.com/casey)) - Don't install `dash` on Travis ([#482](https://github.com/casey/just/pull/482) by [casey](https://github.com/casey)) ### Dependencies - Use `tempfile` crate instead of `tempdir` ([#455](https://github.com/casey/just/pull/455) by [NickeZ](https://github.com/NickeZ)) - Bump clap dependency to 2.33.0 ([#458](https://github.com/casey/just/pull/458) by [NickeZ](https://github.com/NickeZ)) - Minimize dependency version requirements ([#461](https://github.com/casey/just/pull/461) by [casey](https://github.com/casey)) - Remove dependency on brev ([#462](https://github.com/casey/just/pull/462) by [casey](https://github.com/casey)) - Update dependencies ([#501](https://github.com/casey/just/pull/501) by [casey](https://github.com/casey)) [0.4.4](https://github.com/casey/just/releases/tag/v0.4.4) - 2019-06-02 ----------------------------------------------------------------------- ### Changed - Ignore file name case while searching for justfile ([#436](https://github.com/casey/just/pull/436) by [shevtsiv](https://github.com/shevtsiv)) ### Added - Display alias target with `--show` ([#443](https://github.com/casey/just/pull/443) by [casey](https://github.com/casey)) [0.4.3](https://github.com/casey/just/releases/tag/v0.4.3) - 2019-05-07 ----------------------------------------------------------------------- ### Changed - Deprecate `=` in assignments, aliases, and exports in favor of `:=` ([#413](https://github.com/casey/just/pull/413) by [casey](https://github.com/casey)) ### Added - Pass stdin handle to backtick process ([#409](https://github.com/casey/just/pull/409) by [casey](https://github.com/casey)) ### Documented - Fix readme command line ([#411](https://github.com/casey/just/pull/411) by [casey](https://github.com/casey)) - Typo: "command equivelant" -> "command equivalent" ([#418](https://github.com/casey/just/pull/418) by [casey](https://github.com/casey)) - Mention Make’s “phony target” workaround in the comparison ([#421](https://github.com/casey/just/pull/421) by [roryokane](https://github.com/roryokane)) - Add Void Linux install instructions to readme ([#423](https://github.com/casey/just/pull/423) by [casey](https://github.com/casey)) ### Cleaned up or Refactored - Remove stray source files ([#408](https://github.com/casey/just/pull/408) by [casey](https://github.com/casey)) - Replace some calls to brev crate ([#410](https://github.com/casey/just/pull/410) by [casey](https://github.com/casey)) - Lexer code deduplication and refactoring ([#414](https://github.com/casey/just/pull/414) by [casey](https://github.com/casey)) - Refactor and rename test macros ([#415](https://github.com/casey/just/pull/415) by [casey](https://github.com/casey)) - Move CompilationErrorKind into separate module ([#416](https://github.com/casey/just/pull/416) by [casey](https://github.com/casey)) - Remove `write_token_error_context` ([#417](https://github.com/casey/just/pull/417) by [casey](https://github.com/casey)) [0.4.2](https://github.com/casey/just/releases/tag/v0.4.2) - 2019-04-12 ----------------------------------------------------------------------- ### Changed - Regex-based lexer replaced with much nicer character-at-a-time lexer ([#406](https://github.com/casey/just/pull/406) by [casey](https://github.com/casey)) [0.4.1](https://github.com/casey/just/releases/tag/v0.4.1) - 2019-04-12 ----------------------------------------------------------------------- ### Changed - Make summary function non-generic ([#404](https://github.com/casey/just/pull/404) by [casey](https://github.com/casey)) [0.4.0](https://github.com/casey/just/releases/tag/v0.4.0) - 2019-04-12 ----------------------------------------------------------------------- ### Added - Add recipe aliases ([#390](https://github.com/casey/just/pull/390) by [ryloric](https://github.com/ryloric)) - Allow arbitrary expressions as default arguments ([#400](https://github.com/casey/just/pull/400) by [casey](https://github.com/casey)) - Add justfile summaries ([#399](https://github.com/casey/just/pull/399) by [casey](https://github.com/casey)) - Allow outer shebang lines so justfiles can be used as scripts ([#393](https://github.com/casey/just/pull/393) by [casey](https://github.com/casey)) - Allow `--justfile` without `--working-directory` ([#392](https://github.com/casey/just/pull/392) by [smonami](https://github.com/smonami)) - Add link to Chinese translation of readme by chinanf-boy ([#377](https://github.com/casey/just/pull/377) by [casey](https://github.com/casey)) ### Changed - Upgrade to Rust 2018 ([#394](https://github.com/casey/just/pull/394) by [casey](https://github.com/casey)) - Format the codebase with rustfmt ([#346](https://github.com/casey/just/pull/346) by [casey](https://github.com/casey)) [0.3.13](https://github.com/casey/just/releases/tag/v0.3.13) - 2018-11-06 ------------------------------------------------------------------------- ### Added - Print recipe signature if missing arguments ([#369](https://github.com/casey/just/pull/369) by [ladysamantha](https://github.com/ladysamantha)) - Add grandiloquent verbosity level that echos shebang recipes ([#348](https://github.com/casey/just/pull/348) by [casey](https://github.com/casey)) - Wait for child processes to finish ([#345](https://github.com/casey/just/pull/345) by [casey](https://github.com/casey)) - Improve invalid escape sequence error messages ([#328](https://github.com/casey/just/pull/328) by [casey](https://github.com/casey)) ### Fixed - Use PutBackN instead of PutBack in parser ([#364](https://github.com/casey/just/pull/364) by [casey](https://github.com/casey)) [0.3.12](https://github.com/casey/just/releases/tag/v0.3.12) - 2018-06-19 ------------------------------------------------------------------------- ### Added - Implemented invocation_directory function ([#323](https://github.com/casey/just/pull/323) by [casey](https://github.com/casey)) [0.3.11](https://github.com/casey/just/releases/tag/v0.3.11) - 2018-05-6 ------------------------------------------------------------------------ ### Fixed - Fixed colors on windows ([#317](https://github.com/casey/just/pull/317) by [casey](https://github.com/casey)) [0.3.10](https://github.com/casey/just/releases/tag/v0.3.10) - 2018-3-19 ------------------------------------------------------------------------ ### Added - Make .env vars available in env_var functions ([#310](https://github.com/casey/just/pull/310) by [casey](https://github.com/casey)) [0.3.8](https://github.com/casey/just/releases/tag/v0.3.8) - 2018-3-5 --------------------------------------------------------------------- ### Added - Add dotenv integration ([#306](https://github.com/casey/just/pull/306) by [casey](https://github.com/casey)) [0.3.7](https://github.com/casey/just/releases/tag/v0.3.7) - 2017-12-11 ----------------------------------------------------------------------- ### Fixed - Fix error if ! appears in comment ([#296](https://github.com/casey/just/pull/296) by [casey](https://github.com/casey)) [0.3.6](https://github.com/casey/just/releases/tag/v0.3.6) - 2017-12-11 ----------------------------------------------------------------------- ### Fixed - Lex CRLF line endings properly ([#292](https://github.com/casey/just/pull/292) by [casey](https://github.com/casey)) [0.3.5](https://github.com/casey/just/releases/tag/v0.3.5) - 2017-12-11 ----------------------------------------------------------------------- ### Added - Align doc-comments in `--list` output ([#273](https://github.com/casey/just/pull/273) by [casey](https://github.com/casey)) - Add `arch()`, `os()`, and `os_family()` functions ([#277](https://github.com/casey/just/pull/277) by [casey](https://github.com/casey)) - Add `env_var(key)` and `env_var_or_default(key, default)` functions ([#280](https://github.com/casey/just/pull/280) by [casey](https://github.com/casey)) [0.3.4](https://github.com/casey/just/releases/tag/v0.3.4) - 2017-10-06 ----------------------------------------------------------------------- ### Added - Do not evaluate backticks in assignments during dry runs ([#253](https://github.com/casey/just/pull/253) by [aoeu](https://github.com/aoeu)) ### Changed - Change license to CC0 going forward ([#270](https://github.com/casey/just/pull/270) by [casey](https://github.com/casey)) [0.3.1](https://github.com/casey/just/releases/tag/v0.3.1) - 2017-10-06 ----------------------------------------------------------------------- ### Added - Started keeping a changelog in CHANGELOG.md ([#220](https://github.com/casey/just/pull/220) by [casey](https://github.com/casey)) - Recipes whose names begin with an underscore will not appear in `--list` or `--summary` ([#229](https://github.com/casey/just/pull/229) by [casey](https://github.com/casey)) just-1.40.0/CONTRIBUTING.md000064400000000000000000000004651046102023000131310ustar 00000000000000Contributing ============ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be licensed as in [LICENSE](LICENSE), without any additional terms or conditions. See [the readme](README.md#contributing) for contribution workflow suggestions. just-1.40.0/Cargo.lock0000644000001114720000000000100100640ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "android-tzdata" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" [[package]] name = "android_system_properties" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ "libc", ] [[package]] name = "ansi_term" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" dependencies = [ "winapi", ] [[package]] name = "anstream" version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "anstyle-parse" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "anstyle-wincon" version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" dependencies = [ "anstyle", "once_cell", "windows-sys 0.59.0", ] [[package]] name = "arrayref" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "blake3" version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "675f87afced0413c9bb02843499dbbd3882a237645883f71a2b59644a6d2f753" dependencies = [ "arrayref", "arrayvec", "cc", "cfg-if", "constant_time_eq", "memmap2", "rayon-core", ] [[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ "generic-array", ] [[package]] name = "bstr" version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0" dependencies = [ "memchr", "regex-automata", "serde", ] [[package]] name = "bumpalo" version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" [[package]] name = "camino" version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" [[package]] name = "cc" version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ "shlex", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" version = "0.4.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "wasm-bindgen", "windows-link", ] [[package]] name = "clap" version = "4.5.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767" dependencies = [ "clap_builder", "clap_derive", ] [[package]] name = "clap_builder" version = "4.5.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863" dependencies = [ "anstream", "anstyle", "clap_lex", "strsim", "terminal_size", ] [[package]] name = "clap_complete" version = "4.5.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5c5508ea23c5366f77e53f5a0070e5a84e51687ec3ef9e0464c86dc8d13ce98" dependencies = [ "clap", ] [[package]] name = "clap_derive" version = "4.5.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed" dependencies = [ "heck", "proc-macro2", "quote", "syn", ] [[package]] name = "clap_lex" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "clap_mangen" version = "0.2.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "724842fa9b144f9b89b3f3d371a89f3455eea660361d13a554f68f8ae5d6c13a" dependencies = [ "clap", "roff", ] [[package]] name = "colorchoice" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" [[package]] name = "constant_time_eq" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" dependencies = [ "libc", ] [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crypto-common" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", "typenum", ] [[package]] name = "ctrlc" version = "3.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90eeab0aa92f3f9b4e87f258c72b139c207d251f9cbc1080a0086b86a8870dd3" dependencies = [ "nix", "windows-sys 0.59.0", ] [[package]] name = "derive-where" version = "1.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "diff" version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", ] [[package]] name = "dirs" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" dependencies = [ "dirs-sys 0.4.1", ] [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ "dirs-sys 0.5.0", ] [[package]] name = "dirs-sys" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", "redox_users 0.4.6", "windows-sys 0.48.0", ] [[package]] name = "dirs-sys" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", "redox_users 0.5.0", "windows-sys 0.59.0", ] [[package]] name = "dotenvy" version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "edit-distance" version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3f497e87b038c09a155dfd169faa5ec940d0644635555ef6bd464ac20e97397" [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "env_home" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "errno" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", "windows-sys 0.59.0", ] [[package]] name = "executable-path" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ebc5a6d89e3c90b84e8f33c8737933dda8f1c106b5415900b38b9d433841478" [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "generic-array" version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", ] [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] name = "getrandom" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" dependencies = [ "cfg-if", "libc", "wasi 0.13.3+wasi-0.2.2", "windows-targets 0.52.6", ] [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "iana-time-zone" version = "0.1.61" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", "windows-core", ] [[package]] name = "iana-time-zone-haiku" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ "cc", ] [[package]] name = "is_executable" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a1b5bad6f9072935961dfbf1cced2f3d129963d091b6f69f007fe04e758ae2" dependencies = [ "winapi", ] [[package]] name = "is_terminal_polyfill" version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "js-sys" version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ "once_cell", "wasm-bindgen", ] [[package]] name = "just" version = "1.40.0" dependencies = [ "ansi_term", "blake3", "camino", "chrono", "clap", "clap_complete", "clap_mangen", "ctrlc", "derive-where", "dirs 6.0.0", "dotenvy", "edit-distance", "executable-path", "heck", "is_executable", "lexiclean", "libc", "num_cpus", "once_cell", "percent-encoding", "pretty_assertions", "rand", "regex", "rustversion", "semver", "serde", "serde_json", "sha2", "shellexpand", "similar", "snafu", "strum", "target", "tempfile", "temptree", "typed-arena", "unicode-width", "uuid", "which", ] [[package]] name = "lexiclean" version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "441225017b106b9f902e97947a6d31e44ebcf274b91bdbfb51e5c477fcd468e5" [[package]] name = "libc" version = "0.2.170" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828" [[package]] name = "libredox" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags", "libc", ] [[package]] name = "linux-raw-sys" version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9c683daf087dc577b7506e9695b3d556a9f3849903fa28186283afd6809e9" [[package]] name = "log" version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memmap2" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f" dependencies = [ "libc", ] [[package]] name = "nix" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ "bitflags", "cfg-if", "cfg_aliases", "libc", ] [[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] [[package]] name = "num_cpus" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ "hermit-abi", "libc", ] [[package]] name = "once_cell" version = "1.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "percent-encoding" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "ppv-lite86" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ "zerocopy", ] [[package]] name = "pretty_assertions" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" dependencies = [ "diff", "yansi", ] [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha", "rand_core", "zerocopy", ] [[package]] name = "rand_chacha" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom 0.3.1", ] [[package]] name = "rayon-core" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] [[package]] name = "redox_users" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" dependencies = [ "getrandom 0.2.15", "libredox", "thiserror 1.0.69", ] [[package]] name = "redox_users" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" dependencies = [ "getrandom 0.2.15", "libredox", "thiserror 2.0.12", ] [[package]] name = "regex" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "roff" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88f8660c1ff60292143c98d08fc6e2f654d722db50410e3f3797d40baaf9d8f3" [[package]] name = "rustix" version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys 0.4.15", "windows-sys 0.59.0", ] [[package]] name = "rustix" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dade4812df5c384711475be5fcd8c162555352945401aed22a35bffeab61f657" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys 0.9.2", "windows-sys 0.59.0", ] [[package]] name = "rustversion" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "semver" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "sha2" version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", "cpufeatures", "digest", ] [[package]] name = "shellexpand" version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da03fa3b94cc19e3ebfc88c4229c49d8f08cdbd1228870a45f0ffdf84988e14b" dependencies = [ "dirs 5.0.1", ] [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "similar" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" dependencies = [ "bstr", "unicode-segmentation", ] [[package]] name = "snafu" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "223891c85e2a29c3fe8fb900c1fae5e69c2e42415e3177752e8718475efa5019" dependencies = [ "snafu-derive", ] [[package]] name = "snafu-derive" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03c3c6b7927ffe7ecaa769ee0e3994da3b8cafc8f444578982c83ecb161af917" dependencies = [ "heck", "proc-macro2", "quote", "syn", ] [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f64def088c51c9510a8579e3c5d67c65349dcf755e5479ad3d010aa6454e2c32" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c77a8c5abcaf0f9ce05d62342b7d298c346515365c36b673df4ebe3ced01fde8" dependencies = [ "heck", "proc-macro2", "quote", "rustversion", "syn", ] [[package]] name = "syn" version = "2.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e8f05f774b2db35bdad5a8237a90be1102669f8ea013fea9777b366d34ab145" [[package]] name = "tempfile" version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c317e0a526ee6120d8dabad239c8dadca62b24b6f168914bbbc8e2fb1f0e567" dependencies = [ "cfg-if", "fastrand", "getrandom 0.3.1", "once_cell", "rustix 1.0.1", "windows-sys 0.59.0", ] [[package]] name = "temptree" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fda94d8251b40088cb769576f436da19ac1d1ae792c97d0afe1cadc890c8630" dependencies = [ "tempfile", ] [[package]] name = "terminal_size" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ "rustix 1.0.1", "windows-sys 0.59.0", ] [[package]] name = "thiserror" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl 1.0.69", ] [[package]] name = "thiserror" version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" dependencies = [ "thiserror-impl 2.0.12", ] [[package]] name = "thiserror-impl" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "thiserror-impl" version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "typed-arena" version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" [[package]] name = "typenum" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "unicode-segmentation" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "unicode-width" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0f540e3240398cce6128b64ba83fdbdd86129c16a3aa1a3a252efd66eb3d587" dependencies = [ "getrandom 0.3.1", ] [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasi" version = "0.13.3+wasi-0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wasm-bindgen" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" dependencies = [ "unicode-ident", ] [[package]] name = "which" version = "7.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2774c861e1f072b3aadc02f8ba886c26ad6321567ecc294c935434cad06f1283" dependencies = [ "either", "env_home", "rustix 0.38.44", "winsafe", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ "windows-targets 0.52.6", ] [[package]] name = "windows-link" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3" [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets 0.52.6", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winsafe" version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" [[package]] name = "wit-bindgen-rt" version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ "bitflags", ] [[package]] name = "yansi" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "zerocopy" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd97444d05a4328b90e75e503a34bad781f14e28a823ad3557f0750df1ebcbc6" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6352c01d0edd5db859a63e2605f4ea3183ddbd15e2c4a9e7d32184df75e4f154" dependencies = [ "proc-macro2", "quote", "syn", ] just-1.40.0/Cargo.toml0000644000000074110000000000100101040ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.74" name = "just" version = "1.40.0" authors = ["Casey Rodarmor "] build = false exclude = [ "/book", "/icon.png", "/screenshot.png", "/www", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "🤖 Just a command runner" homepage = "https://github.com/casey/just" readme = "crates-io-readme.md" keywords = [ "command-line", "task", "runner", "development", "utility", ] categories = [ "command-line-utilities", "development-tools", ] license = "CC0-1.0" repository = "https://github.com/casey/just" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "just" path = "src/lib.rs" doctest = false [[bin]] name = "just" path = "src/main.rs" test = false [[test]] name = "integration" path = "tests/lib.rs" [dependencies.ansi_term] version = "0.12.0" [dependencies.blake3] version = "1.5.0" features = [ "rayon", "mmap", ] [dependencies.camino] version = "1.0.4" [dependencies.chrono] version = "0.4.38" [dependencies.clap] version = "4.0.0" features = [ "derive", "env", "wrap_help", ] [dependencies.clap_complete] version = "4.0.0" [dependencies.clap_mangen] version = "0.2.20" [dependencies.ctrlc] version = "3.1.1" features = ["termination"] [dependencies.derive-where] version = "1.2.7" [dependencies.dirs] version = "6.0.0" [dependencies.dotenvy] version = "0.15" [dependencies.edit-distance] version = "2.0.0" [dependencies.heck] version = "0.5.0" [dependencies.is_executable] version = "1.0.4" [dependencies.lexiclean] version = "0.0.1" [dependencies.libc] version = "0.2.0" [dependencies.num_cpus] version = "1.15.0" [dependencies.once_cell] version = "1.19.0" [dependencies.percent-encoding] version = "2.3.1" [dependencies.rand] version = "0.9.0" [dependencies.regex] version = "1.10.4" [dependencies.rustversion] version = "1.0.18" [dependencies.semver] version = "1.0.20" [dependencies.serde] version = "1.0.130" features = [ "derive", "rc", ] [dependencies.serde_json] version = "1.0.68" [dependencies.sha2] version = "0.10" [dependencies.shellexpand] version = "3.1.0" [dependencies.similar] version = "2.1.0" features = ["unicode"] [dependencies.snafu] version = "0.8.0" [dependencies.strum] version = "0.27.1" features = ["derive"] [dependencies.target] version = "2.0.0" [dependencies.tempfile] version = "3.0.0" [dependencies.typed-arena] version = "2.0.1" [dependencies.unicode-width] version = "0.2.0" [dependencies.uuid] version = "1.0.0" features = ["v4"] [dev-dependencies.executable-path] version = "1.0.0" [dev-dependencies.pretty_assertions] version = "1.0.0" [dev-dependencies.temptree] version = "0.2.0" [dev-dependencies.which] version = "7.0.0" [lints.clippy] arbitrary-source-item-ordering = "deny" enum_glob_use = "allow" needless_pass_by_value = "allow" similar_names = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" too_many_arguments = "allow" too_many_lines = "allow" unnecessary_wraps = "allow" wildcard_imports = "allow" [lints.clippy.all] level = "deny" priority = -1 [lints.clippy.pedantic] level = "deny" priority = -1 [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(fuzzing)"] [profile.release] lto = true codegen-units = 1 just-1.40.0/Cargo.toml.orig000064400000000000000000000047551046102023000135750ustar 00000000000000[package] name = "just" version = "1.40.0" authors = ["Casey Rodarmor "] autotests = false categories = ["command-line-utilities", "development-tools"] description = "🤖 Just a command runner" edition = "2021" exclude = ["/book", "/icon.png", "/screenshot.png", "/www"] homepage = "https://github.com/casey/just" keywords = ["command-line", "task", "runner", "development", "utility"] license = "CC0-1.0" readme = "crates-io-readme.md" repository = "https://github.com/casey/just" rust-version = "1.74" [workspace] members = [".", "crates/*"] [dependencies] ansi_term = "0.12.0" blake3 = { version = "1.5.0", features = ["rayon", "mmap"] } camino = "1.0.4" chrono = "0.4.38" clap = { version = "4.0.0", features = ["derive", "env", "wrap_help"] } clap_complete = "4.0.0" clap_mangen = "0.2.20" ctrlc = { version = "3.1.1", features = ["termination"] } derive-where = "1.2.7" dirs = "6.0.0" dotenvy = "0.15" edit-distance = "2.0.0" heck = "0.5.0" is_executable = "1.0.4" lexiclean = "0.0.1" libc = "0.2.0" num_cpus = "1.15.0" once_cell = "1.19.0" percent-encoding = "2.3.1" rand = "0.9.0" regex = "1.10.4" rustversion = "1.0.18" semver = "1.0.20" serde = { version = "1.0.130", features = ["derive", "rc"] } serde_json = "1.0.68" sha2 = "0.10" shellexpand = "3.1.0" similar = { version = "2.1.0", features = ["unicode"] } snafu = "0.8.0" strum = { version = "0.27.1", features = ["derive"] } target = "2.0.0" tempfile = "3.0.0" typed-arena = "2.0.1" unicode-width = "0.2.0" uuid = { version = "1.0.0", features = ["v4"] } [dev-dependencies] executable-path = "1.0.0" pretty_assertions = "1.0.0" temptree = "0.2.0" which = "7.0.0" [lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(fuzzing)'] } [lints.clippy] all = { level = "deny", priority = -1 } arbitrary-source-item-ordering = "deny" enum_glob_use = "allow" needless_pass_by_value = "allow" pedantic = { level = "deny", priority = -1 } similar_names = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" too_many_arguments = "allow" too_many_lines = "allow" unnecessary_wraps = "allow" wildcard_imports = "allow" [lib] doctest = false [[bin]] path = "src/main.rs" name = "just" test = false # The public documentation is minimal and doesn't change between # platforms, so we only build them for linux on docs.rs to save # their build machines some cycles. [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [profile.release] lto = true codegen-units = 1 [[test]] name = "integration" path = "tests/lib.rs" just-1.40.0/GRAMMAR.md000064400000000000000000000076261046102023000123160ustar 00000000000000justfile grammar ================ Justfiles are processed by a mildly context-sensitive tokenizer and a recursive descent parser. The grammar is LL(k), for an unknown but hopefully reasonable value of k. tokens ------ ``` BACKTICK = `[^`]*` INDENTED_BACKTICK = ```[^(```)]*``` COMMENT = #([^!].*)?$ DEDENT = emitted when indentation decreases EOF = emitted at the end of the file INDENT = emitted when indentation increases LINE = emitted before a recipe line NAME = [a-zA-Z_][a-zA-Z0-9_-]* NEWLINE = \n|\r\n RAW_STRING = '[^']*' INDENTED_RAW_STRING = '''[^(''')]*''' STRING = "[^"]*" # also processes \n \r \t \" \\ escapes INDENTED_STRING = """[^(""")]*""" # also processes \n \r \t \" \\ escapes LINE_PREFIX = @-|-@|@|- TEXT = recipe text, only matches in a recipe body ``` grammar syntax -------------- ``` | alternation () grouping _? option (0 or 1 times) _* repetition (0 or more times) _+ repetition (1 or more times) ``` grammar ------- ``` justfile : item* EOF item : alias | assignment | eol | export | import | module | recipe | set eol : NEWLINE | COMMENT NEWLINE alias : 'alias' NAME ':=' NAME eol assignment : NAME ':=' expression eol export : 'export' assignment set : 'set' setting eol setting : 'allow-duplicate-recipes' boolean? | 'allow-duplicate-variables' boolean? | 'dotenv-filename' ':=' string | 'dotenv-load' boolean? | 'dotenv-path' ':=' string | 'dotenv-required' boolean? | 'export' boolean? | 'fallback' boolean? | 'ignore-comments' boolean? | 'positional-arguments' boolean? | 'script-interpreter' ':=' string_list | 'quiet' boolean? | 'shell' ':=' string_list | 'tempdir' ':=' string | 'unstable' boolean? | 'windows-powershell' boolean? | 'windows-shell' ':=' string_list | 'working-directory' ':=' string boolean : ':=' ('true' | 'false') string_list : '[' string (',' string)* ','? ']' import : 'import' '?'? string? eol module : 'mod' '?'? NAME string? eol expression : disjunct || expression | disjunct disjunct : conjunct && disjunct | conjunct conjunct : 'if' condition '{' expression '}' 'else' '{' expression '}' | 'assert' '(' condition ',' expression ')' | '/' expression | value '/' expression | value '+' expression | value condition : expression '==' expression | expression '!=' expression | expression '=~' expression value : NAME '(' sequence? ')' | BACKTICK | INDENTED_BACKTICK | NAME | string | '(' expression ')' string : 'x'? STRING | 'x'? INDENTED_STRING | 'x'? RAW_STRING | 'x'? INDENTED_RAW_STRING sequence : expression ',' sequence | expression ','? recipe : attributes* '@'? NAME parameter* variadic? ':' dependencies eol body? attributes : '[' attribute* ']' eol attribute : NAME ( '(' string ')' )? parameter : '$'? NAME | '$'? NAME '=' value variadic : '*' parameter | '+' parameter dependencies : dependency* ('&&' dependency+)? dependency : NAME | '(' NAME expression* ')' body : INDENT line+ DEDENT line : LINE LINE_PREFIX? (TEXT | interpolation)+ NEWLINE | NEWLINE interpolation : '{{' expression '}}' ``` just-1.40.0/LICENSE000064400000000000000000000156101046102023000117030ustar 00000000000000Creative Commons Legal Code CC0 1.0 Universal CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. just-1.40.0/README.md000064400000000000000000003533661046102023000121720ustar 00000000000000
Table of Contents↗️

just

crates.io version build status downloads chat on discord say thanks

`just` is a handy way to save and run project-specific commands. This readme is also available as a [book](https://just.systems/man/en/). The book reflects the latest release, whereas the [readme on GitHub](https://github.com/casey/just/blob/master/README.md) reflects latest master. (中文文档在 [这里](https://github.com/casey/just/blob/master/README.中文.md), 快看过来!) Commands, called recipes, are stored in a file called `justfile` with syntax inspired by `make`: ![screenshot](https://raw.githubusercontent.com/casey/just/master/screenshot.png) You can then run them with `just RECIPE`: ```console $ just test-all cc *.c -o main ./test --all Yay, all your tests passed! ``` `just` has a ton of useful features, and many improvements over `make`: - `just` is a command runner, not a build system, so it avoids much of [`make`'s complexity and idiosyncrasies](#what-are-the-idiosyncrasies-of-make-that-just-avoids). No need for `.PHONY` recipes! - Linux, MacOS, Windows, and other reasonable unices are supported with no additional dependencies. (Although if your system doesn't have an `sh`, you'll need to [choose a different shell](#shell).) - Errors are specific and informative, and syntax errors are reported along with their source context. - Recipes can accept [command line arguments](#recipe-parameters). - Wherever possible, errors are resolved statically. Unknown recipes and circular dependencies are reported before anything runs. - `just` [loads `.env` files](#dotenv-settings), making it easy to populate environment variables. - Recipes can be [listed from the command line](#listing-available-recipes). - Command line completion scripts are [available for most popular shells](#shell-completion-scripts). - Recipes can be written in [arbitrary languages](#shebang-recipes), like Python or NodeJS. - `just` can be invoked from any subdirectory, not just the directory that contains the `justfile`. - And [much more](https://just.systems/man/en/)! If you need help with `just` please feel free to open an issue or ping me on [Discord](https://discord.gg/ezYScXR). Feature requests and bug reports are always welcome! Installation ------------ ### Prerequisites `just` should run on any system with a reasonable `sh`, including Linux, MacOS, and the BSDs. On Windows, `just` works with the `sh` provided by [Git for Windows](https://git-scm.com), [GitHub Desktop](https://desktop.github.com), or [Cygwin](http://www.cygwin.com). If you'd rather not install `sh`, you can use the `shell` setting to use the shell of your choice. Like PowerShell: ```just # use PowerShell instead of sh: set shell := ["powershell.exe", "-c"] hello: Write-Host "Hello, world!" ``` …or `cmd.exe`: ```just # use cmd.exe instead of sh: set shell := ["cmd.exe", "/c"] list: dir ``` You can also set the shell using command-line arguments. For example, to use PowerShell, launch `just` with `--shell powershell.exe --shell-arg -c`. (PowerShell is installed by default on Windows 7 SP1 and Windows Server 2008 R2 S1 and later, and `cmd.exe` is quite fiddly, so PowerShell is recommended for most Windows users.) ### Packages #### Cross-platform
Package Manager Package Command
asdf just asdf plugin add just
asdf install just <version>
Cargo just cargo install just
Conda just conda install -c conda-forge just
Homebrew just brew install just
Nix just nix-env -iA nixpkgs.just
npm rust-just npm install -g rust-just
PyPI rust-just pipx install rust-just
Snap just snap install --edge --classic just
#### BSD
Operating System Package Manager Package Command
FreeBSD pkg just pkg install just
#### Linux
Operating System Package Manager Package Command
Alpine apk-tools just apk add just
Arch pacman just pacman -S just
Debian 13 (unreleased) and Ubuntu 24.04 derivatives apt just apt install just
Debian and Ubuntu derivatives MPR just git clone https://mpr.makedeb.org/just
cd just
makedeb -si
Debian and Ubuntu derivatives Prebuilt-MPR just You must have the Prebuilt-MPR set up on your system in order to run this command.
apt install just
Fedora DNF just dnf install just
Gentoo Portage guru/dev-build/just eselect repository enable guru
emerge --sync guru
emerge dev-build/just
NixOS Nix just nix-env -iA nixos.just
openSUSE Zypper just zypper in just
Solus eopkg just eopkg install just
Void XBPS just xbps-install -S just
#### Windows
Package Manager Package Command
Chocolatey just choco install just
Scoop just scoop install just
Windows Package Manager Casey/Just winget install --id Casey.Just --exact
#### macOS
Package Manager Package Command
MacPorts just port install just
![just package version table](https://repology.org/badge/vertical-allrepos/just.svg) ### Pre-Built Binaries Pre-built binaries for Linux, MacOS, and Windows can be found on [the releases page](https://github.com/casey/just/releases). You can use the following command on Linux, MacOS, or Windows to download the latest release, just replace `DEST` with the directory where you'd like to put `just`: ```console curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to DEST ``` For example, to install `just` to `~/bin`: ```console # create ~/bin mkdir -p ~/bin # download and extract just to ~/bin/just curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin # add `~/bin` to the paths that your shell searches for executables # this line should be added to your shells initialization file, # e.g. `~/.bashrc` or `~/.zshrc` export PATH="$PATH:$HOME/bin" # just should now be executable just --help ``` Note that `install.sh` may fail on GitHub Actions, or in other environments where many machines share IP addresses. `install.sh` calls GitHub APIs in order to determine the latest version of `just` to install, and those API calls are rate-limited on a per-IP basis. To make `install.sh` more reliable in such circumstances, pass a specific tag to install with `--tag`. [Releases](https://github.com/casey/just/releases) include a `SHA256SUM` file which can be used to verify the integrity of pre-built binary archives. To verify a release, download the pre-built binary archive along with the `SHA256SUM` file and run: ```sh shasum --algorithm 256 --ignore-missing --check SHA256SUMS ``` ### GitHub Actions `just` can be installed on GitHub Actions in a few ways. Using package managers pre-installed on GitHub Actions runners on MacOS with `brew install just`, and on Windows with `choco install just`. With [extractions/setup-just](https://github.com/extractions/setup-just): ```yaml - uses: extractions/setup-just@v2 with: just-version: 1.5.0 # optional semver specification, otherwise latest ``` Or with [taiki-e/install-action](https://github.com/taiki-e/install-action): ```yaml - uses: taiki-e/install-action@just ``` ### Release RSS Feed An [RSS feed](https://en.wikipedia.org/wiki/RSS) of `just` releases is available [here](https://github.com/casey/just/releases.atom). ### Node.js Installation [just-install](https://npmjs.com/package/just-install) can be used to automate installation of `just` in Node.js applications. `just` is a great, more robust alternative to npm scripts. If you want to include `just` in the dependencies of a Node.js application, `just-install` will install a local, platform-specific binary as part of the `npm install` command. This removes the need for every developer to install `just` independently using one of the processes mentioned above. After installation, the `just` command will work in npm scripts or with npx. It's great for teams who want to make the set up process for their project as easy as possible. For more information, see the [just-install README file](https://github.com/brombal/just-install#readme). Backwards Compatibility ----------------------- With the release of version 1.0, `just` features a strong commitment to backwards compatibility and stability. Future releases will not introduce backwards incompatible changes that make existing `justfile`s stop working, or break working invocations of the command-line interface. This does not, however, preclude fixing outright bugs, even if doing so might break `justfiles` that rely on their behavior. There will never be a `just` 2.0. Any desirable backwards-incompatible changes will be opt-in on a per-`justfile` basis, so users may migrate at their leisure. Features that aren't yet ready for stabilization are marked as unstable and may be changed or removed at any time. Using unstable features produces an error by default, which can be suppressed with by passing the `--unstable` flag, `set unstable`, or setting the environment variable `JUST_UNSTABLE`, to any value other than `false`, `0`, or the empty string. Editor Support -------------- `justfile` syntax is close enough to `make` that you may want to tell your editor to use `make` syntax highlighting for `just`. ### Vim and Neovim Vim version 9.1.1042 or better and Neovim version 0.11 or better support Justfile syntax highlighting out of the box, thanks to [pbnj](https://github.com/pbnj). #### `vim-just` The [vim-just](https://github.com/NoahTheDuke/vim-just) plugin provides syntax highlighting for `justfile`s. Install it with your favorite package manager, like [Plug](https://github.com/junegunn/vim-plug): ```vim call plug#begin() Plug 'NoahTheDuke/vim-just' call plug#end() ``` Or with Vim's built-in package support: ```console mkdir -p ~/.vim/pack/vendor/start cd ~/.vim/pack/vendor/start git clone https://github.com/NoahTheDuke/vim-just.git ``` #### `tree-sitter-just` [tree-sitter-just](https://github.com/IndianBoy42/tree-sitter-just) is an [Nvim Treesitter](https://github.com/nvim-treesitter/nvim-treesitter) plugin for Neovim. #### Makefile Syntax Highlighting Vim's built-in makefile syntax highlighting isn't perfect for `justfile`s, but it's better than nothing. You can put the following in `~/.vim/filetype.vim`: ```vimscript if exists("did_load_filetypes") finish endif augroup filetypedetect au BufNewFile,BufRead justfile setf make augroup END ``` Or add the following to an individual `justfile` to enable `make` mode on a per-file basis: ```text # vim: set ft=make : ``` ### Emacs [just-mode](https://github.com/leon-barrett/just-mode.el) provides syntax highlighting and automatic indentation of `justfile`s. It is available on [MELPA](https://melpa.org/) as [just-mode](https://melpa.org/#/just-mode). [justl](https://github.com/psibi/justl.el) provides commands for executing and listing recipes. You can add the following to an individual `justfile` to enable `make` mode on a per-file basis: ```text # Local Variables: # mode: makefile # End: ``` ### Visual Studio Code An extension for VS Code is [available here](https://github.com/nefrob/vscode-just). Unmaintained VS Code extensions include [skellock/vscode-just](https://github.com/skellock/vscode-just) and [sclu1034/vscode-just](https://github.com/sclu1034/vscode-just). ### JetBrains IDEs A plugin for JetBrains IDEs by [linux_china](https://github.com/linux-china) is [available here](https://plugins.jetbrains.com/plugin/18658-just). ### Kakoune Kakoune supports `justfile` syntax highlighting out of the box, thanks to TeddyDD. ### Helix [Helix](https://helix-editor.com/) supports `justfile` syntax highlighting out-of-the-box since version 23.05. ### Sublime Text The [Just package](https://github.com/nk9/just_sublime) by [nk9](https://github.com/nk9) with `just` syntax and some other tools is available on [PackageControl](https://packagecontrol.io/packages/Just). ### Micro [Micro](https://micro-editor.github.io/) supports Justfile syntax highlighting out of the box, thanks to [tomodachi94](https://github.com/tomodachi94). ### Zed The [zed-just](https://github.com/jackTabsCode/zed-just/) extension by [jackTabsCode](https://github.com/jackTabsCode) is avilable on the [Zed extensions page](https://zed.dev/extensions?query=just). ### Other Editors Feel free to send me the commands necessary to get syntax highlighting working in your editor of choice so that I may include them here. Quick Start ----------- See the installation section for how to install `just` on your computer. Try running `just --version` to make sure that it's installed correctly. For an overview of the syntax, check out [this cheatsheet](https://cheatography.com/linux-china/cheat-sheets/justfile/). Once `just` is installed and working, create a file named `justfile` in the root of your project with the following contents: ```just recipe-name: echo 'This is a recipe!' # this is a comment another-recipe: @echo 'This is another recipe.' ``` When you invoke `just` it looks for file `justfile` in the current directory and upwards, so you can invoke it from any subdirectory of your project. The search for a `justfile` is case insensitive, so any case, like `Justfile`, `JUSTFILE`, or `JuStFiLe`, will work. `just` will also look for files with the name `.justfile`, in case you'd like to hide a `justfile`. Running `just` with no arguments runs the first recipe in the `justfile`: ```console $ just echo 'This is a recipe!' This is a recipe! ``` One or more arguments specify the recipe(s) to run: ```console $ just another-recipe This is another recipe. ``` `just` prints each command to standard error before running it, which is why `echo 'This is a recipe!'` was printed. This is suppressed for lines starting with `@`, which is why `echo 'This is another recipe.'` was not printed. Recipes stop running if a command fails. Here `cargo publish` will only run if `cargo test` succeeds: ```just publish: cargo test # tests passed, time to publish! cargo publish ``` Recipes can depend on other recipes. Here the `test` recipe depends on the `build` recipe, so `build` will run before `test`: ```just build: cc main.c foo.c bar.c -o main test: build ./test sloc: @echo "`wc -l *.c` lines of code" ``` ```console $ just test cc main.c foo.c bar.c -o main ./test testing… all tests passed! ``` Recipes without dependencies will run in the order they're given on the command line: ```console $ just build sloc cc main.c foo.c bar.c -o main 1337 lines of code ``` Dependencies will always run first, even if they are passed after a recipe that depends on them: ```console $ just test build cc main.c foo.c bar.c -o main ./test testing… all tests passed! ``` Examples -------- A variety of `justfile`s can be found in the [examples directory](https://github.com/casey/just/tree/master/examples) and on [GitHub](https://github.com/search?q=path%3A**%2Fjustfile&type=code). Features -------- ### The Default Recipe When `just` is invoked without a recipe, it runs the first recipe in the `justfile`. This recipe might be the most frequently run command in the project, like running the tests: ```just test: cargo test ``` You can also use dependencies to run multiple recipes by default: ```just default: lint build test build: echo Building… test: echo Testing… lint: echo Linting… ``` If no recipe makes sense as the default recipe, you can add a recipe to the beginning of your `justfile` that lists the available recipes: ```just default: just --list ``` ### Listing Available Recipes Recipes can be listed in alphabetical order with `just --list`: ```console $ just --list Available recipes: build test deploy lint ``` Recipes in [submodules](#modules1190) can be listed with `just --list PATH`, where `PATH` is a space- or `::`-separated module path: ``` $ cat justfile mod foo $ cat foo.just mod bar $ cat bar.just baz: $ just foo bar Available recipes: baz $ just foo::bar Available recipes: baz ``` `just --summary` is more concise: ```console $ just --summary build test deploy lint ``` Pass `--unsorted` to print recipes in the order they appear in the `justfile`: ```just test: echo 'Testing!' build: echo 'Building!' ``` ```console $ just --list --unsorted Available recipes: test build ``` ```console $ just --summary --unsorted test build ``` If you'd like `just` to default to listing the recipes in the `justfile`, you can use this as your default recipe: ```just default: @just --list ``` Note that you may need to add `--justfile {{justfile()}}` to the line above. Without it, if you executed `just -f /some/distant/justfile -d .` or `just -f ./non-standard-justfile`, the plain `just --list` inside the recipe would not necessarily use the file you provided. It would try to find a justfile in your current path, maybe even resulting in a `No justfile found` error. The heading text can be customized with `--list-heading`: ```console $ just --list --list-heading $'Cool stuff…\n' Cool stuff… test build ``` And the indentation can be customized with `--list-prefix`: ```console $ just --list --list-prefix ···· Available recipes: ····test ····build ``` The argument to `--list-heading` replaces both the heading and the newline following it, so it should contain a newline if non-empty. It works this way so you can suppress the heading line entirely by passing the empty string: ```console $ just --list --list-heading '' test build ``` ### Invoking Multiple Recipes Multiple recipes may be invoked on the command line at once: ```just build: make web serve: python3 -m http.server -d out 8000 ``` ```console $ just build serve make web python3 -m http.server -d out 8000 ``` Keep in mind that recipes with parameters will swallow arguments, even if they match the names of other recipes: ```just build project: make {{project}} serve: python3 -m http.server -d out 8000 ``` ```console $ just build serve make: *** No rule to make target `serve'. Stop. ``` The `--one` flag can be used to restrict command-line invocations to a single recipe: ```console $ just --one build serve error: Expected 1 command-line recipe invocation but found 2. ``` ### Working Directory By default, recipes run with the working directory set to the directory that contains the `justfile`. The `[no-cd]` attribute can be used to make recipes run with the working directory set to directory in which `just` was invoked. ```just @foo: pwd [no-cd] @bar: pwd ``` ```console $ cd subdir $ just foo / $ just bar /subdir ``` You can override the working directory for all recipes with `set working-directory := '…'`: ```just set working-directory := 'bar' @foo: pwd ``` ```console $ pwd /home/bob $ just foo /home/bob/bar ``` You can override the working directory for a specific recipe with the `working-directory` attribute1.38.0: ```just [working-directory: 'bar'] @foo: pwd ``` ```console $ pwd /home/bob $ just foo /home/bob/bar ``` The argument to the `working-directory` setting or `working-directory` attribute may be absolute or relative. If it is relative it is interpreted relative to the default working directory. ### Aliases Aliases allow recipes to be invoked on the command line with alternative names: ```just alias b := build build: echo 'Building!' ``` ```console $ just b echo 'Building!' Building! ``` The target of an alias may be a recipe in a submodule: ```justfile mod foo alias baz := foo::bar ``` ### Settings Settings control interpretation and execution. Each setting may be specified at most once, anywhere in the `justfile`. For example: ```just set shell := ["zsh", "-cu"] foo: # this line will be run as `zsh -cu 'ls **/*.txt'` ls **/*.txt ``` #### Table of Settings | Name | Value | Default | Description | |------|-------|---------|-------------| | `allow-duplicate-recipes` | boolean | `false` | Allow recipes appearing later in a `justfile` to override earlier recipes with the same name. | | `allow-duplicate-variables` | boolean | `false` | Allow variables appearing later in a `justfile` to override earlier variables with the same name. | | `dotenv-filename` | string | - | Load a `.env` file with a custom name, if present. | | `dotenv-load` | boolean | `false` | Load a `.env` file, if present. | | `dotenv-path` | string | - | Load a `.env` file from a custom path and error if not present. Overrides `dotenv-filename`. | | `dotenv-required` | boolean | `false` | Error if a `.env` file isn't found. | | `export` | boolean | `false` | Export all variables as environment variables. | | `fallback` | boolean | `false` | Search `justfile` in parent directory if the first recipe on the command line is not found. | | `ignore-comments` | boolean | `false` | Ignore recipe lines beginning with `#`. | | `positional-arguments` | boolean | `false` | Pass positional arguments. | | `quiet` | boolean | `false` | Disable echoing recipe lines before executing. | | `script-interpreter`1.33.0 | `[COMMAND, ARGS…]` | `['sh', '-eu']` | Set command used to invoke recipes with empty `[script]` attribute. | | `shell` | `[COMMAND, ARGS…]` | - | Set command used to invoke recipes and evaluate backticks. | | `tempdir` | string | - | Create temporary directories in `tempdir` instead of the system default temporary directory. | | `unstable`1.31.0 | boolean | `false` | Enable unstable features. | | `windows-powershell` | boolean | `false` | Use PowerShell on Windows as default shell. (Deprecated. Use `windows-shell` instead. | | `windows-shell` | `[COMMAND, ARGS…]` | - | Set the command used to invoke recipes and evaluate backticks. | | `working-directory`1.33.0 | string | - | Set the working directory for recipes and backticks, relative to the default working directory. | Boolean settings can be written as: ```justfile set NAME ``` Which is equivalent to: ```justfile set NAME := true ``` #### Allow Duplicate Recipes If `allow-duplicate-recipes` is set to `true`, defining multiple recipes with the same name is not an error and the last definition is used. Defaults to `false`. ```just set allow-duplicate-recipes @foo: echo foo @foo: echo bar ``` ```console $ just foo bar ``` #### Allow Duplicate Variables If `allow-duplicate-variables` is set to `true`, defining multiple variables with the same name is not an error and the last definition is used. Defaults to `false`. ```just set allow-duplicate-variables a := "foo" a := "bar" @foo: echo {{a}} ``` ```console $ just foo bar ``` #### Dotenv Settings If any of `dotenv-load`, `dotenv-filename`, `dotenv-path`, or `dotenv-required` are set, `just` will try to load environment variables from a file. If `dotenv-path` is set, `just` will look for a file at the given path, which may be absolute, or relative to the working directory. The command-line option `--dotenv-path`, short form `-E`, can be used to set or override `dotenv-path` at runtime. If `dotenv-filename` is set `just` will look for a file at the given path, relative to the working directory and each of its ancestors. If `dotenv-filename` is not set, but `dotenv-load` or `dotenv-required` are set, just will look for a file named `.env`, relative to the working directory and each of its ancestors. `dotenv-filename` and `dotenv-path` are similar, but `dotenv-path` is only checked relative to the working directory, whereas `dotenv-filename` is checked relative to the working directory and each of its ancestors. It is not an error if an environment file is not found, unless `dotenv-required` is set. The loaded variables are environment variables, not `just` variables, and so must be accessed using `$VARIABLE_NAME` in recipes and backticks. For example, if your `.env` file contains: ```console # a comment, will be ignored DATABASE_ADDRESS=localhost:6379 SERVER_PORT=1337 ``` And your `justfile` contains: ```just set dotenv-load serve: @echo "Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT…" ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` `just serve` will output: ```console $ just serve Starting server with database localhost:6379 on port 1337… ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` #### Export The `export` setting causes all `just` variables to be exported as environment variables. Defaults to `false`. ```just set export a := "hello" @foo b: echo $a echo $b ``` ```console $ just foo goodbye hello goodbye ``` #### Positional Arguments If `positional-arguments` is `true`, recipe arguments will be passed as positional arguments to commands. For linewise recipes, argument `$0` will be the name of the recipe. For example, running this recipe: ```just set positional-arguments @foo bar: echo $0 echo $1 ``` Will produce the following output: ```console $ just foo hello foo hello ``` When using an `sh`-compatible shell, such as `bash` or `zsh`, `$@` expands to the positional arguments given to the recipe, starting from one. When used within double quotes as `"$@"`, arguments including whitespace will be passed on as if they were double-quoted. That is, `"$@"` is equivalent to `"$1" "$2"`… When there are no positional parameters, `"$@"` and `$@` expand to nothing (i.e., they are removed). This example recipe will print arguments one by one on separate lines: ```just set positional-arguments @test *args='': bash -c 'while (( "$#" )); do echo - $1; shift; done' -- "$@" ``` Running it with _two_ arguments: ```console $ just test foo "bar baz" - foo - bar baz ``` Positional arguments may also be turned on on a per-recipe basis with the `[positional-arguments]` attribute1.29.0: ```just [positional-arguments] @foo bar: echo $0 echo $1 ``` Note that PowerShell does not handle positional arguments in the same way as other shells, so turning on positional arguments will likely break recipes that use PowerShell. If using PowerShell 7.4 or better, the `-CommandWithArgs` flag will make positional arguments work as expected: ```just set shell := ['pwsh.exe', '-CommandWithArgs'] set positional-arguments print-args a b c: Write-Output @($args[1..($args.Count - 1)]) ``` #### Shell The `shell` setting controls the command used to invoke recipe lines and backticks. Shebang recipes are unaffected. The default shell is `sh -cu`. ```just # use python3 to execute recipe lines and backticks set shell := ["python3", "-c"] # use print to capture result of evaluation foos := `print("foo" * 4)` foo: print("Snake snake snake snake.") print("{{foos}}") ``` `just` passes the command to be executed as an argument. Many shells will need an additional flag, often `-c`, to make them evaluate the first argument. ##### Windows Shell `just` uses `sh` on Windows by default. To use a different shell on Windows, use `windows-shell`: ```just set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] hello: Write-Host "Hello, world!" ``` See [powershell.just](https://github.com/casey/just/blob/master/examples/powershell.just) for a justfile that uses PowerShell on all platforms. ##### Windows PowerShell *`set windows-powershell` uses the legacy `powershell.exe` binary, and is no longer recommended. See the `windows-shell` setting above for a more flexible way to control which shell is used on Windows.* `just` uses `sh` on Windows by default. To use `powershell.exe` instead, set `windows-powershell` to true. ```just set windows-powershell := true hello: Write-Host "Hello, world!" ``` ##### Python 3 ```just set shell := ["python3", "-c"] ``` ##### Bash ```just set shell := ["bash", "-uc"] ``` ##### Z Shell ```just set shell := ["zsh", "-uc"] ``` ##### Fish ```just set shell := ["fish", "-c"] ``` ##### Nushell ```just set shell := ["nu", "-c"] ``` If you want to change the default table mode to `light`: ```just set shell := ['nu', '-m', 'light', '-c'] ``` *[Nushell](https://github.com/nushell/nushell) was written in Rust, and **has cross-platform support for Windows / macOS and Linux**.* ### Documentation Comments Comments immediately preceding a recipe will appear in `just --list`: ```just # build stuff build: ./bin/build # test stuff test: ./bin/test ``` ```console $ just --list Available recipes: build # build stuff test # test stuff ``` The `[doc]` attribute can be used to set or suppress a recipe's doc comment: ```just # This comment won't appear [doc('Build stuff')] build: ./bin/build # This one won't either [doc] test: ./bin/test ``` ```console $ just --list Available recipes: build # Build stuff test ``` ### Expressions and Substitutions Various operators and function calls are supported in expressions, which may be used in assignments, default recipe arguments, and inside recipe body `{{…}}` substitutions. ```just tmpdir := `mktemp -d` version := "0.2.7" tardir := tmpdir / "awesomesauce-" + version tarball := tardir + ".tar.gz" config := quote(config_dir() / ".project-config") publish: rm -f {{tarball}} mkdir {{tardir}} cp README.md *.c {{ config }} {{tardir}} tar zcvf {{tarball}} {{tardir}} scp {{tarball}} me@server.com:release/ rm -rf {{tarball}} {{tardir}} ``` #### Concatenation The `+` operator returns the left-hand argument concatenated with the right-hand argument: ```just foobar := 'foo' + 'bar' ``` #### Logical Operators The logical operators `&&` and `||` can be used to coalesce string values1.37.0, similar to Python's `and` and `or`. These operators consider the empty string `''` to be false, and all other strings to be true. These operators are currently unstable. The `&&` operator returns the empty string if the left-hand argument is the empty string, otherwise it returns the right-hand argument: ```justfile foo := '' && 'goodbye' # '' bar := 'hello' && 'goodbye' # 'goodbye' ``` The `||` operator returns the left-hand argument if it is non-empty, otherwise it returns the right-hand argument: ```justfile foo := '' || 'goodbye' # 'goodbye' bar := 'hello' || 'goodbye' # 'hello' ``` #### Joining Paths The `/` operator can be used to join two strings with a slash: ```just foo := "a" / "b" ``` ``` $ just --evaluate foo a/b ``` Note that a `/` is added even if one is already present: ```just foo := "a/" bar := foo / "b" ``` ``` $ just --evaluate bar a//b ``` Absolute paths can also be constructed1.5.0: ```just foo := / "b" ``` ``` $ just --evaluate foo /b ``` The `/` operator uses the `/` character, even on Windows. Thus, using the `/` operator should be avoided with paths that use universal naming convention (UNC), i.e., those that start with `\?`, since forward slashes are not supported with UNC paths. #### Escaping `{{` To write a recipe containing `{{`, use `{{{{`: ```just braces: echo 'I {{{{LOVE}} curly braces!' ``` (An unmatched `}}` is ignored, so it doesn't need to be escaped.) Another option is to put all the text you'd like to escape inside of an interpolation: ```just braces: echo '{{'I {{LOVE}} curly braces!'}}' ``` Yet another option is to use `{{ "{{" }}`: ```just braces: echo 'I {{ "{{" }}LOVE}} curly braces!' ``` ### Strings `'single'`, `"double"`, and `'''triple'''` quoted string literals are supported. Unlike in recipe bodies, `{{…}}` interpolations are not supported inside strings. Double-quoted strings support escape sequences: ```just carriage-return := "\r" double-quote := "\"" newline := "\n" no-newline := "\ " slash := "\\" tab := "\t" unicode-codepoint := "\u{1F916}" ``` ```console $ just --evaluate "arriage-return := " double-quote := """ newline := " " no-newline := "" slash := "\" tab := " " unicode-codepoint := "🤖" ``` The unicode character escape sequence `\u{…}`1.36.0 accepts up to six hex digits. Strings may contain line breaks: ```just single := ' hello ' double := " goodbye " ``` Single-quoted strings do not recognize escape sequences: ```just escapes := '\t\n\r\"\\' ``` ```console $ just --evaluate escapes := "\t\n\r\"\\" ``` Indented versions of both single- and double-quoted strings, delimited by triple single- or double-quotes, are supported. Indented string lines are stripped of a leading line break, and leading whitespace common to all non-blank lines: ```just # this string will evaluate to `foo\nbar\n` x := ''' foo bar ''' # this string will evaluate to `abc\n wuv\nxyz\n` y := """ abc wuv xyz """ ``` Similar to unindented strings, indented double-quoted strings process escape sequences, and indented single-quoted strings ignore escape sequences. Escape sequence processing takes place after unindentation. The unindentation algorithm does not take escape-sequence produced whitespace or newlines into account. Strings prefixed with `x` are shell expanded1.27.0: ```justfile foobar := x'~/$FOO/${BAR}' ``` | Value | Replacement | |------|-------------| | `$VAR` | value of environment variable `VAR` | | `${VAR}` | value of environment variable `VAR` | | `${VAR:-DEFAULT}` | value of environment variable `VAR`, or `DEFAULT` if `VAR` is not set | | Leading `~` | path to current user's home directory | | Leading `~USER` | path to `USER`'s home directory | This expansion is performed at compile time, so variables from `.env` files and exported `just` variables cannot be used. However, this allows shell expanded strings to be used in places like settings and import paths, which cannot depend on `just` variables and `.env` files. ### Ignoring Errors Normally, if a command returns a non-zero exit status, execution will stop. To continue execution after a command, even if it fails, prefix the command with `-`: ```just foo: -cat foo echo 'Done!' ``` ```console $ just foo cat foo cat: foo: No such file or directory echo 'Done!' Done! ``` ### Functions `just` provides many built-in functions for use in expressions, including recipe body `{{…}}` substitutions, assignments, and default parameter values. All functions ending in `_directory` can be abbreviated to `_dir`. So `home_directory()` can also be written as `home_dir()`. In addition, `invocation_directory_native()` can be abbreviated to `invocation_dir_native()`. #### System Information - `arch()` — Instruction set architecture. Possible values are: `"aarch64"`, `"arm"`, `"asmjs"`, `"hexagon"`, `"mips"`, `"msp430"`, `"powerpc"`, `"powerpc64"`, `"s390x"`, `"sparc"`, `"wasm32"`, `"x86"`, `"x86_64"`, and `"xcore"`. - `num_cpus()`1.15.0 - Number of logical CPUs. - `os()` — Operating system. Possible values are: `"android"`, `"bitrig"`, `"dragonfly"`, `"emscripten"`, `"freebsd"`, `"haiku"`, `"ios"`, `"linux"`, `"macos"`, `"netbsd"`, `"openbsd"`, `"solaris"`, and `"windows"`. - `os_family()` — Operating system family; possible values are: `"unix"` and `"windows"`. For example: ```just system-info: @echo "This is an {{arch()}} machine". ``` ```console $ just system-info This is an x86_64 machine ``` The `os_family()` function can be used to create cross-platform `justfile`s that work on various operating systems. For an example, see [cross-platform.just](https://github.com/casey/just/blob/master/examples/cross-platform.just) file. #### External Commands - `shell(command, args...)`1.27.0 returns the standard output of shell script `command` with zero or more positional arguments `args`. The shell used to interpret `command` is the same shell that is used to evaluate recipe lines, and can be changed with `set shell := […]`. `command` is passed as the first argument, so if the command is `'echo $@'`, the full command line, with the default shell command `sh -cu` and `args` `'foo'` and `'bar'` will be: ``` 'sh' '-cu' 'echo $@' 'echo $@' 'foo' 'bar' ``` This is so that `$@` works as expected, and `$1` refers to the first argument. `$@` does not include the first positional argument, which is expected to be the name of the program being run. ```just # arguments can be variables or expressions file := '/sys/class/power_supply/BAT0/status' bat0stat := shell('cat $1', file) # commands can be variables or expressions command := 'wc -l' output := shell(command + ' "$1"', 'main.c') # arguments referenced by the shell command must be used empty := shell('echo', 'foo') full := shell('echo $1', 'foo') error := shell('echo $1') ``` ```just # Using python as the shell. Since `python -c` sets `sys.argv[0]` to `'-c'`, # the first "real" positional argument will be `sys.argv[2]`. set shell := ["python3", "-c"] olleh := shell('import sys; print(sys.argv[2][::-1])', 'hello') ``` #### Environment Variables - `env(key)`1.15.0 — Retrieves the environment variable with name `key`, aborting if it is not present. ```just home_dir := env('HOME') test: echo "{{home_dir}}" ``` ```console $ just /home/user1 ``` - `env(key, default)`1.15.0 — Retrieves the environment variable with name `key`, returning `default` if it is not present. - `env_var(key)` — Deprecated alias for `env(key)`. - `env_var_or_default(key, default)` — Deprecated alias for `env(key, default)`. A default can be substituted for an empty environment variable value with the `||` operator, currently unstable: ```just set unstable foo := env('FOO') || 'DEFAULT_VALUE' ``` #### Executables - `require(name)`1.39.0 — Search directories in the `PATH` environment variable for the executable `name` and return its full path, or halt with an error if no executable with `name` exists. ```just bash := require("bash") @test: echo "bash: '{{bash}}'" ``` ```console $ just bash: '/bin/bash' ``` - `which(name)`1.39.0 — Search directories in the `PATH` environment variable for the executable `name` and return its full path, or the empty string if no executable with `name` exists. Currently unstable. ```just set unstable bosh := which("bosh") @test: echo "bosh: '{{bosh}}'" ``` ```console $ just bosh: '' ``` #### Invocation Information - `is_dependency()` - Returns the string `true` if the current recipe is being run as a dependency of another recipe, rather than being run directly, otherwise returns the string `false`. #### Invocation Directory - `invocation_directory()` - Retrieves the absolute path to the current directory when `just` was invoked, before `just` changed it (chdir'd) prior to executing commands. On Windows, `invocation_directory()` uses `cygpath` to convert the invocation directory to a Cygwin-compatible `/`-separated path. Use `invocation_directory_native()` to return the verbatim invocation directory on all platforms. For example, to call `rustfmt` on files just under the "current directory" (from the user/invoker's perspective), use the following rule: ```just rustfmt: find {{invocation_directory()}} -name \*.rs -exec rustfmt {} \; ``` Alternatively, if your command needs to be run from the current directory, you could use (e.g.): ```just build: cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here ``` - `invocation_directory_native()` - Retrieves the absolute path to the current directory when `just` was invoked, before `just` changed it (chdir'd) prior to executing commands. #### Justfile and Justfile Directory - `justfile()` - Retrieves the path of the current `justfile`. - `justfile_directory()` - Retrieves the path of the parent directory of the current `justfile`. For example, to run a command relative to the location of the current `justfile`: ```just script: {{justfile_directory()}}/scripts/some_script ``` #### Source and Source Directory - `source_file()`1.27.0 - Retrieves the path of the current source file. - `source_directory()`1.27.0 - Retrieves the path of the parent directory of the current source file. `source_file()` and `source_directory()` behave the same as `justfile()` and `justfile_directory()` in the root `justfile`, but will return the path and directory, respectively, of the current `import` or `mod` source file when called from within an import or submodule. #### Just Executable - `just_executable()` - Absolute path to the `just` executable. For example: ```just executable: @echo The executable is at: {{just_executable()}} ``` ```console $ just The executable is at: /bin/just ``` #### Just Process ID - `just_pid()` - Process ID of the `just` executable. For example: ```just pid: @echo The process ID is: {{ just_pid() }} ``` ```console $ just The process ID is: 420 ``` #### String Manipulation - `append(suffix, s)`1.27.0 Append `suffix` to whitespace-separated strings in `s`. `append('/src', 'foo bar baz')` → `'foo/src bar/src baz/src'` - `prepend(prefix, s)`1.27.0 Prepend `prefix` to whitespace-separated strings in `s`. `prepend('src/', 'foo bar baz')` → `'src/foo src/bar src/baz'` - `encode_uri_component(s)`1.27.0 - Percent-encode characters in `s` except `[A-Za-z0-9_.!~*'()-]`, matching the behavior of the [JavaScript `encodeURIComponent` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent). - `quote(s)` - Replace all single quotes with `'\''` and prepend and append single quotes to `s`. This is sufficient to escape special characters for many shells, including most Bourne shell descendants. - `replace(s, from, to)` - Replace all occurrences of `from` in `s` to `to`. - `replace_regex(s, regex, replacement)` - Replace all occurrences of `regex` in `s` to `replacement`. Regular expressions are provided by the [Rust `regex` crate](https://docs.rs/regex/latest/regex/). See the [syntax documentation](https://docs.rs/regex/latest/regex/#syntax) for usage examples. Capture groups are supported. The `replacement` string uses [Replacement string syntax](https://docs.rs/regex/latest/regex/struct.Regex.html#replacement-string-syntax). - `trim(s)` - Remove leading and trailing whitespace from `s`. - `trim_end(s)` - Remove trailing whitespace from `s`. - `trim_end_match(s, substring)` - Remove suffix of `s` matching `substring`. - `trim_end_matches(s, substring)` - Repeatedly remove suffixes of `s` matching `substring`. - `trim_start(s)` - Remove leading whitespace from `s`. - `trim_start_match(s, substring)` - Remove prefix of `s` matching `substring`. - `trim_start_matches(s, substring)` - Repeatedly remove prefixes of `s` matching `substring`. #### Case Conversion - `capitalize(s)`1.7.0 - Convert first character of `s` to uppercase and the rest to lowercase. - `kebabcase(s)`1.7.0 - Convert `s` to `kebab-case`. - `lowercamelcase(s)`1.7.0 - Convert `s` to `lowerCamelCase`. - `lowercase(s)` - Convert `s` to lowercase. - `shoutykebabcase(s)`1.7.0 - Convert `s` to `SHOUTY-KEBAB-CASE`. - `shoutysnakecase(s)`1.7.0 - Convert `s` to `SHOUTY_SNAKE_CASE`. - `snakecase(s)`1.7.0 - Convert `s` to `snake_case`. - `titlecase(s)`1.7.0 - Convert `s` to `Title Case`. - `uppercamelcase(s)`1.7.0 - Convert `s` to `UpperCamelCase`. - `uppercase(s)` - Convert `s` to uppercase. #### Path Manipulation ##### Fallible - `absolute_path(path)` - Absolute path to relative `path` in the working directory. `absolute_path("./bar.txt")` in directory `/foo` is `/foo/bar.txt`. - `canonicalize(path)`1.24.0 - Canonicalize `path` by resolving symlinks and removing `.`, `..`, and extra `/`s where possible. - `extension(path)` - Extension of `path`. `extension("/foo/bar.txt")` is `txt`. - `file_name(path)` - File name of `path` with any leading directory components removed. `file_name("/foo/bar.txt")` is `bar.txt`. - `file_stem(path)` - File name of `path` without extension. `file_stem("/foo/bar.txt")` is `bar`. - `parent_directory(path)` - Parent directory of `path`. `parent_directory("/foo/bar.txt")` is `/foo`. - `without_extension(path)` - `path` without extension. `without_extension("/foo/bar.txt")` is `/foo/bar`. These functions can fail, for example if a path does not have an extension, which will halt execution. ##### Infallible - `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean("foo//bar")` is `foo/bar`, `clean("foo/..")` is `.`, `clean("foo/./bar")` is `foo/bar`. - `join(a, b…)` - *This function uses `/` on Unix and `\` on Windows, which can be lead to unwanted behavior. The `/` operator, e.g., `a / b`, which always uses `/`, should be considered as a replacement unless `\`s are specifically desired on Windows.* Join path `a` with path `b`. `join("foo/bar", "baz")` is `foo/bar/baz`. Accepts two or more arguments. #### Filesystem Access - `path_exists(path)` - Returns `true` if the path points at an existing entity and `false` otherwise. Traverses symbolic links, and returns `false` if the path is inaccessible or points to a broken symlink. - `read(path)`1.39.0 - Returns the content of file at `path` as string. ##### Error Reporting - `error(message)` - Abort execution and report error `message` to user. #### UUID and Hash Generation - `blake3(string)`1.25.0 - Return [BLAKE3] hash of `string` as hexadecimal string. - `blake3_file(path)`1.25.0 - Return [BLAKE3] hash of file at `path` as hexadecimal string. - `sha256(string)` - Return the SHA-256 hash of `string` as hexadecimal string. - `sha256_file(path)` - Return SHA-256 hash of file at `path` as hexadecimal string. - `uuid()` - Generate a random version 4 UUID. [BLAKE3]: https://github.com/BLAKE3-team/BLAKE3/ #### Random - `choose(n, alphabet)`1.27.0 - Generate a string of `n` randomly selected characters from `alphabet`, which may not contain repeated characters. For example, `choose('64', HEX)` will generate a random 64-character lowercase hex string. #### Datetime - `datetime(format)`1.30.0 - Return local time with `format`. - `datetime_utc(format)`1.30.0 - Return UTC time with `format`. The arguments to `datetime` and `datetime_utc` are `strftime`-style format strings, see the [`chrono` library docs](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) for details. #### Semantic Versions - `semver_matches(version, requirement)`1.16.0 - Check whether a [semantic `version`](https://semver.org), e.g., `"0.1.0"` matches a `requirement`, e.g., `">=0.1.0"`, returning `"true"` if so and `"false"` otherwise. #### Style - `style(name)`1.37.0 - Return a named terminal display attribute escape sequence used by `just`. Unlike terminal display attribute escape sequence constants, which contain standard colors and styles, `style(name)` returns an escape sequence used by `just` itself, and can be used to make recipe output match `just`'s own output. Recognized values for `name` are `'command'`, for echoed recipe lines, `error`, and `warning`. For example, to style an error message: ```just scary: @echo '{{ style("error") }}OH NO{{ NORMAL }}' ``` ##### User Directories1.23.0 These functions return paths to user-specific directories for things like configuration, data, caches, executables, and the user's home directory. On Unix, these functions follow the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html). On MacOS and Windows, these functions return the system-specified user-specific directories. For example, `cache_directory()` returns `~/Library/Caches` on MacOS and `{FOLDERID_LocalAppData}` on Windows. See the [`dirs`](https://docs.rs/dirs/latest/dirs/index.html) crate for more details. - `cache_directory()` - The user-specific cache directory. - `config_directory()` - The user-specific configuration directory. - `config_local_directory()` - The local user-specific configuration directory. - `data_directory()` - The user-specific data directory. - `data_local_directory()` - The local user-specific data directory. - `executable_directory()` - The user-specific executable directory. - `home_directory()` - The user's home directory. If you would like to use XDG base directories on all platforms you can use the `env(…)` function with the appropriate environment variable and fallback, although note that the XDG specification requires ignoring non-absolute paths, so for full compatibility with spec-compliant applications, you would need to do: ```just xdg_config_dir := if env('XDG_CONFIG_HOME', '') =~ '^/' { env('XDG_CONFIG_HOME') } else { home_directory() / '.config' } ``` ### Constants A number of constants are predefined: | Name | Value | |------|-------------| | `HEX`1.27.0 | `"0123456789abcdef"` | | `HEXLOWER`1.27.0 | `"0123456789abcdef"` | | `HEXUPPER`1.27.0 | `"0123456789ABCDEF"` | | `CLEAR`1.37.0 | `"\ec"` | | `NORMAL`1.37.0 | `"\e[0m"` | | `BOLD`1.37.0 | `"\e[1m"` | | `ITALIC`1.37.0 | `"\e[3m"` | | `UNDERLINE`1.37.0 | `"\e[4m"` | | `INVERT`1.37.0 | `"\e[7m"` | | `HIDE`1.37.0 | `"\e[8m"` | | `STRIKETHROUGH`1.37.0 | `"\e[9m"` | | `BLACK`1.37.0 | `"\e[30m"` | | `RED`1.37.0 | `"\e[31m"` | | `GREEN`1.37.0 | `"\e[32m"` | | `YELLOW`1.37.0 | `"\e[33m"` | | `BLUE`1.37.0 | `"\e[34m"` | | `MAGENTA`1.37.0 | `"\e[35m"` | | `CYAN`1.37.0 | `"\e[36m"` | | `WHITE`1.37.0 | `"\e[37m"` | | `BG_BLACK`1.37.0 | `"\e[40m"` | | `BG_RED`1.37.0 | `"\e[41m"` | | `BG_GREEN`1.37.0 | `"\e[42m"` | | `BG_YELLOW`1.37.0 | `"\e[43m"` | | `BG_BLUE`1.37.0 | `"\e[44m"` | | `BG_MAGENTA`1.37.0 | `"\e[45m"` | | `BG_CYAN`1.37.0 | `"\e[46m"` | | `BG_WHITE`1.37.0 | `"\e[47m"` | ```just @foo: echo {{HEX}} ``` ```console $ just foo 0123456789abcdef ``` Constants starting with `\e` are [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). `CLEAR` clears the screen, similar to the `clear` command. The rest are of the form `\e[Nm`, where `N` is an integer, and set terminal display attributes. Terminal display attribute escape sequences can be combined, for example text weight `BOLD`, text style `STRIKETHROUGH`, foreground color `CYAN`, and background color `BG_BLUE`. They should be followed by `NORMAL`, to reset the terminal back to normal. Escape sequences should be quoted, since `[` is treated as a special character by some shells. ```just @foo: echo '{{BOLD + STRIKETHROUGH + CYAN + BG_BLUE}}Hi!{{NORMAL}}' ``` ### Attributes Recipes, `mod` statements, and aliases may be annotated with attributes that change their behavior. | Name | Type | Description | |------|------|-------------| | `[confirm]`1.17.0 | recipe | Require confirmation prior to executing recipe. | | `[confirm('PROMPT')]`1.23.0 | recipe | Require confirmation prior to executing recipe with a custom prompt. | | `[doc('DOC')]`1.27.0 | module, recipe | Set recipe or module's [documentation comment](#documentation-comments) to `DOC`. | | `[extension('EXT')]`1.32.0 | recipe | Set shebang recipe script's file extension to `EXT`. `EXT` should include a period if one is desired. | | `[group('NAME')]`1.27.0 | module, recipe | Put recipe or module in in [group](#groups) `NAME`. | | `[linux]`1.8.0 | recipe | Enable recipe on Linux. | | `[macos]`1.8.0 | recipe | Enable recipe on MacOS. | | `[no-cd]`1.9.0 | recipe | Don't change directory before executing recipe. | | `[no-exit-message]`1.7.0 | recipe | Don't print an error message if recipe fails. | | `[no-quiet]`1.23.0 | recipe | Override globally quiet recipes and always echo out the recipe. | | `[openbsd]`1.38.0 | recipe | Enable recipe on OpenBSD. | | `[positional-arguments]`1.29.0 | recipe | Turn on [positional arguments](#positional-arguments) for this recipe. | | `[private]`1.10.0 | alias, recipe | Make recipe, alias, or variable private. See [Private Recipes](#private-recipes). | | `[script]`1.33.0 | recipe | Execute recipe as script. See [script recipes](#script-recipes) for more details. | | `[script(COMMAND)]`1.32.0 | recipe | Execute recipe as a script interpreted by `COMMAND`. See [script recipes](#script-recipes) for more details. | | `[unix]`1.8.0 | recipe | Enable recipe on Unixes. (Includes MacOS). | | `[windows]`1.8.0 | recipe | Enable recipe on Windows. | | `[working-directory(PATH)]`1.38.0 | recipe | Set recipe working directory. `PATH` may be relative or absolute. If relative, it is interpreted relative to the default working directory. | A recipe can have multiple attributes, either on multiple lines: ```just [no-cd] [private] foo: echo "foo" ``` Or separated by commas on a single line1.14.0: ```just [no-cd, private] foo: echo "foo" ``` #### Enabling and Disabling Recipes1.8.0 The `[linux]`, `[macos]`, `[unix]`, and `[windows]` attributes are configuration attributes. By default, recipes are always enabled. A recipe with one or more configuration attributes will only be enabled when one or more of those configurations is active. This can be used to write `justfile`s that behave differently depending on which operating system they run on. The `run` recipe in this `justfile` will compile and run `main.c`, using a different C compiler and using the correct output binary name for that compiler depending on the operating system: ```just [unix] run: cc main.c ./a.out [windows] run: cl main.c main.exe ``` #### Disabling Changing Directory1.9.0 `just` normally executes recipes with the current directory set to the directory that contains the `justfile`. This can be disabled using the `[no-cd]` attribute. This can be used to create recipes which use paths relative to the invocation directory, or which operate on the current directory. For example, this `commit` recipe: ```just [no-cd] commit file: git add {{file}} git commit ``` Can be used with paths that are relative to the current directory, because `[no-cd]` prevents `just` from changing the current directory when executing `commit`. #### Requiring Confirmation for Recipes1.17.0 `just` normally executes all recipes unless there is an error. The `[confirm]` attribute allows recipes require confirmation in the terminal prior to running. This can be overridden by passing `--yes` to `just`, which will automatically confirm any recipes marked by this attribute. Recipes dependent on a recipe that requires confirmation will not be run if the relied upon recipe is not confirmed, as well as recipes passed after any recipe that requires confirmation. ```just [confirm] delete-all: rm -rf * ``` #### Custom Confirmation Prompt1.23.0 The default confirmation prompt can be overridden with `[confirm(PROMPT)]`: ```just [confirm("Are you sure you want to delete everything?")] delete-everything: rm -rf * ``` ### Groups Recipes and modules may be annotated with a group name: ```just [group('lint')] js-lint: echo 'Running JS linter…' [group('rust recipes')] [group('lint')] rust-lint: echo 'Running Rust linter…' [group('lint')] cpp-lint: echo 'Running C++ linter…' # not in any group email-everyone: echo 'Sending mass email…' ``` Recipes are listed by group: ``` $ just --list Available recipes: email-everyone # not in any group [lint] cpp-lint js-lint rust-lint [rust recipes] rust-lint ``` `just --list --unsorted` prints recipes in their justfile order within each group: ``` $ just --list --unsorted Available recipes: (no group) email-everyone # not in any group [lint] js-lint rust-lint cpp-lint [rust recipes] rust-lint ``` Groups can be listed with `--groups`: ``` $ just --groups Recipe groups: lint rust recipes ``` Use `just --groups --unsorted` to print groups in their justfile order. ### Command Evaluation Using Backticks Backticks can be used to store the result of commands: ```just localhost := `dumpinterfaces | cut -d: -f2 | sed 's/\/.*//' | sed 's/ //g'` serve: ./serve {{localhost}} 8080 ``` Indented backticks, delimited by three backticks, are de-indented in the same manner as indented strings: ````just # This backtick evaluates the command `echo foo\necho bar\n`, which produces the value `foo\nbar\n`. stuff := ``` echo foo echo bar ``` ```` See the [Strings](#strings) section for details on unindenting. Backticks may not start with `#!`. This syntax is reserved for a future upgrade. The [`shell(…)` function](#external-commands) provides a more general mechanism to invoke external commands, including the ability to execute the contents of a variable as a command, and to pass arguments to a command. ### Conditional Expressions `if`/`else` expressions evaluate different branches depending on if two expressions evaluate to the same value: ```just foo := if "2" == "2" { "Good!" } else { "1984" } bar: @echo "{{foo}}" ``` ```console $ just bar Good! ``` It is also possible to test for inequality: ```just foo := if "hello" != "goodbye" { "xyz" } else { "abc" } bar: @echo {{foo}} ``` ```console $ just bar xyz ``` And match against regular expressions: ```just foo := if "hello" =~ 'hel+o' { "match" } else { "mismatch" } bar: @echo {{foo}} ``` ```console $ just bar match ``` Regular expressions are provided by the [regex crate](https://github.com/rust-lang/regex), whose syntax is documented on [docs.rs](https://docs.rs/regex/1.5.4/regex/#syntax). Since regular expressions commonly use backslash escape sequences, consider using single-quoted string literals, which will pass slashes to the regex parser unmolested. Conditional expressions short-circuit, which means they only evaluate one of their branches. This can be used to make sure that backtick expressions don't run when they shouldn't. ```just foo := if env_var("RELEASE") == "true" { `get-something-from-release-database` } else { "dummy-value" } ``` Conditionals can be used inside of recipes: ```just bar foo: echo {{ if foo == "bar" { "hello" } else { "goodbye" } }} ``` Note the space after the final `}`! Without the space, the interpolation will be prematurely closed. Multiple conditionals can be chained: ```just foo := if "hello" == "goodbye" { "xyz" } else if "a" == "a" { "abc" } else { "123" } bar: @echo {{foo}} ``` ```console $ just bar abc ``` ### Stopping execution with error Execution can be halted with the `error` function. For example: ```just foo := if "hello" == "goodbye" { "xyz" } else if "a" == "b" { "abc" } else { error("123") } ``` Which produce the following error when run: ``` error: Call to function `error` failed: 123 | 16 | error("123") ``` ### Setting Variables from the Command Line Variables can be overridden from the command line. ```just os := "linux" test: build ./test --test {{os}} build: ./build {{os}} ``` ```console $ just ./build linux ./test --test linux ``` Any number of arguments of the form `NAME=VALUE` can be passed before recipes: ```console $ just os=plan9 ./build plan9 ./test --test plan9 ``` Or you can use the `--set` flag: ```console $ just --set os bsd ./build bsd ./test --test bsd ``` ### Getting and Setting Environment Variables #### Exporting `just` Variables Assignments prefixed with the `export` keyword will be exported to recipes as environment variables: ```just export RUST_BACKTRACE := "1" test: # will print a stack trace if it crashes cargo test ``` Parameters prefixed with a `$` will be exported as environment variables: ```just test $RUST_BACKTRACE="1": # will print a stack trace if it crashes cargo test ``` Exported variables and parameters are not exported to backticks in the same scope. ```just export WORLD := "world" # This backtick will fail with "WORLD: unbound variable" BAR := `echo hello $WORLD` ``` ```just # Running `just a foo` will fail with "A: unbound variable" a $A $B=`echo $A`: echo $A $B ``` When [export](#export) is set, all `just` variables are exported as environment variables. #### Unexporting Environment Variables1.29.0 Environment variables can be unexported with the `unexport keyword`: ```just unexport FOO @foo: echo $FOO ``` ``` $ export FOO=bar $ just foo sh: FOO: unbound variable ``` #### Getting Environment Variables from the environment Environment variables from the environment are passed automatically to the recipes. ```just print_home_folder: echo "HOME is: '${HOME}'" ``` ```console $ just HOME is '/home/myuser' ``` #### Setting `just` Variables from Environment Variables Environment variables can be propagated to `just` variables using the `env()` function. See [environment-variables](#environment-variables). ### Recipe Parameters Recipes may have parameters. Here recipe `build` has a parameter called `target`: ```just build target: @echo 'Building {{target}}…' cd {{target}} && make ``` To pass arguments on the command line, put them after the recipe name: ```console $ just build my-awesome-project Building my-awesome-project… cd my-awesome-project && make ``` To pass arguments to a dependency, put the dependency in parentheses along with the arguments: ```just default: (build "main") build target: @echo 'Building {{target}}…' cd {{target}} && make ``` Variables can also be passed as arguments to dependencies: ```just target := "main" _build version: @echo 'Building {{version}}…' cd {{version}} && make build: (_build target) ``` A command's arguments can be passed to dependency by putting the dependency in parentheses along with the arguments: ```just build target: @echo "Building {{target}}…" push target: (build target) @echo 'Pushing {{target}}…' ``` Parameters may have default values: ```just default := 'all' test target tests=default: @echo 'Testing {{target}}:{{tests}}…' ./test --tests {{tests}} {{target}} ``` Parameters with default values may be omitted: ```console $ just test server Testing server:all… ./test --tests all server ``` Or supplied: ```console $ just test server unit Testing server:unit… ./test --tests unit server ``` Default values may be arbitrary expressions, but expressions containing the `+`, `&&`, `||`, or `/` operators must be parenthesized: ```just arch := "wasm" test triple=(arch + "-unknown-unknown") input=(arch / "input.dat"): ./test {{triple}} ``` The last parameter of a recipe may be variadic, indicated with either a `+` or a `*` before the argument name: ```just backup +FILES: scp {{FILES}} me@server.com: ``` Variadic parameters prefixed with `+` accept _one or more_ arguments and expand to a string containing those arguments separated by spaces: ```console $ just backup FAQ.md GRAMMAR.md scp FAQ.md GRAMMAR.md me@server.com: FAQ.md 100% 1831 1.8KB/s 00:00 GRAMMAR.md 100% 1666 1.6KB/s 00:00 ``` Variadic parameters prefixed with `*` accept _zero or more_ arguments and expand to a string containing those arguments separated by spaces, or an empty string if no arguments are present: ```just commit MESSAGE *FLAGS: git commit {{FLAGS}} -m "{{MESSAGE}}" ``` Variadic parameters can be assigned default values. These are overridden by arguments passed on the command line: ```just test +FLAGS='-q': cargo test {{FLAGS}} ``` `{{…}}` substitutions may need to be quoted if they contain spaces. For example, if you have the following recipe: ```just search QUERY: lynx https://www.google.com/?q={{QUERY}} ``` And you type: ```console $ just search "cat toupee" ``` `just` will run the command `lynx https://www.google.com/?q=cat toupee`, which will get parsed by `sh` as `lynx`, `https://www.google.com/?q=cat`, and `toupee`, and not the intended `lynx` and `https://www.google.com/?q=cat toupee`. You can fix this by adding quotes: ```just search QUERY: lynx 'https://www.google.com/?q={{QUERY}}' ``` Parameters prefixed with a `$` will be exported as environment variables: ```just foo $bar: echo $bar ``` ### Dependencies Dependencies run before recipes that depend on them: ```just a: b @echo A b: @echo B ``` ``` $ just a B A ``` In a given invocation of `just`, a recipe with the same arguments will only run once, regardless of how many times it appears in the command-line invocation, or how many times it appears as a dependency: ```just a: @echo A b: a @echo B c: a @echo C ``` ``` $ just a a a a a A $ just b c A B C ``` Multiple recipes may depend on a recipe that performs some kind of setup, and when those recipes run, that setup will only be performed once: ```just build: cc main.c test-foo: build ./a.out --test foo test-bar: build ./a.out --test bar ``` ``` $ just test-foo test-bar cc main.c ./a.out --test foo ./a.out --test bar ``` Recipes in a given run are only skipped when they receive the same arguments: ```just build: cc main.c test TEST: build ./a.out --test {{TEST}} ``` ``` $ just test foo test bar cc main.c ./a.out --test foo ./a.out --test bar ``` #### Running Recipes at the End of a Recipe Normal dependencies of a recipes always run before a recipe starts. That is to say, the dependee always runs before the depender. These dependencies are called "prior dependencies". A recipe can also have subsequent dependencies, which run immediately after the recipe and are introduced with an `&&`: ```just a: echo 'A!' b: a && c d echo 'B!' c: echo 'C!' d: echo 'D!' ``` …running _b_ prints: ```console $ just b echo 'A!' A! echo 'B!' B! echo 'C!' C! echo 'D!' D! ``` #### Running Recipes in the Middle of a Recipe `just` doesn't support running recipes in the middle of another recipe, but you can call `just` recursively in the middle of a recipe. Given the following `justfile`: ```just a: echo 'A!' b: a echo 'B start!' just c echo 'B end!' c: echo 'C!' ``` …running _b_ prints: ```console $ just b echo 'A!' A! echo 'B start!' B start! echo 'C!' C! echo 'B end!' B end! ``` This has limitations, since recipe `c` is run with an entirely new invocation of `just`: Assignments will be recalculated, dependencies might run twice, and command line arguments will not be propagated to the child `just` process. ### Shebang Recipes Recipes that start with `#!` are called shebang recipes, and are executed by saving the recipe body to a file and running it. This lets you write recipes in different languages: ```just polyglot: python js perl sh ruby nu python: #!/usr/bin/env python3 print('Hello from python!') js: #!/usr/bin/env node console.log('Greetings from JavaScript!') perl: #!/usr/bin/env perl print "Larry Wall says Hi!\n"; sh: #!/usr/bin/env sh hello='Yo' echo "$hello from a shell script!" nu: #!/usr/bin/env nu let hello = 'Hola' echo $"($hello) from a nushell script!" ruby: #!/usr/bin/env ruby puts "Hello from ruby!" ``` ```console $ just polyglot Hello from python! Greetings from JavaScript! Larry Wall says Hi! Yo from a shell script! Hola from a nushell script! Hello from ruby! ``` On Unix-like operating systems, including Linux and MacOS, shebang recipes are executed by saving the recipe body to a file in a temporary directory, marking the file as executable, and executing it. The OS then parses the shebang line into a command line and invokes it, including the path to the file. For example, if a recipe starts with `#!/usr/bin/env bash`, the final command that the OS runs will be something like `/usr/bin/env bash /tmp/PATH_TO_SAVED_RECIPE_BODY`. Shebang line splitting is operating system dependent. When passing a command with arguments, you may need to tell `env` to split them explicitly by using the `-S` flag: ```just run: #!/usr/bin/env -S bash -x ls ``` Windows does not support shebang lines. On Windows, `just` splits the shebang line into a command and arguments, saves the recipe body to a file, and invokes the split command and arguments, adding the path to the saved recipe body as the final argument. For example, on Windows, if a recipe starts with `#! py`, the final command the OS runs will be something like `py C:\Temp\PATH_TO_SAVED_RECIPE_BODY`. ### Python Recipes with `uv` [`uv`](https://github.com/astral-sh/uv) is an excellent cross-platform python project manager, written in Rust. Using the `[script]` attribute and `script-interpreter` setting, `just` can easily be configured to run Python recipes with `uv`: ```just set unstable set script-interpreter := ['uv', 'run', '--script'] [script] hello: print("Hello from Python!") [script] goodbye: # /// script # requires-python = ">=3.11" # dependencies=["sh"] # /// import sh print(sh.echo("Goodbye from Python!"), end='') ``` Of course, a shebang also works: ```just hello: #!/usr/bin/env uv run --script print("Hello from Python!") ``` ### Script Recipes Recipes with a `[script(COMMAND)]`1.32.0 attribute are run as scripts interpreted by `COMMAND`. This avoids some of the issues with shebang recipes, such as the use of `cygpath` on Windows, the need to use `/usr/bin/env`, and inconsistencies in shebang line splitting across Unix OSs. Recipes with an empty `[script]` attribute are executed with the value of `set script-interpreter := […]`1.33.0, defaulting to `sh -eu`, and *not* the value of `set shell`. The body of the recipe is evaluated, written to disk in the temporary directory, and run by passing its path as an argument to `COMMAND`. The `[script(…)]` attribute is unstable, so you'll need to use `set unstable`, set the `JUST_UNSTABLE` environment variable, or pass `--unstable` on the command line. ### Safer Bash Shebang Recipes If you're writing a `bash` shebang recipe, consider adding `set -euxo pipefail`: ```just foo: #!/usr/bin/env bash set -euxo pipefail hello='Yo' echo "$hello from Bash!" ``` It isn't strictly necessary, but `set -euxo pipefail` turns on a few useful features that make `bash` shebang recipes behave more like normal, linewise `just` recipe: - `set -e` makes `bash` exit if a command fails. - `set -u` makes `bash` exit if a variable is undefined. - `set -x` makes `bash` print each script line before it's run. - `set -o pipefail` makes `bash` exit if a command in a pipeline fails. This is `bash`-specific, so isn't turned on in normal linewise `just` recipes. Together, these avoid a lot of shell scripting gotchas. #### Shebang Recipe Execution on Windows On Windows, shebang interpreter paths containing a `/` are translated from Unix-style paths to Windows-style paths using `cygpath`, a utility that ships with [Cygwin](http://www.cygwin.com). For example, to execute this recipe on Windows: ```just echo: #!/bin/sh echo "Hello!" ``` The interpreter path `/bin/sh` will be translated to a Windows-style path using `cygpath` before being executed. If the interpreter path does not contain a `/` it will be executed without being translated. This is useful if `cygpath` is not available, or you wish to pass a Windows-style path to the interpreter. ### Setting Variables in a Recipe Recipe lines are interpreted by the shell, not `just`, so it's not possible to set `just` variables in the middle of a recipe: ```justfile foo: x := "hello" # This doesn't work! echo {{x}} ``` It is possible to use shell variables, but there's another problem. Every recipe line is run by a new shell instance, so variables set in one line won't be set in the next: ```just foo: x=hello && echo $x # This works! y=bye echo $y # This doesn't, `y` is undefined here! ``` The best way to work around this is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing: ```just foo: #!/usr/bin/env bash set -euxo pipefail x=hello echo $x ``` ### Sharing Environment Variables Between Recipes Each line of each recipe is executed by a fresh shell, so it is not possible to share environment variables between recipes. #### Using Python Virtual Environments Some tools, like [Python's venv](https://docs.python.org/3/library/venv.html), require loading environment variables in order to work, making them challenging to use with `just`. As a workaround, you can execute the virtual environment binaries directly: ```just venv: [ -d foo ] || python3 -m venv foo run: venv ./foo/bin/python3 main.py ``` ### Changing the Working Directory in a Recipe Each recipe line is executed by a new shell, so if you change the working directory on one line, it won't have an effect on later lines: ```just foo: pwd # This `pwd` will print the same directory… cd bar pwd # …as this `pwd`! ``` There are a couple ways around this. One is to call `cd` on the same line as the command you want to run: ```just foo: cd bar && pwd ``` The other is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing, and thus a `cd` on one line will affect later lines, just like a shell script: ```just foo: #!/usr/bin/env bash set -euxo pipefail cd bar pwd ``` ### Indentation Recipe lines can be indented with spaces or tabs, but not a mix of both. All of a recipe's lines must have the same type of indentation, but different recipes in the same `justfile` may use different indentation. Each recipe must be indented at least one level from the `recipe-name` but after that may be further indented. Here's a justfile with a recipe indented with spaces, represented as `·`, and tabs, represented as `→`. ```justfile set windows-shell := ["pwsh", "-NoLogo", "-NoProfileLoadTime", "-Command"] set ignore-comments list-space directory: ··#!pwsh ··foreach ($item in $(Get-ChildItem {{directory}} )) { ····echo $item.Name ··} ··echo "" # indentation nesting works even when newlines are escaped list-tab directory: → @foreach ($item in $(Get-ChildItem {{directory}} )) { \ → → echo $item.Name \ → } → @echo "" ``` ```pwsh PS > just list-space ~ Desktop Documents Downloads PS > just list-tab ~ Desktop Documents Downloads ``` ### Multi-Line Constructs Recipes without an initial shebang are evaluated and run line-by-line, which means that multi-line constructs probably won't do what you want. For example, with the following `justfile`: ```justfile conditional: if true; then echo 'True!' fi ``` The extra leading whitespace before the second line of the `conditional` recipe will produce a parse error: ```console $ just conditional error: Recipe line has extra leading whitespace | 3 | echo 'True!' | ^^^^^^^^^^^^^^^^ ``` To work around this, you can write conditionals on one line, escape newlines with slashes, or add a shebang to your recipe. Some examples of multi-line constructs are provided for reference. #### `if` statements ```just conditional: if true; then echo 'True!'; fi ``` ```just conditional: if true; then \ echo 'True!'; \ fi ``` ```just conditional: #!/usr/bin/env sh if true; then echo 'True!' fi ``` #### `for` loops ```just for: for file in `ls .`; do echo $file; done ``` ```just for: for file in `ls .`; do \ echo $file; \ done ``` ```just for: #!/usr/bin/env sh for file in `ls .`; do echo $file done ``` #### `while` loops ```just while: while `server-is-dead`; do ping -c 1 server; done ``` ```just while: while `server-is-dead`; do \ ping -c 1 server; \ done ``` ```just while: #!/usr/bin/env sh while `server-is-dead`; do ping -c 1 server done ``` #### Outside Recipe Bodies Parenthesized expressions can span multiple lines: ```just abc := ('a' + 'b' + 'c') abc2 := ( 'a' + 'b' + 'c' ) foo param=('foo' + 'bar' ): echo {{param}} bar: (foo 'Foo' ) echo 'Bar!' ``` Lines ending with a backslash continue on to the next line as if the lines were joined by whitespace1.15.0: ```just a := 'foo' + \ 'bar' foo param1 \ param2='foo' \ *varparam='': dep1 \ (dep2 'foo') echo {{param1}} {{param2}} {{varparam}} dep1: \ # this comment is not part of the recipe body echo 'dep1' dep2 \ param: echo 'Dependency with parameter {{param}}' ``` Backslash line continuations can also be used in interpolations. The line following the backslash must be indented. ```just recipe: echo '{{ \ "This interpolation " + \ "has a lot of text." \ }}' echo 'back to recipe body' ``` ### Command Line Options `just` supports a number of useful command line options for listing, dumping, and debugging recipes and variables: ```console $ just --list Available recipes: js perl polyglot python ruby $ just --show perl perl: #!/usr/bin/env perl print "Larry Wall says Hi!\n"; $ just --show polyglot polyglot: python js perl sh ruby ``` Some command-line options can be set with environment variables. For example: ```console $ export JUST_UNSTABLE=1 $ just ``` Is equivalent to: ```console $ just --unstable ``` Consult `just --help` to see which options can be set from environment variables. ### Private Recipes Recipes and aliases whose name starts with a `_` are omitted from `just --list`: ```just test: _test-helper ./bin/test _test-helper: ./bin/super-secret-test-helper-stuff ``` ```console $ just --list Available recipes: test ``` And from `just --summary`: ```console $ just --summary test ``` The `[private]` attribute1.10.0 may also be used to hide recipes or aliases without needing to change the name: ```just [private] foo: [private] alias b := bar bar: ``` ```console $ just --list Available recipes: bar ``` This is useful for helper recipes which are only meant to be used as dependencies of other recipes. ### Quiet Recipes A recipe name may be prefixed with `@` to invert the meaning of `@` before each line: ```just @quiet: echo hello echo goodbye @# all done! ``` Now only the lines starting with `@` will be echoed: ```console $ just quiet hello goodbye # all done! ``` All recipes in a Justfile can be made quiet with `set quiet`: ```just set quiet foo: echo "This is quiet" @foo2: echo "This is also quiet" ``` The `[no-quiet]` attribute overrides this setting: ```just set quiet foo: echo "This is quiet" [no-quiet] foo2: echo "This is not quiet" ``` Shebang recipes are quiet by default: ```just foo: #!/usr/bin/env bash echo 'Foo!' ``` ```console $ just foo Foo! ``` Adding `@` to a shebang recipe name makes `just` print the recipe before executing it: ```just @bar: #!/usr/bin/env bash echo 'Bar!' ``` ```console $ just bar #!/usr/bin/env bash echo 'Bar!' Bar! ``` `just` normally prints error messages when a recipe line fails. These error messages can be suppressed using the `[no-exit-message]`1.7.0 attribute. You may find this especially useful with a recipe that wraps a tool: ```just git *args: @git {{args}} ``` ```console $ just git status fatal: not a git repository (or any of the parent directories): .git error: Recipe `git` failed on line 2 with exit code 128 ``` Add the attribute to suppress the exit error message when the tool exits with a non-zero code: ```just [no-exit-message] git *args: @git {{args}} ``` ```console $ just git status fatal: not a git repository (or any of the parent directories): .git ``` ### Selecting Recipes to Run With an Interactive Chooser The `--choose` subcommand makes `just` invoke a chooser to select which recipes to run. Choosers should read lines containing recipe names from standard input and print one or more of those names separated by spaces to standard output. Because there is currently no way to run a recipe that requires arguments with `--choose`, such recipes will not be given to the chooser. Private recipes and aliases are also skipped. The chooser can be overridden with the `--chooser` flag. If `--chooser` is not given, then `just` first checks if `$JUST_CHOOSER` is set. If it isn't, then the chooser defaults to `fzf`, a popular fuzzy finder. Arguments can be included in the chooser, i.e. `fzf --exact`. The chooser is invoked in the same way as recipe lines. For example, if the chooser is `fzf`, it will be invoked with `sh -cu 'fzf'`, and if the shell, or the shell arguments are overridden, the chooser invocation will respect those overrides. If you'd like `just` to default to selecting recipes with a chooser, you can use this as your default recipe: ```just default: @just --choose ``` ### Invoking `justfile`s in Other Directories If the first argument passed to `just` contains a `/`, then the following occurs: 1. The argument is split at the last `/`. 2. The part before the last `/` is treated as a directory. `just` will start its search for the `justfile` there, instead of in the current directory. 3. The part after the last slash is treated as a normal argument, or ignored if it is empty. This may seem a little strange, but it's useful if you wish to run a command in a `justfile` that is in a subdirectory. For example, if you are in a directory which contains a subdirectory named `foo`, which contains a `justfile` with the recipe `build`, which is also the default recipe, the following are all equivalent: ```console $ (cd foo && just build) $ just foo/build $ just foo/ ``` Additional recipes after the first are sought in the same `justfile`. For example, the following are both equivalent: ```console $ just foo/a b $ (cd foo && just a b) ``` And will both invoke recipes `a` and `b` in `foo/justfile`. ### Imports One `justfile` can include the contents of another using `import` statements. If you have the following `justfile`: ```justfile import 'foo/bar.just' a: b @echo A ``` And the following text in `foo/bar.just`: ```just b: @echo B ``` `foo/bar.just` will be included in `justfile` and recipe `b` will be defined: ```console $ just b B $ just a B A ``` The `import` path can be absolute or relative to the location of the justfile containing it. A leading `~/` in the import path is replaced with the current users home directory. Justfiles are insensitive to order, so included files can reference variables and recipes defined after the `import` statement. Imported files can themselves contain `import`s, which are processed recursively. `allow-duplicate-recipes` and `allow-duplicate-variables` allow duplicate recipes and variables, respectively, to override each other, instead of producing an error. Within a module, later definitions override earlier definitions: ```just set allow-duplicate-recipes foo: foo: echo 'yes' ``` When `import`s are involved, things unfortunately get much more complicated and hard to explain. Shallower definitions always override deeper definitions, so recipes at the top level will override recipes in imports, and recipes in an import will override recipes in an import which itself imports those recipes. When two duplicate definitions are imported and are at the same depth, the one from the earlier import will override the one from the later import. This is because `just` uses a stack when processing imports, pushing imports onto the stack in source-order, and always processing the top of the stack next, so earlier imports are actually handled later by the compiler. This is definitely a bug, but since `just` has very strong backwards compatibility guarantees and we take enormous pains not to break anyone's `justfile`, we have created issue #2540 to discuss whether or not we can actually fix it. Imports may be made optional by putting a `?` after the `import` keyword: ```just import? 'foo/bar.just' ``` Importing the same source file multiple times is not an error1.37.0. This allows importing multiple justfiles, for example `foo.just` and `bar.just`, which both import a third justfile containing shared recipes, for example `baz.just`, without the duplicate import of `baz.just` being an error: ```justfile # justfile import 'foo.just' import 'bar.just' ``` ```justfile # foo.just import 'baz.just' foo: baz ``` ```justfile # bar.just import 'baz.just' bar: baz ``` ```just # baz baz: ``` ### Modules1.19.0 A `justfile` can declare modules using `mod` statements. `mod` statements were stabilized in `just`1.31.0. In earlier versions, you'll need to use the `--unstable` flag, `set unstable`, or set the `JUST_UNSTABLE` environment variable to use them. If you have the following `justfile`: ```justfile mod bar a: @echo A ``` And the following text in `bar.just`: ```just b: @echo B ``` `bar.just` will be included in `justfile` as a submodule. Recipes, aliases, and variables defined in one submodule cannot be used in another, and each module uses its own settings. Recipes in submodules can be invoked as subcommands: ```console $ just bar b B ``` Or with path syntax: ```console $ just bar::b B ``` If a module is named `foo`, just will search for the module file in `foo.just`, `foo/mod.just`, `foo/justfile`, and `foo/.justfile`. In the latter two cases, the module file may have any capitalization. Module statements may be of the form: ```justfile mod foo 'PATH' ``` Which loads the module's source file from `PATH`, instead of from the usual locations. A leading `~/` in `PATH` is replaced with the current user's home directory. `PATH` may point to the module source file itself, or to a directory containing the module source file with the name `mod.just`, `justfile`, or `.justfile`. In the latter two cases, the module file may have any capitalization. Environment files are only loaded for the root justfile, and loaded environment variables are available in submodules. Settings in submodules that affect environment file loading are ignored. Recipes in submodules without the `[no-cd]` attribute run with the working directory set to the directory containing the submodule source file. `justfile()` and `justfile_directory()` always return the path to the root justfile and the directory that contains it, even when called from submodule recipes. Modules may be made optional by putting a `?` after the `mod` keyword: ```just mod? foo ``` Missing source files for optional modules do not produce an error. Optional modules with no source file do not conflict, so you can have multiple mod statements with the same name, but with different source file paths, as long as at most one source file exists: ```just mod? foo 'bar.just' mod? foo 'baz.just' ``` Modules may be given doc comments which appear in `--list` output1.30.0: ```justfile # foo is a great module! mod foo ``` ```console $ just --list Available recipes: foo ... # foo is a great module! ``` Modules are still missing a lot of features, for example, the ability to depend on recipes and refer to variables in other modules. See the [module improvement tracking issue](https://github.com/casey/just/issues/2252) for more information. ### Hiding `justfile`s `just` looks for `justfile`s named `justfile` and `.justfile`, which can be used to keep a `justfile` hidden. ### Just Scripts By adding a shebang line to the top of a `justfile` and making it executable, `just` can be used as an interpreter for scripts: ```console $ cat > script < formatted-justfile ``` The `--dump` command can be used with `--dump-format json` to print a JSON representation of a `justfile`. ### Fallback to parent `justfile`s If a recipe is not found in a `justfile` and the `fallback` setting is set, `just` will look for `justfile`s in the parent directory and up, until it reaches the root directory. `just` will stop after it reaches a `justfile` in which the `fallback` setting is `false` or unset. As an example, suppose the current directory contains this `justfile`: ```just set fallback foo: echo foo ``` And the parent directory contains this `justfile`: ```just bar: echo bar ``` ```console $ just bar Trying ../justfile echo bar bar ``` ### Avoiding Argument Splitting Given this `justfile`: ```just foo argument: touch {{argument}} ``` The following command will create two files, `some` and `argument.txt`: ```console $ just foo "some argument.txt" ``` The user's shell will parse `"some argument.txt"` as a single argument, but when `just` replaces `touch {{argument}}` with `touch some argument.txt`, the quotes are not preserved, and `touch` will receive two arguments. There are a few ways to avoid this: quoting, positional arguments, and exported arguments. #### Quoting Quotes can be added around the `{{argument}}` interpolation: ```just foo argument: touch '{{argument}}' ``` This preserves `just`'s ability to catch variable name typos before running, for example if you were to write `{{argument}}`, but will not do what you want if the value of `argument` contains single quotes. #### Positional Arguments The `positional-arguments` setting causes all arguments to be passed as positional arguments, allowing them to be accessed with `$1`, `$2`, …, and `$@`, which can be then double-quoted to avoid further splitting by the shell: ```just set positional-arguments foo argument: touch "$1" ``` This defeats `just`'s ability to catch typos, for example if you type `$2` instead of `$1`, but works for all possible values of `argument`, including those with double quotes. #### Exported Arguments All arguments are exported when the `export` setting is set: ```just set export foo argument: touch "$argument" ``` Or individual arguments may be exported by prefixing them with `$`: ```just foo $argument: touch "$argument" ``` This defeats `just`'s ability to catch typos, for example if you type `$argument`, but works for all possible values of `argument`, including those with double quotes. ### Configuring the Shell There are a number of ways to configure the shell for linewise recipes, which are the default when a recipe does not start with a `#!` shebang. Their precedence, from highest to lowest, is: 1. The `--shell` and `--shell-arg` command line options. Passing either of these will cause `just` to ignore any settings in the current justfile. 2. `set windows-shell := [...]` 3. `set windows-powershell` (deprecated) 4. `set shell := [...]` Since `set windows-shell` has higher precedence than `set shell`, you can use `set windows-shell` to pick a shell on Windows, and `set shell` to pick a shell for all other platforms. ### Timestamps `just` can print timestamps before each recipe commands: ```just recipe: echo one sleep 2 echo two ``` ``` $ just --timestamp recipe [07:28:46] echo one one [07:28:46] sleep 2 [07:28:48] echo two two ``` By default, timestamps are formatted as `HH:MM:SS`. The format can be changed with `--timestamp-format`: ``` $ just --timestamp recipe --timestamp-format '%H:%M:%S%.3f %Z' [07:32:11:.349 UTC] echo one one [07:32:11:.350 UTC] sleep 2 [07:32:13:.352 UTC] echo two two ``` The argument to `--timestamp-format` is a `strftime`-style format string, see the [`chrono` library docs](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) for details. Changelog --------- A changelog for the latest release is available in [CHANGELOG.md](https://raw.githubusercontent.com/casey/just/master/CHANGELOG.md). Changelogs for previous releases are available on [the releases page](https://github.com/casey/just/releases). `just --changelog` can also be used to make a `just` binary print its changelog. Miscellanea ----------- ### Re-running recipes when files change [`watchexec`](https://github.com/mattgreen/watchexec) can re-run any command when files change. To re-run the recipe `foo` when any file changes: ```console watchexec just foo ``` See `watchexec --help` for more info, including how to specify which files should be watched for changes. ### Running tasks in parallel GNU parallel can be used to run tasks concurrently: ```just parallel: #!/usr/bin/env -S parallel --shebang --ungroup --jobs {{ num_cpus() }} echo task 1 start; sleep 3; echo task 1 done echo task 2 start; sleep 3; echo task 2 done echo task 3 start; sleep 3; echo task 3 done echo task 4 start; sleep 3; echo task 4 done ``` ### Shell Alias For lightning-fast command running, put `alias j=just` in your shell's configuration file. In `bash`, the aliased command may not keep the shell completion functionality described in the next section. Add the following line to your `.bashrc` to use the same completion function as `just` for your aliased command: ```console complete -F _just -o bashdefault -o default j ``` ### Shell Completion Scripts Shell completion scripts for Bash, Elvish, Fish, Nushell, PowerShell, and Zsh are available [release archives](https://github.com/casey/just/releases). The `just` binary can also generate the same completion scripts at runtime using `just --completions SHELL`: ```console $ just --completions zsh > just.zsh ``` Please refer to your shell's documentation for how to install them. *macOS Note:* Recent versions of macOS use zsh as the default shell. If you use Homebrew to install `just`, it will automatically install the most recent copy of the zsh completion script in the Homebrew zsh directory, which the built-in version of zsh doesn't know about by default. It's best to use this copy of the script if possible, since it will be updated whenever you update `just` via Homebrew. Also, many other Homebrew packages use the same location for completion scripts, and the built-in zsh doesn't know about those either. To take advantage of `just` completion in zsh in this scenario, you can set `fpath` to the Homebrew location before calling `compinit`. Note also that Oh My Zsh runs `compinit` by default. So your `.zshrc` file could look like this: ```zsh # Init Homebrew, which adds environment variables eval "$(brew shellenv)" fpath=($HOMEBREW_PREFIX/share/zsh/site-functions $fpath) # Then choose one of these options: # 1. If you're using Oh My Zsh, you can initialize it here # source $ZSH/oh-my-zsh.sh # 2. Otherwise, run compinit yourself # autoload -U compinit # compinit ``` ### Man Page `just` can print its own man page with `just --man`. Man pages are written in [`roff`](https://en.wikipedia.org/wiki/Roff_%28software%29), a venerable markup language and one of the first practical applications of Unix. If you have [`groff`](https://www.gnu.org/software/groff/) installed you can view the man page with `just --man | groff -mandoc -Tascii | less`. ### Grammar A non-normative grammar of `justfile`s can be found in [GRAMMAR.md](https://github.com/casey/just/blob/master/GRAMMAR.md). ### just.sh Before `just` was a fancy Rust program it was a tiny shell script that called `make`. You can find the old version in [contrib/just.sh](https://github.com/casey/just/blob/master/contrib/just.sh). ### Global and User `justfile`s If you want some recipes to be available everywhere, you have a few options. #### Global Justfile `just --global-justfile`, or `just -g` for short, searches the following paths, in-order, for a justfile: - `$XDG_CONFIG_HOME/just/justfile` - `$HOME/.config/just/justfile` - `$HOME/justfile` - `$HOME/.justfile` You can put recipes that are used across many projects in a global justfile to easily invoke them from any directory. #### User justfile tips You can also adopt some of the following workflows. These tips assume you've created a `justfile` at `~/.user.justfile`, but you can put this `justfile` at any convenient path on your system. ##### Recipe Aliases If you want to call the recipes in `~/.user.justfile` by name, and don't mind creating an alias for every recipe, add the following to your shell's initialization script: ```console for recipe in `just --justfile ~/.user.justfile --summary`; do alias $recipe="just --justfile ~/.user.justfile --working-directory . $recipe" done ``` Now, if you have a recipe called `foo` in `~/.user.justfile`, you can just type `foo` at the command line to run it. It took me way too long to realize that you could create recipe aliases like this. Notwithstanding my tardiness, I am very pleased to bring you this major advance in `justfile` technology. ##### Forwarding Alias If you'd rather not create aliases for every recipe, you can create a single alias: ```console alias .j='just --justfile ~/.user.justfile --working-directory .' ``` Now, if you have a recipe called `foo` in `~/.user.justfile`, you can just type `.j foo` at the command line to run it. I'm pretty sure that nobody actually uses this feature, but it's there. ¯\\\_(ツ)\_/¯ ##### Customization You can customize the above aliases with additional options. For example, if you'd prefer to have the recipes in your `justfile` run in your home directory, instead of the current directory: ```console alias .j='just --justfile ~/.user.justfile --working-directory ~' ``` ### Node.js `package.json` Script Compatibility The following export statement gives `just` recipes access to local Node module binaries, and makes `just` recipe commands behave more like `script` entries in Node.js `package.json` files: ```just export PATH := "./node_modules/.bin:" + env_var('PATH') ``` ### Paths on Windows On Windows, all functions that return paths, except `invocation_directory()` will return `\`-separated paths. When not using PowerShell or `cmd.exe` these paths should be quoted to prevent the `\`s from being interpreted as character escapes: ```just ls: echo '{{absolute_path(".")}}' ``` `cygpath.exe` is an executable included in some distributions of Unix userlands for Windows, including [Cygwin](https://www.cygwin.com/) and [Git](https://git-scm.com/downloads) for Windows. `just` uses `cygpath.exe` in two places: For backwards compatibility, `invocation_directory()`, uses `cygpath.exe` to convert the invocation directory into a unix-style `/`-separated path. Use `invocation_directory_native()` to get the native, Windows-style path. On unix, `invocation_directory()` and `invocation_directory_native()` both return the same unix-style path. `cygpath.exe` is used also used to convert Unix-style shebang lines into Windows paths. As an alternative, the `[script]` attribute, currently unstable, can be used, which does not depend on `cygpath.exe`. If `cygpath.exe` is available, you can use it to convert between path styles: ```just foo_unix := '/hello/world' foo_windows := shell('cygpath --windows $1', foo_unix) bar_windows := 'C:\hello\world' bar_unix := shell('cygpath --unix $1', bar_windows) ``` ### Remote Justfiles If you wish to include a `mod` or `import` source file in many `justfiles` without needing to duplicate it, you can use an optional `mod` or `import`, along with a recipe to fetch the module source: ```just import? 'foo.just' fetch: curl https://raw.githubusercontent.com/casey/just/master/justfile > foo.just ``` Given the above `justfile`, after running `just fetch`, the recipes in `foo.just` will be available. ### Printing Complex Strings `echo` can be used to print strings, but because it processes escape sequences, like `\n`, and different implementations of `echo` recognize different escape sequences, using `printf` is often a better choice. `printf` takes a C-style format string and any number of arguments, which are interpolated into the format string. This can be combined with indented, triple quoted strings to emulate shell heredocs. Substitution complex strings into recipe bodies with `{…}` can also lead to trouble as it may be split by the shell into multiple arguments depending on the presence of whitespace and quotes. Exporting complex strings as environment variables and referring to them with `"$NAME"`, note the double quotes, can also help. Putting all this together, to print a string verbatim to standard output, with all its various escape sequences and quotes undisturbed: ```just export FOO := ''' a complicated string with some dis\tur\bi\ng escape sequences and "quotes" of 'different' kinds ''' bar: printf %s "$FOO" ``` ### Alternatives and Prior Art There is no shortage of command runners! Some more or less similar alternatives to `just` include: - [make](https://en.wikipedia.org/wiki/Make_(software)): The Unix build tool that inspired `just`. There are a few different modern day descendents of the original `make`, including [FreeBSD Make](https://www.freebsd.org/cgi/man.cgi?make(1)) and [GNU Make](https://www.gnu.org/software/make/). - [task](https://github.com/go-task/task): A YAML-based command runner written in Go. - [maid](https://github.com/egoist/maid): A Markdown-based command runner written in JavaScript. - [microsoft/just](https://github.com/microsoft/just): A JavaScript-based command runner written in JavaScript. - [cargo-make](https://github.com/sagiegurari/cargo-make): A command runner for Rust projects. - [mmake](https://github.com/tj/mmake): A wrapper around `make` with a number of improvements, including remote includes. - [robo](https://github.com/tj/robo): A YAML-based command runner written in Go. - [mask](https://github.com/jakedeichert/mask): A Markdown-based command runner written in Rust. - [makesure](https://github.com/xonixx/makesure): A simple and portable command runner written in AWK and shell. - [haku](https://github.com/VladimirMarkelov/haku): A make-like command runner written in Rust. Contributing ------------ `just` welcomes your contributions! `just` is released under the maximally permissive [CC0](https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt) public domain dedication and fallback license, so your changes must also be released under this license. ### Getting Started `just` is written in Rust. Use [rustup](https://www.rust-lang.org/tools/install) to install a Rust toolchain. `just` is extensively tested. All new features must be covered by unit or integration tests. Unit tests are under [src](https://github.com/casey/just/blob/master/src), live alongside the code being tested, and test code in isolation. Integration tests are in the [tests directory](https://github.com/casey/just/blob/master/tests) and test the `just` binary from the outside by invoking `just` on a given `justfile` and set of command-line arguments, and checking the output. You should write whichever type of tests are easiest to write for your feature while still providing good test coverage. Unit tests are useful for testing new Rust functions that are used internally and as an aid for development. A good example are the unit tests which cover the [`unindent()` function](https://github.com/casey/just/blob/master/src/unindent.rs), used to unindent triple-quoted strings and backticks. `unindent()` has a bunch of tricky edge cases which are easy to exercise with unit tests that call `unindent()` directly. Integration tests are useful for making sure that the final behavior of the `just` binary is correct. `unindent()` is also covered by integration tests which make sure that evaluating a triple-quoted string produces the correct unindented value. However, there are not integration tests for all possible cases. These are covered by faster, more concise unit tests that call `unindent()` directly. Integration tests use the `Test` struct, a builder which allows for easily invoking `just` with a given `justfile`, arguments, and environment variables, and checking the program's stdout, stderr, and exit code . ### Contribution Workflow 1. Make sure the feature is wanted. There should be an open issue about the feature with a comment from [@casey](https://github.com/casey) saying that it's a good idea or seems reasonable. If there isn't, open a new issue and ask for feedback. There are lots of good features which can't be merged, either because they aren't backwards compatible, have an implementation which would overcomplicate the codebase, or go against `just`'s design philosophy. 2. Settle on the design of the feature. If the feature has multiple possible implementations or syntaxes, make sure to nail down the details in the issue. 3. Clone `just` and start hacking. The best workflow is to have the code you're working on in an editor alongside a job that re-runs tests whenever a file changes. You can run such a job by installing [cargo-watch](https://github.com/watchexec/cargo-watch) with `cargo install cargo-watch` and running `just watch test`. 4. Add a failing test for your feature. Most of the time this will be an integration test which exercises the feature end-to-end. Look for an appropriate file to put the test in in [tests](https://github.com/casey/just/blob/master/tests), or add a new file in [tests](https://github.com/casey/just/blob/master/tests) and add a `mod` statement importing that file in [tests/lib.rs](https://github.com/casey/just/blob/master/tests/lib.rs). 5. Implement the feature. 6. Run `just ci` to make sure that all tests, lints, and checks pass. 7. Open a PR with the new code that is editable by maintainers. PRs often require rebasing and minor tweaks. If the PR is not editable by maintainers, each rebase and tweak will require a round trip of code review. Your PR may be summarily closed if it is not editable by maintainers. 8. Incorporate feedback. 9. Enjoy the sweet feeling of your PR getting merged! Feel free to open a draft PR at any time for discussion and feedback. ### Hints Here are some hints to get you started with specific kinds of new features, which you can use in addition to the contribution workflow above. #### Adding a New Attribute 1. Write a new integration test in [tests/attributes.rs](https://github.com/casey/just/blob/master/tests/attributes.rs). 2. Add a new variant to the [`Attribute`](https://github.com/casey/just/blob/master/src/attribute.rs) enum. 3. Implement the functionality of the new attribute. 4. Run `just ci` to make sure that all tests pass. ### Janus [Janus](https://github.com/casey/janus) is a tool for checking whether a change to `just` breaks or changes the interpretation of existing `justfile`s. It collects and analyzes public `justfile`s on GitHub. Before merging a particularly large or gruesome change, Janus should be run to make sure that nothing breaks. Don't worry about running Janus yourself, Casey will happily run it for you on changes that need it. ### Minimum Supported Rust Version The minimum supported Rust version, or MSRV, is current stable Rust. It may build on older versions of Rust, but this is not guaranteed. ### New Releases New releases of `just` are made frequently so that users quickly get access to new features. Release commit messages use the following template: ``` Release x.y.z - Bump version: x.y.z → x.y.z - Update changelog - Update changelog contributor credits - Update dependencies - Update version references in readme ``` Frequently Asked Questions -------------------------- ### What are the idiosyncrasies of Make that Just avoids? `make` has some behaviors which are confusing, complicated, or make it unsuitable for use as a general command runner. One example is that under some circumstances, `make` won't actually run the commands in a recipe. For example, if you have a file called `test` and the following makefile: ```just test: ./test ``` `make` will refuse to run your tests: ```console $ make test make: `test' is up to date. ``` `make` assumes that the `test` recipe produces a file called `test`. Since this file exists and the recipe has no other dependencies, `make` thinks that it doesn't have anything to do and exits. To be fair, this behavior is desirable when using `make` as a build system, but not when using it as a command runner. You can disable this behavior for specific targets using `make`'s built-in [`.PHONY` target name](https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html), but the syntax is verbose and can be hard to remember. The explicit list of phony targets, written separately from the recipe definitions, also introduces the risk of accidentally defining a new non-phony target. In `just`, all recipes are treated as if they were phony. Other examples of `make`'s idiosyncrasies include the difference between `=` and `:=` in assignments, the confusing error messages that are produced if you mess up your makefile, needing `$$` to use environment variables in recipes, and incompatibilities between different flavors of `make`. ### What's the relationship between Just and Cargo build scripts? [`cargo` build scripts](http://doc.crates.io/build-script.html) have a pretty specific use, which is to control how `cargo` builds your Rust project. This might include adding flags to `rustc` invocations, building an external dependency, or running some kind of codegen step. `just`, on the other hand, is for all the other miscellaneous commands you might run as part of development. Things like running tests in different configurations, linting your code, pushing build artifacts to a server, removing temporary files, and the like. Also, although `just` is written in Rust, it can be used regardless of the language or build system your project uses. Further Ramblings ----------------- I personally find it very useful to write a `justfile` for almost every project, big or small. On a big project with multiple contributors, it's very useful to have a file with all the commands needed to work on the project close at hand. There are probably different commands to test, build, lint, deploy, and the like, and having them all in one place is useful and cuts down on the time you have to spend telling people which commands to run and how to type them. And, with an easy place to put commands, it's likely that you'll come up with other useful things which are part of the project's collective wisdom, but which aren't written down anywhere, like the arcane commands needed for some part of your revision control workflow, to install all your project's dependencies, or all the random flags you might need to pass to the build system. Some ideas for recipes: - Deploying/publishing the project - Building in release mode vs debug mode - Running in debug mode or with logging enabled - Complex git workflows - Updating dependencies - Running different sets of tests, for example fast tests vs slow tests, or running them with verbose output - Any complex set of commands that you really should write down somewhere, if only to be able to remember them Even for small, personal projects it's nice to be able to remember commands by name instead of ^Reverse searching your shell history, and it's a huge boon to be able to go into an old project written in a random language with a mysterious build system and know that all the commands you need to do whatever you need to do are in the `justfile`, and that if you type `just` something useful (or at least interesting!) will probably happen. For ideas for recipes, check out [this project's `justfile`](https://github.com/casey/just/blob/master/justfile), or some of the `justfile`s [out in the wild](https://github.com/search?q=path%3A**%2Fjustfile&type=code). Anyways, I think that's about it for this incredibly long-winded README. I hope you enjoy using `just` and find great success and satisfaction in all your computational endeavors! 😸 just-1.40.0/README.中文.md000064400000000000000000002261131046102023000143510ustar 00000000000000↖️ 目录

just

crates.io version build status downloads chat on discord say thanks

`just` 为您提供一种保存和运行项目特有命令的便捷方式。 本指南同时也可以以 [书](https://just.systems/man/zh/) 的形式提供在线阅读。 命令,在此也称为配方,存储在一个名为 `justfile` 的文件中,其语法受 `make` 启发: ![screenshot](https://raw.githubusercontent.com/casey/just/master/screenshot.png) 然后你可以用 `just RECIPE` 运行它们: ```sh $ just test-all cc *.c -o main ./test --all Yay, all your tests passed! ``` `just` 有很多很棒的特性,而且相比 `make` 有很多改进: - `just` 是一个命令运行器,而不是一个构建系统,所以它避免了许多 [`make` 的复杂性和特异性](#just-避免了-make-的哪些特异性)。不需要 `.PHONY` 配方! - 支持 Linux、MacOS 和 Windows,而且无需额外的依赖。(尽管如果你的系统没有 `sh`,你需要 [选择一个不同的 Shell](#shell))。 - 错误具体且富有参考价值,语法错误将会与产生它们的上下文一起被报告。 - 配方可以接受 [命令行参数](#配方参数)。 - 错误会尽可能被静态地解决。未知的配方和循环依赖关系会在运行之前被报告。 - `just` 可以 [加载`.env`文件](#环境变量加载),简化环境变量注入。 - 配方可以在 [命令行中列出](#列出可用的配方)。 - 命令行自动补全脚本 [支持大多数流行的 Shell](#shell-自动补全脚本)。 - 配方可以用 [任意语言](#用其他语言书写配方) 编写,如 Python 或 NodeJS。 - `just` 可以从任何子目录中调用,而不仅仅是包含 `justfile` 的目录。 - 不仅如此,还有 [更多](https://just.systems/man/zh/)! 如果你在使用 `just` 方面需要帮助,请随时创建一个 Issue 或在 [Discord](https://discord.gg/ezYScXR) 上与我联系。我们随时欢迎功能请求和错误报告! 安装 ------------ ### 预备知识 `just` 应该可以在任何有合适的 `sh` 的系统上运行,包括 Linux、MacOS 和 BSD。 在 Windows 上,`just` 可以使用 [Git for Windows](https://git-scm.com)、[GitHub Desktop](https://desktop.github.com) 或 [Cygwin](http://www.cygwin.com) 所提供的 `sh`。 如果你不愿意安装 `sh`,也可以使用 `shell` 设置来指定你要使用的 Shell。 比如 PowerShell: ```just # 使用 PowerShell 替代 sh: set shell := ["powershell.exe", "-c"] hello: Write-Host "Hello, world!" ``` …或者 `cmd.exe`: ```just # 使用 cmd.exe 替代 sh: set shell := ["cmd.exe", "/c"] list: dir ``` 你也可以使用命令行参数来设置 Shell。例如,若要使用 PowerShell 也可以用 `--shell powershell.exe --shell-arg -c` 启动`just`。 (PowerShell 默认安装在 Windows 7 SP1 和 Windows Server 2008 R2 S1 及更高版本上,而 `cmd.exe` 相当麻烦,所以 PowerShell 被推荐给大多数 Windows 用户) ### 安装包
操作系统 包管理器 安装包 命令
Various Cargo just cargo install just
Microsoft Windows Scoop just scoop install just
Various Homebrew just brew install just
macOS MacPorts just port install just
Arch Linux pacman just pacman -S just
Various Nix just nix-env -iA nixpkgs.just
NixOS Nix just nix-env -iA nixos.just
Solus eopkg just eopkg install just
Void Linux XBPS just xbps-install -S just
FreeBSD pkg just pkg install just
Alpine Linux apk-tools just apk add just
Fedora Linux DNF just dnf install just
Gentoo Linux Portage guru/sys-devel/just eselect repository enable guru
emerge --sync guru
emerge sys-devel/just
Various Conda just conda install -c conda-forge just
Microsoft Windows Chocolatey just choco install just
Various Snap just snap install --edge --classic just
Various asdf just asdf plugin add just
asdf install just <version>
Various PyPI rust-just pipx install rust-just
Various npm rust-just npm install -g rust-just
Debian and Ubuntu derivatives MPR just git clone 'https://mpr.makedeb.org/just'
cd just
makedeb -si
Debian and Ubuntu derivatives Prebuilt-MPR just You must have the Prebuilt-MPR set up on your system in order to run this command.
sudo apt install just
![package version table](https://repology.org/badge/vertical-allrepos/just.svg) ### 预制二进制文件 Linux、MacOS 和 Windows 的预制二进制文件可以在 [发布页](https://github.com/casey/just/releases) 上找到。 你也可以在 Linux、MacOS 或 Windows 上使用下面的命令来下载最新的版本,只需将 `DEST` 替换为你想安装 `just` 的目录即可: ```sh curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to DEST ``` 例如,安装 `just` 到 `~/bin` 目录: ```sh # 创建 ~/bin mkdir -p ~/bin # 下载并解压 just 到 ~/bin/just curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin # 在 Shell 搜索可执行文件的路径中添加`~/bin` # 这一行应该被添加到你的 Shell 初始化文件中,e.g. `~/.bashrc` 或者 `~/.zshrc`: export PATH="$PATH:$HOME/bin" # 现在 just 应该就可以执行了 just --help ``` ### GitHub Actions 使用 [extractions/setup-just](https://github.com/extractions/setup-just): ```yaml - uses: extractions/setup-just@v1 with: just-version: 0.8 # optional semver specification, otherwise latest ``` 使用 [taiki-e/install-action](https://github.com/taiki-e/install-action): ```yaml - uses: taiki-e/install-action@just ``` ### 发布 RSS 订阅 `just` 的发布 [RSS 订阅](https://en.wikipedia.org/wiki/RSS) 可以在 [这里](https://github.com/casey/just/releases.atom) 找到。 ### Node.js 安装 [just-install](https://npmjs.com/package/just-install) 可用于在 Node.js 应用程序中自动安装 `just`。 `just` 是一个很赞的比 npm 脚本更强大的替代品。如果你想在 Node.js 应用程序的依赖中包含 `just`,可以通过 `just-install`,它将在本机安装一个针对特定平台的二进制文件作为 `npm install` 安装结果的一部分。这样就不需要每个开发者使用上述提到的步骤独立安装 `just`。安装后,`just` 命令将在 npm 脚本或 npx 中工作。这对那些想让项目的设置过程尽可能简单的团队来说是很有用的。 想了解更多信息, 请查看 [just-install 说明文件](https://github.com/brombal/just-install#readme)。 向后兼容性 ----------------------- 随着 1.0 版本的发布,`just` 突出对向后兼容性和稳定性的强烈承诺。 未来的版本将不会引入向后不兼容的变化,不会使现有的 `justfile` 停止工作,或破坏命令行界面的正常调用。 然而,这并不排除修复全面的错误,即使这样做可能会破坏依赖其行为的 `justfiles`。 永远不会有一个 `just` 2.0。任何理想的向后兼容的变化都是在每个 `justfile` 的基础上选择性加入的,所以用户可以在他们的闲暇时间进行迁移。 还没有准备好稳定化的功能将在 `--unstable` 标志后被选择性启用。由 `--unstable` 启用的功能可能会在任何时候以不兼容的方式发生变化。 编辑器支持 -------------- `justfile` 的语法与 `make` 非常接近,你可以让你的编辑器对 `just` 使用 `make` 语法高亮。 ### Vim 和 Neovim #### `vim-just` [vim-just](https://github.com/NoahTheDuke/vim-just) 插件可以为 vim 提供 `justfile` 语法高亮显示。 你可以用你喜欢的软件包管理器安装它,如 [Plug](https://github.com/junegunn/vim-plug): ```vim call plug#begin() Plug 'NoahTheDuke/vim-just' call plug#end() ``` 或者使用 Vim 的内置包支持: ```sh mkdir -p ~/.vim/pack/vendor/start cd ~/.vim/pack/vendor/start git clone https://github.com/NoahTheDuke/vim-just.git ``` #### `tree-sitter-just` [tree-sitter-just](https://github.com/IndianBoy42/tree-sitter-just) 是一个针对 Neovim 的 [Nvim Treesitter](https://github.com/nvim-treesitter/nvim-treesitter) 插件。 #### Makefile 语法高亮 Vim 内置的 makefile 语法高亮对 `justfile` 来说并不完美,但总比没有好。你可以把以下内容放在 `~/.vim/filetype.vim` 中: ```vimscript if exists("did_load_filetypes") finish endif augroup filetypedetect au BufNewFile,BufRead justfile setf make augroup END ``` 或者在单个 `justfile` 中添加以下内容,以在每个文件的基础上启用 `make` 模式: ```text # vim: set ft=make : ``` ### Emacs [just-mode](https://github.com/leon-barrett/just-mode.el) 可以为 `justfile` 提供语法高亮和自动缩进。它可以在 [MELPA](https://melpa.org/) 上通过 [just-mode](https://melpa.org/#/just-mode) 获得。 [justl](https://github.com/psibi/justl.el) 提供了执行和列出配方的命令。 你可以在一个单独的 `justfile` 中添加以下内容,以便对每个文件启用 `make` 模式: ```text # Local Variables: # mode: makefile # End: ``` ### Visual Studio Code 由 [skellock](https://github.com/skellock) 为 VS Code 提供的扩展 [可在此获得](https://marketplace.visualstudio.com/items?itemName=skellock.just)([仓库](https://github.com/skellock/vscode-just)),但是开发已经不活跃了。 你可以通过运行以下命令来安装它: ```sh code --install-extension skellock.just ``` 最近由 [sclu1034](https://github.com/sclu1034) 提供的一个更活跃的分叉可以在 [这里](https://github.com/sclu1034/vscode-just) 找到。 ### JetBrains IDEs 由 [linux_china](https://github.com/linux-china) 为 JetBrains IDEs 提供的插件可 [由此获得](https://plugins.jetbrains.com/plugin/18658-just)。 ### Kakoune Kakoune 已经内置支持 `justfile` 语法高亮,这要感谢 TeddyDD。 ### Sublime Text 由 [nk9](https://github.com/nk9) 提供的 [Just 包](https://github.com/nk9/just_sublime) 支持 `just` 语法高亮,同时还有其它工具,这些可以在 [PackageControl](https://packagecontrol.io/packages/Just) 上找到。 ### 其它编辑器 欢迎给我发送必要的命令,以便在你选择的编辑器中实现语法高亮,这样我就可以把它们放在这里。 快速开始 ----------- 参见 [安装部分](#安装) 了解如何在你的电脑上安装 `just`。试着运行 `just --version` 以确保它被正确安装。 关于语法的概述,请查看这个 [速查表](https://cheatography.com/linux-china/cheat-sheets/justfile/)。 一旦 `just` 安装完毕并开始工作,在你的项目根目录创建一个名为 `justfile` 的文件,内容如下: ```just recipe-name: echo 'This is a recipe!' # 这是一行注释 another-recipe: @echo 'This is another recipe.' ``` 当你调用 `just` 时,它会在当前目录和父目录寻找文件 `justfile`,所以你可以从你项目的任何子目录中调用它。 搜索 `justfile` 是不分大小写的,所以任何大小写,如 `Justfile`、`JUSTFILE` 或 `JuStFiLe` 都可以工作。`just` 也会寻找名字为 `.justfile` 的文件,以便你打算隐藏一个 `justfile`。 运行 `just` 时未传参数,则运行 `justfile` 中的第一个配方: ```sh $ just echo 'This is a recipe!' This is a recipe! ``` 通过一个或多个参数指定要运行的配方: ```sh $ just another-recipe This is another recipe. ``` `just` 在运行每条命令前都会将其打印到标准错误中,这就是为什么 `echo 'This is a recipe!'` 被打印出来。对于以 `@` 开头的行,这将被抑制,这就是为什么 `echo 'This is another recipe.'` 没有被打印。 如果一个命令失败,配方就会停止运行。这里 `cargo publish` 只有在 `cargo test` 成功后才会运行: ```just publish: cargo test # 前面的测试通过才会执行 publish! cargo publish ``` 配方可以依赖其他配方。在这里,`test` 配方依赖于 `build` 配方,所以 `build` 将在 `test` 之前运行: ```just build: cc main.c foo.c bar.c -o main test: build ./test sloc: @echo "`wc -l *.c` lines of code" ``` ```sh $ just test cc main.c foo.c bar.c -o main ./test testing… all tests passed! ``` 没有依赖关系的配方将按照命令行上给出的顺序运行: ```sh $ just build sloc cc main.c foo.c bar.c -o main 1337 lines of code ``` 依赖项总是先运行,即使它们被放在依赖它们的配方之后: ```sh $ just test build cc main.c foo.c bar.c -o main ./test testing… all tests passed! ``` 示例 -------- 在 [Examples 目录](https://github.com/casey/just/tree/master/examples) 中可以找到各种 `justfile` 的例子。 特性介绍 -------- ### 默认配方 当 `just` 被调用而没有传入任何配方时,它会运行 `justfile` 中的第一个配方。这个配方可能是项目中最常运行的命令,比如运行测试: ```just test: cargo test ``` 你也可以使用依赖关系来默认运行多个配方: ```just default: lint build test build: echo Building… test: echo Testing… lint: echo Linting… ``` 在没有合适配方作为默认配方的情况下,你也可以在 `justfile` 的开头添加一个配方,用于列出可用的配方: ```just default: just --list ``` ### 列出可用的配方 可以用 `just --list` 按字母顺序列出配方: ```sh $ just --list Available recipes: build test deploy lint ``` `just --summary` 以更简洁的形式列出配方: ```sh $ just --summary build test deploy lint ``` 传入 `--unsorted` 选项可以按照它们在 `justfile` 中出现的顺序打印配方: ```just test: echo 'Testing!' build: echo 'Building!' ``` ```sh $ just --list --unsorted Available recipes: test build ``` ```sh $ just --summary --unsorted test build ``` 如果你想让 `just` 默认列出 `justfile` 中的配方,你可以使用这个作为默认配方: ```just default: @just --list ``` 请注意,你可能需要在上面这一行中添加 `--justfile {{justfile()}}`。没有它,如果你执行 `just -f /some/distant/justfile -d .` 或 `just -f ./non-standard-justfile` 配方中的普通 `just --list` 就不一定会使用你提供的文件,它将试图在你的当前路径中找到一个 `justfile`,甚至可能导致 `No justfile found` 的错误。 标题文本可以用 `--list-heading` 来定制: ```sh $ just --list --list-heading $'Cool stuff…\n' Cool stuff… test build ``` 而缩进可以用 `--list-prefix` 来定制: ```sh $ just --list --list-prefix ···· Available recipes: ····test ····build ``` `--list-heading` 参数同时替换了标题和后面的换行,所以如果不是空的,应该包含一个换行。这样做是为了允许你通过传递空字符串来完全抑制标题行: ```sh $ just --list --list-heading '' test build ``` ### 别名 别名允许你用其他名称来调用配方: ```just alias b := build build: echo 'Building!' ``` ```sh $ just b build echo 'Building!' Building! ``` ### 设置 设置控制解释和执行。每个设置最多可以指定一次,可以出现在 `justfile` 的任何地方。 例如: ```just set shell := ["zsh", "-cu"] foo: # this line will be run as `zsh -cu 'ls **/*.txt'` ls **/*.txt ``` #### 设置一览表 | 名称 | 值 | 默认 | 描述 | | --------------------------- | ------------------ | ----- | --------------------------------------------------------------------------------------- | | `allow-duplicate-recipes` | boolean | False | 允许在 `justfile` 后面出现的配方覆盖之前的同名配方 | | `allow-duplicate-variables` | boolean | False | 允许在 `justfile` 后面出现的变量覆盖之前的同名变量 | | `dotenv-filename` | string | - | 如果有自定义名称的 `.env` 环境变量文件的话,则将其加载 | | `dotenv-load` | boolean | False | 如果有`.env` 环境变量文件的话,则将其加载 | | `dotenv-path` | string | - | 从自定义路径中加载 `.env` 环境变量文件, 文件不存在将会报错。可以覆盖 `dotenv-filename` | | `dotenv-required` | boolean | False | 如果 `.env` 环境变量文件不存在的话,需要报错 | | `export` | boolean | False | 将所有变量导出为环境变量 | | `fallback` | boolean | False | 如果命令行中的第一个配方没有找到,则在父目录中搜索 `justfile` | | `ignore-comments` | boolean | False | 忽略以`#`开头的配方行 | | `positional-arguments` | boolean | False | 传递位置参数 | | `shell` | `[COMMAND, ARGS…]` | - | 设置用于调用配方和评估反引号内包裹内容的命令 | | `tempdir` | string | - | 在 `tempdir` 位置创建临时目录,而不是系统默认的临时目录 | | `windows-powershell` | boolean | False | 在 Windows 上使用 PowerShell 作为默认 Shell(废弃,建议使用 `windows-shell`) | | `windows-shell` | `[COMMAND, ARGS…]` | - | 设置用于调用配方和评估反引号内包裹内容的命令 | Bool 类型设置可以写成: ```justfile set NAME ``` 这就相当于: ```justfile set NAME := true ``` #### 允许重复的配方 如果 `allow-duplicate-recipes` 被设置为 `true`,那么定义多个同名的配方就不会出错,而会使用最后的定义。默认为 `false`。 ```just set allow-duplicate-recipes @foo: echo foo @foo: echo bar ``` ```sh $ just foo bar ``` #### 允许重复的变量 如果 `allow-duplicate-variables` 被设置为 `true`,那么定义多个同名的变量将不会报错。默认为 `false`。 ```just set allow-duplicate-variables a := "foo" a := "bar" @foo: echo $a ``` ```sh $ just foo bar ``` #### 环境变量加载 如果 `dotenv-load`, `dotenv-filename`, `dotenv-path`, or `dotenv-required` 中任意一项被设置, `just` 会尝试从文件中加载环境变量 如果设置了 `dotenv-path`, `just` 会在指定的路径下搜索文件,该路径可以是绝对路径, 也可以是基于当前工作路径的相对路径 如果设置了 `dotenv-filename`,`just` 会在指定的相对路径,以及其所有的上层目录中,搜索指定文件 如果没有设置 `dotenv-filename`,但是设置了 `dotenv-load` 或 `dotenv-required`, `just` 会在当前工作路径,以及其所有的上层目录中,寻找名为 `.env` 的文件。 `dotenv-filename` 和 `dotenv-path` 很相似,但是 `dotenv-path` 只会检查指定的目录 而 `dotenv-filename` 会检查指定目录以及其所有的上层目录。 如果没有找到环境变量文件也不会报错,除非设置了 `dotenv-required`。 从文件中加载的变量是环境变量,而非 `just` 变量,所以在配方和反引号中需要必须通过 `$VARIABLE_NAME` 来调用。 比如,如果你的 `.env` 文件包含以下内容: ```sh # a comment, will be ignored DATABASE_ADDRESS=localhost:6379 SERVER_PORT=1337 ``` 并且你的 `justfile` 包含: ```just set dotenv-load serve: @echo "Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT…" ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` `just serve` 将会输出: ```sh $ just serve Starting server with database localhost:6379 on port 1337… ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` #### 导出 `export` 设置使所有 `just` 变量作为环境变量被导出。默认值为 `false`。 ```just set export a := "hello" @foo b: echo $a echo $b ``` ```sh $ just foo goodbye hello goodbye ``` #### 位置参数 如果 `positional-arguments` 为 `true`,配方参数将作为位置参数传递给命令。对于行式配方,参数 `$0` 将是配方的名称。 例如,运行这个配方: ```just set positional-arguments @foo bar: echo $0 echo $1 ``` 将产生以下输出: ```sh $ just foo hello foo hello ``` 当使用 `sh` 兼容的 Shell,如 `bash` 或 `zsh` 时,`$@` 会展开为传给配方的位置参数,从1开始。当在双引号内使用 `"$@"` 时,包括空白的参数将被传递,就像它们是双引号一样。也就是说,`"$@"` 相当于 `"$1" "$2"`......当没有位置参数时,`"$@"` 和 `$@` 将展开为空(即,它们被删除)。 这个例子的配方将逐行打印参数: ```just set positional-arguments @test *args='': bash -c 'while (( "$#" )); do echo - $1; shift; done' -- "$@" ``` 用 _两个_ 参数运行: ```sh $ just test foo "bar baz" - foo - bar baz ``` #### Shell `shell` 设置控制用于调用执行配方代码行和反引号内指令的命令。Shebang 配方不受影响。 ```just # use python3 to execute recipe lines and backticks set shell := ["python3", "-c"] # use print to capture result of evaluation foos := `print("foo" * 4)` foo: print("Snake snake snake snake.") print("{{foos}}") ``` `just` 把要执行的命令作为一个参数进行传递。许多 Shell 需要一个额外的标志,通常是 `-c`,以使它们评估执行第一个参数。 ##### Windows Shell `just` 在 Windows 上默认使用 `sh`。要在 Windows 上使用不同的 Shell,请使用`windows-shell`: ```just set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] hello: Write-Host "Hello, world!" ``` 参考 [powershell.just](https://github.com/casey/just/blob/master/examples/powershell.just) ,了解在所有平台上使用 PowerShell 的 justfile。 ##### Windows PowerShell *`set windows-powershell` 使用遗留的 `powershell.exe` 二进制文件,不再推荐。请参阅上面的 `windows-shell` 设置,以通过更灵活的方式来控制在 Windows 上使用哪个 Shell。* `just` 在 Windows 上默认使用 `sh`。要使用 `powershell.exe` 作为替代,请将 `windows-powershell` 设置为 `true`。 ```just set windows-powershell := true hello: Write-Host "Hello, world!" ``` ##### Python 3 ```just set shell := ["python3", "-c"] ``` ##### Bash ```just set shell := ["bash", "-uc"] ``` ##### Z Shell ```just set shell := ["zsh", "-uc"] ``` ##### Fish ```just set shell := ["fish", "-c"] ``` ##### Nushell ```just set shell := ["nu", "-c"] ``` 如果你想设置默认的表格显示模式为 `light`: ```just set shell := ['nu', '-m', 'light', '-c'] ``` *[Nushell](https://github.com/nushell/nushell) 使用 Rust 开发并且具备良好的跨平台能力,**支持 Windows / macOS 和各种 Linux 发行版*** ### 文档注释 紧接着配方前面的注释将出现在 `just --list` 中: ```just # build stuff build: ./bin/build # test stuff test: ./bin/test ``` ```sh $ just --list Available recipes: build # build stuff test # test stuff ``` ### 变量和替换 支持在变量、字符串、拼接、路径连接和替换中使用 `{{…}}` : ```just tmpdir := `mktemp -d` version := "0.2.7" tardir := tmpdir / "awesomesauce-" + version tarball := tardir + ".tar.gz" publish: rm -f {{tarball}} mkdir {{tardir}} cp README.md *.c {{tardir}} tar zcvf {{tarball}} {{tardir}} scp {{tarball}} me@server.com:release/ rm -rf {{tarball}} {{tardir}} ``` #### 路径拼接 `/` 操作符可用于通过斜线连接两个字符串: ```just foo := "a" / "b" ``` ``` $ just --evaluate foo a/b ``` 请注意,即使已经有一个 `/`,也会添加一个 `/`: ```just foo := "a/" bar := foo / "b" ``` ``` $ just --evaluate bar a//b ``` 也可以构建绝对路径1.5.0: ```just foo := / "b" ``` ``` $ just --evaluate foo /b ``` `/` 操作符使用 `/` 字符,即使在 Windows 上也是如此。因此,在使用通用命名规则(UNC)的路径中应避免使用 `/` 操作符,即那些以 `\?` 开头的路径,因为 UNC 路径不支持正斜线。 #### 转义 `{{` 想要写一个包含 `{{` 的配方,可以使用 `{{{{`: ```just braces: echo 'I {{{{LOVE}} curly braces!' ``` (未匹配的 `}}` 会被忽略,所以不需要转义) 另一个选择是把所有你想转义的文本都放在插值里面: ```just braces: echo '{{'I {{LOVE}} curly braces!'}}' ``` 然而,另一个选择是使用 `{{ "{{" }}`: ```just braces: echo 'I {{ "{{" }}LOVE}} curly braces!' ``` ### 字符串 双引号字符串支持转义序列: ```just string-with-tab := "\t" string-with-newline := "\n" string-with-carriage-return := "\r" string-with-double-quote := "\"" string-with-slash := "\\" string-with-no-newline := "\ " ``` ```sh $ just --evaluate "tring-with-carriage-return := " string-with-double-quote := """ string-with-newline := " " string-with-no-newline := "" string-with-slash := "\" string-with-tab := " " ``` 字符串可以包含换行符: ```just single := ' hello ' double := " goodbye " ``` 单引号字符串不支持转义序列: ```just escapes := '\t\n\r\"\\' ``` ```sh $ just --evaluate escapes := "\t\n\r\"\\" ``` 支持单引号和双引号字符串的缩进版本,以三个单引号或三个双引号为界。缩进的字符串行被删除了所有非空行所共有的前导空白: ```just # 这个字符串执行结果为 `foo\nbar\n` x := ''' foo bar ''' # 这个字符串执行结果为 `abc\n wuv\nbar\n` y := """ abc wuv xyz """ ``` 与未缩进的字符串类似,缩进的双引号字符串处理转义序列,而缩进的单引号字符串则忽略转义序列。转义序列的处理是在取消缩进后进行的。取消缩进的算法不考虑转义序列产生的空白或换行。 ### 错误忽略 通常情况下,如果一个命令返回一个非零的退出状态,将停止执行。要想在一个命令之后继续执行,即使它失败了,需要在命令前加上 `-`: ```just foo: -cat foo echo 'Done!' ``` ```sh $ just foo cat foo cat: foo: No such file or directory echo 'Done!' Done! ``` ### 函数 `just` 提供了一些内置函数,在编写配方时可能很有用。 #### 系统信息 - `arch()` — 指令集结构。可能的值是:`"aarch64"`, `"arm"`, `"asmjs"`, `"hexagon"`, `"mips"`, `"msp430"`, `"powerpc"`, `"powerpc64"`, `"s390x"`, `"sparc"`, `"wasm32"`, `"x86"`, `"x86_64"`, 和 `"xcore"`。 - `os()` — 操作系统,可能的值是: `"android"`, `"bitrig"`, `"dragonfly"`, `"emscripten"`, `"freebsd"`, `"haiku"`, `"ios"`, `"linux"`, `"macos"`, `"netbsd"`, `"openbsd"`, `"solaris"`, 和 `"windows"`。 - `os_family()` — 操作系统系列;可能的值是:`"unix"` 和 `"windows"`。 例如: ```just system-info: @echo "This is an {{arch()}} machine". ``` ```sh $ just system-info This is an x86_64 machine ``` `os_family()` 函数可以用来创建跨平台的 `justfile`,使其可以在不同的操作系统上工作。一个例子,见 [cross-platform.just](https://github.com/casey/just/blob/master/examples/cross-platform.just) 文件。 #### 环境变量 - `env_var(key)` — 获取名称为 `key` 的环境变量,如果不存在则终止。 ```just home_dir := env_var('HOME') test: echo "{{home_dir}}" ``` ```sh $ just /home/user1 ``` - `env_var_or_default(key, default)` — 获取名称为 `key` 的环境变量,如果不存在则返回 `default`。 #### 调用目录 - `invocation_directory()` - 获取 `just` 被调用时当前目录所对应的绝对路径,在 `just` 改变路径并执行相应命令前。 例如,要对 "当前目录" 下的文件调用 `rustfmt`(从用户/调用者的角度看),使用以下规则: ```just rustfmt: find {{invocation_directory()}} -name \*.rs -exec rustfmt {} \; ``` 另外,如果你的命令需要从当前目录运行,你可以使用如下方式: ```just build: cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here ``` #### Justfile 和 Justfile 目录 - `justfile()` - 取得当前 `justfile` 的路径。 - `justfile_directory()` - 取得当前 `justfile` 文件父目录的路径。 例如,运行一个相对于当前 `justfile` 位置的命令: ```just script: ./{{justfile_directory()}}/scripts/some_script ``` #### Just 可执行程序 - `just_executable()` - `just` 可执行文件的绝对路径。 例如: ```just executable: @echo The executable is at: {{just_executable()}} ``` ```sh $ just The executable is at: /bin/just ``` #### 字符串处理 - `quote(s)` - 用 `'\''` 替换所有的单引号,并在 `s` 的首尾添加单引号。这足以为许多 Shell 转义特殊字符,包括大多数 Bourne Shell 的后代。 - `replace(s, from, to)` - 将 `s` 中的所有 `from` 替换为 `to`。 - `replace_regex(s, regex, replacement)` - 将 `s` 中所有的 `regex` 替换为 `replacement`。正则表达式由 [Rust `regex` 包](https://docs.rs/regex/latest/regex/) 提供。参见 [语法文档](https://docs.rs/regex/latest/regex/#syntax) 以了解使用示例。 - `trim(s)` - 去掉 `s` 的首尾空格。 - `trim_end(s)` - 去掉 `s` 的尾部空格。 - `trim_end_match(s, substr)` - 删除与 `substr` 匹配的 `s` 的后缀。 - `trim_end_matches(s, substr)` - 反复删除与 `substr` 匹配的 `s` 的后缀。 - `trim_start(s)` - 去掉 `s` 的首部空格。 - `trim_start_match(s, substr)` - 删除与 `substr` 匹配的 `s` 的前缀。 - `trim_start_matches(s, substr)` - 反复删除与 `substr` 匹配的 `s` 的前缀。 #### 大小写转换 - `capitalize(s)`1.7.0 - 将 `s` 的第一个字符转换成大写字母,其余的转换成小写字母。 - `kebabcase(s)`1.7.0 - 将 `s` 转换为 `kebab-case`。 - `lowercamelcase(s)`1.7.0 - 将 `s` 转换为小驼峰形式:`lowerCamelCase`。 - `lowercase(s)` - 将 `s` 转换为全小写形式。 - `shoutykebabcase(s)`1.7.0 - 将 `s` 转换为 `SHOUTY-KEBAB-CASE`。 - `shoutysnakecase(s)`1.7.0 - 将 `s` 转换为 `SHOUTY_SNAKE_CASE`。 - `snakecase(s)`1.7.0 - 将 `s` 转换为 `snake_case`。 - `titlecase(s)`1.7.0 - 将 `s` 转换为 `Title Case`。 - `uppercamelcase(s)`1.7.0 - 将 `s` 转换为 `UpperCamelCase`。 - `uppercase(s)` - 将 `s` 转换为大写形式。 #### 路径操作 ##### 非可靠的 - `absolute_path(path)` - 将当前工作目录中到相对路径 `path` 的路径转换为绝对路径。在 `/foo` 目录通过 `absolute_path("./bar.txt")` 可以得到 `/foo/bar.txt`。 - `extension(path)` - 获取 `path` 的扩展名。`extension("/foo/bar.txt")` 结果为 `txt`。 - `file_name(path)` - 获取 `path` 的文件名,去掉任何前面的目录部分。`file_name("/foo/bar.txt")` 的结果为 `bar.txt`。 - `file_stem(path)` - 获取 `path` 的文件名,不含扩展名。`file_stem("/foo/bar.txt")` 的结果为 `bar`。 - `parent_directory(path)` - 获取 `path` 的父目录。`parent_directory("/foo/bar.txt")` 的结果为 `/foo`。 - `without_extension(path)` - 获取 `path` 不含扩展名部分。`without_extension("/foo/bar.txt")` 的结果为 `/foo/bar`。 这些函数可能会失败,例如,如果一个路径没有扩展名,则将停止执行。 ##### 可靠的 - `clean(path)` - 通过删除多余的路径分隔符、中间的 `.` 和 `..` 来简化 `path`。`clean("foo//bar")` 结果为 `foo/bar`,`clean("foo/..")` 为 `.`,`clean("foo/./bar")` 结果为 `foo/bar`。 - `join(a, b…)` - *这个函数在 Unix 上使用 `/`,在 Windows 上使用 `\`,这可能会导致非预期的行为。`/` 操作符,例如,`a / b`,总是使用 `/`,应该被考虑作为替代,除非在 Windows 上特别指定需要 `\`。* 将路径 `a` 和 路径 `b` 拼接在一起。`join("foo/bar", "baz")` 结果为 `foo/bar/baz`。它接受两个或多个参数。 #### 文件系统访问 - `path_exists(path)` - 如果路径指向一个存在的文件或目录,则返回 `true`,否则返回 `false`。也会遍历符号链接,如果路径无法访问或指向一个无效的符号链接,则返回 `false`。 ##### 错误报告 - `error(message)` - 终止执行并向用户报告错误 `message`。 #### UUID 和哈希值生成 - `sha256(string)` - 以十六进制字符串形式返回 `string` 的 SHA-256 哈希值。 - `sha256_file(path)` - 以十六进制字符串形式返回 `path` 处的文件的 SHA-256 哈希值。 - `uuid()` - 返回一个随机生成的 UUID。 ### 配方属性 配方可以通过添加属性注释来改变其行为。 | 名称 | 描述 | | ----------------------------------- | -------------------------------------- | | `[no-cd]`1.9.0 | 在执行配方之前不要改变目录。 | | `[no-exit-message]`1.7.0 | 如果配方执行失败,不要打印错误信息。 | | `[linux]`1.8.0 | 在Linux上启用配方。 | | `[macos]`1.8.0 | 在MacOS上启用配方。 | | `[unix]`1.8.0 | 在Unixes上启用配方。 | | `[windows]`1.8.0 | 在Windows上启用配方。 | | `[private]`1.10.0 | 参见 [私有配方](#私有配方). | #### 启用和禁用配方1.8.0 `[linux]`, `[macos]`, `[unix]` 和 `[windows]` 属性是配置属性。默认情况下,配方总是被启用。一个带有一个或多个配置属性的配方只有在其中一个或多个配置处于激活状态时才会被启用。 这可以用来编写因运行的操作系统不同,其行为也不同的 `justfile`。以下 `justfile` 中的 `run` 配方将编译和运行 `main.c`,并且根据操作系统的不同而使用不同的C编译器,同时使用正确的二进制产物名称: ```just [unix] run: cc main.c ./a.out [windows] run: cl main.c main.exe ``` #### 禁用变更目录1.9.0 `just` 通常在执行配方时将当前目录设置为包含 `justfile` 的目录,你可以通过 `[no-cd]` 属性来禁用此行为。这可以用来创建使用调用目录相对路径或者对当前目录进行操作的配方。 例如这个 `commit` 配方: ```just [no-cd] commit file: git add {{file}} git commit ``` 可以使用相对于当前目录的路径,因为 `[no-cd]` 可以防止 `just` 在执行 `commit` 配方时改变当前目录。 ### 使用反引号的命令求值 反引号可以用来存储命令的求值结果: ```just localhost := `dumpinterfaces | cut -d: -f2 | sed 's/\/.*//' | sed 's/ //g'` serve: ./serve {{localhost}} 8080 ``` 缩进的反引号,以三个反引号为界,与字符串缩进的方式一样,会被去掉缩进: ````just # This backtick evaluates the command `echo foo\necho bar\n`, which produces the value `foo\nbar\n`. stuff := ``` echo foo echo bar ``` ```` 参见 [字符串](#字符串) 部分,了解去除缩进的细节。 反引号内不能以 `#!` 开头。这种语法是为将来的升级而保留的。 ### 条件表达式 `if` / `else` 表达式评估不同的分支,取决于两个表达式是否评估为相同的值: ```just foo := if "2" == "2" { "Good!" } else { "1984" } bar: @echo "{{foo}}" ``` ```sh $ just bar Good! ``` 也可以用于测试不相等: ```just foo := if "hello" != "goodbye" { "xyz" } else { "abc" } bar: @echo {{foo}} ``` ```sh $ just bar xyz ``` 还支持与正则表达式进行匹配: ```just foo := if "hello" =~ 'hel+o' { "match" } else { "mismatch" } bar: @echo {{foo}} ``` ```sh $ just bar match ``` 正则表达式由 [Regex 包](https://github.com/rust-lang/regex) 提供,其语法在 [docs.rs](https://docs.rs/regex/1.5.4/regex/#syntax) 上有对应文档。由于正则表达式通常使用反斜线转义序列,请考虑使用单引号的字符串字面值,这将使斜线不受干扰地传递给正则分析器。 条件表达式是短路的,这意味着它们只评估其中的一个分支。这可以用来确保反引号内的表达式在不应该运行的时候不会运行。 ```just foo := if env_var("RELEASE") == "true" { `get-something-from-release-database` } else { "dummy-value" } ``` 条件语句也可以在配方中使用: ```just bar foo: echo {{ if foo == "bar" { "hello" } else { "goodbye" } }} ``` 注意最后的 `}` 后面的空格! 没有这个空格,插值将被提前结束。 多个条件语句可以被连起来: ```just foo := if "hello" == "goodbye" { "xyz" } else if "a" == "a" { "abc" } else { "123" } bar: @echo {{foo}} ``` ```sh $ just bar abc ``` ### 出现错误停止执行 可以用 `error` 函数停止执行。比如: ```just foo := if "hello" == "goodbye" { "xyz" } else if "a" == "b" { "abc" } else { error("123") } ``` 在运行时产生以下错误: ``` error: Call to function `error` failed: 123 | 16 | error("123") ``` ### 从命令行设置变量 变量可以从命令行进行覆盖。 ```just os := "linux" test: build ./test --test {{os}} build: ./build {{os}} ``` ```sh $ just ./build linux ./test --test linux ``` 任何数量的 `NAME=VALUE` 形式的参数都可以在配方前传递: ```sh $ just os=plan9 ./build plan9 ./test --test plan9 ``` 或者你可以使用 `--set` 标志: ```sh $ just --set os bsd ./build bsd ./test --test bsd ``` ### 获取和设置环境变量 #### 导出 `just` 变量 以 `export` 关键字为前缀的赋值将作为环境变量导出到配方中: ```just export RUST_BACKTRACE := "1" test: # 如果它崩溃了,将打印一个堆栈追踪 cargo test ``` 以 `$` 为前缀的参数将被作为环境变量导出: ```just test $RUST_BACKTRACE="1": # 如果它崩溃了,将打印一个堆栈追踪 cargo test ``` 导出的变量和参数不会被导出到同一作用域内反引号包裹的表达式里。 ```just export WORLD := "world" # This backtick will fail with "WORLD: unbound variable" BAR := `echo hello $WORLD` ``` ```just # Running `just a foo` will fail with "A: unbound variable" a $A $B=`echo $A`: echo $A $B ``` 当 [export](#导出) 被设置时,所有的 `just` 变量都将作为环境变量被导出。 #### 从环境中获取环境变量 来自环境的环境变量会自动传递给配方: ```just print_home_folder: echo "HOME is: '${HOME}'" ``` ```sh $ just HOME is '/home/myuser' ``` #### 从 `.env` 文件加载环境变量 如果 [dotenv-load](#环境变量加载) 被设置,`just` 将从 `.env` 文件中加载环境变量。该文件中的变量将作为环境变量提供给配方。参见 [环境变量集成](#环境变量加载) 以获得更多信息。 #### 从环境变量中设置 `just` 变量 环境变量可以通过函数 `env_var()` 和 `env_var_or_default()` 传入到 `just` 变量。 参见 [environment-variables](#环境变量)。 ### 配方参数 配方可以有参数。这里的配方 `build` 有一个参数叫 `target`: ```just build target: @echo 'Building {{target}}…' cd {{target}} && make ``` 要在命令行上传递参数,请把它们放在配方名称后面: ```sh $ just build my-awesome-project Building my-awesome-project… cd my-awesome-project && make ``` 要向依赖配方传递参数,请将依赖配方和参数一起放在括号里: ```just default: (build "main") build target: @echo 'Building {{target}}…' cd {{target}} && make ``` 变量也可以作为参数传递给依赖: ```just target := "main" _build version: @echo 'Building {{version}}…' cd {{version}} && make build: (_build target) ``` 命令的参数可以通过将依赖与参数一起放在括号中的方式传递给依赖: ```just build target: @echo "Building {{target}}…" push target: (build target) @echo 'Pushing {{target}}…' ``` 参数可以有默认值: ```just default := 'all' test target tests=default: @echo 'Testing {{target}}:{{tests}}…' ./test --tests {{tests}} {{target}} ``` 有默认值的参数可以省略: ```sh $ just test server Testing server:all… ./test --tests all server ``` 或者提供: ```sh $ just test server unit Testing server:unit… ./test --tests unit server ``` 默认值可以是任意的表达式,但字符串或路径拼接必须放在括号内: ```just arch := "wasm" test triple=(arch + "-unknown-unknown") input=(arch / "input.dat"): ./test {{triple}} ``` 配方的最后一个参数可以是变长的,在参数名称前用 `+` 或 `*` 表示: ```just backup +FILES: scp {{FILES}} me@server.com: ``` 以 `+` 为前缀的变长参数接受 _一个或多个_ 参数,并展开为一个包含这些参数的字符串,以空格分隔: ```sh $ just backup FAQ.md GRAMMAR.md scp FAQ.md GRAMMAR.md me@server.com: FAQ.md 100% 1831 1.8KB/s 00:00 GRAMMAR.md 100% 1666 1.6KB/s 00:00 ``` 以 `*` 为前缀的变长参数接受 _0个或更多_ 参数,并展开为一个包含这些参数的字符串,以空格分隔,如果没有参数,则为空字符串: ```just commit MESSAGE *FLAGS: git commit {{FLAGS}} -m "{{MESSAGE}}" ``` 变长参数可以被分配默认值。这些参数被命令行上传递的参数所覆盖: ```just test +FLAGS='-q': cargo test {{FLAGS}} ``` `{{…}}` 的替换可能需要加引号,如果它们包含空格。例如,如果你有以下配方: ```just search QUERY: lynx https://www.google.com/?q={{QUERY}} ``` 然后你输入: ```sh $ just search "cat toupee" ``` `just` 将运行 `lynx https://www.google.com/?q=cat toupee` 命令,这将被 `sh` 解析为`lynx`、`https://www.google.com/?q=cat` 和 `toupee`,而不是原来的 `lynx` 和 `https://www.google.com/?q=cat toupee`。 你可以通过添加引号来解决这个问题: ```just search QUERY: lynx 'https://www.google.com/?q={{QUERY}}' ``` 以 `$` 为前缀的参数将被作为环境变量导出: ```just foo $bar: echo $bar ``` ### 在配方的末尾运行配方 一个配方的正常依赖总是在配方开始之前运行。也就是说,被依赖方总是在依赖方之前运行。这些依赖被称为 "前期依赖"。 一个配方也可以有后续的依赖,它们在配方之后运行,用 `&&` 表示: ```just a: echo 'A!' b: a && c d echo 'B!' c: echo 'C!' d: echo 'D!' ``` …运行 _b_ 输出: ```sh $ just b echo 'A!' A! echo 'B!' B! echo 'C!' C! echo 'D!' D! ``` ### 在配方中间运行配方 `just` 不支持在配方的中间运行另一个配方,但你可以在一个配方的中间递归调用 `just`。例如以下 `justfile`: ```just a: echo 'A!' b: a echo 'B start!' just c echo 'B end!' c: echo 'C!' ``` …运行 _b_ 输出: ```sh $ just b echo 'A!' A! echo 'B start!' B start! echo 'C!' C! echo 'B end!' B end! ``` 这有局限性,因为配方 `c` 是以一个全新的 `just` 调用来运行的,赋值将被重新计算,依赖可能会运行两次,命令行参数不会被传入到子 `just` 进程。 ### 用其他语言书写配方 以 `#!` 开头的配方被称为 Shebang 配方,它通过将配方主体保存到文件中并运行它来执行。这让你可以用不同的语言来编写配方: ```just polyglot: python js perl sh ruby nu python: #!/usr/bin/env python3 print('Hello from python!') js: #!/usr/bin/env node console.log('Greetings from JavaScript!') perl: #!/usr/bin/env perl print "Larry Wall says Hi!\n"; sh: #!/usr/bin/env sh hello='Yo' echo "$hello from a shell script!" nu: #!/usr/bin/env nu let hello = 'Hola' echo $"($hello) from a nushell script!" ruby: #!/usr/bin/env ruby puts "Hello from ruby!" ``` ```sh $ just polyglot Hello from python! Greetings from JavaScript! Larry Wall says Hi! Yo from a shell script! Hola from a nushell script! Hello from ruby! ``` 在类似 Unix 的操作系统中,包括 Linux 和 MacOS,Shebang 配方的执行方式是将配方主体保存到临时目录下的一个文件中,将该文件标记为可执行文件,然后执行它。操作系统将 Shebang 行解析为一个命令行并调用它,包括文件的路径。例如,如果一个配方以 `#!/usr/bin/env bash` 开头,操作系统运行的最终命令将是 `/usr/bin/env bash /tmp/PATH_TO_SAVED_RECIPE_BODY` 之类。请记住,不同的操作系统对 Shebang 行的分割方式不同。 Windows 不支持 Shebang 行。在 Windows 上,`just` 将 Shebang 行分割成命令和参数,将配方主体保存到一个文件中,并调用分割后的命令和参数,同时将保存的配方主体的路径作为最后一个参数。 ### 更加安全的 Bash Shebang 配方 如果你正在写一个 `bash` Shebang 配方,考虑加入 `set -euxo pipefail`: ```just foo: #!/usr/bin/env bash set -euxo pipefail hello='Yo' echo "$hello from Bash!" ``` 严格意义上说这不是必须的,但是 `set -euxo pipefail` 开启了一些有用的功能,使 `bash` Shebang 配方的行为更像正常的、行式的 `just` 配方: - `set -e` 使 `bash` 在命令失败时退出。 - `set -u` 使 `bash` 在变量未定义时退出。 - `set -x` 使 `bash` 在运行前打印每一行脚本。 - `set -o pipefail` 使 `bash` 在管道中的一个命令失败时退出。这是 `bash` 特有的,所以在普通的行式 `just` 配方中没有开启。 这些措施共同避免了很多 Shell 脚本的问题。 #### 在 Windows 上执行 Shebang 配方 在 Windows 上,包含 `/` 的 Shebang 解释器路径通过 `cygpath` 从 Unix 风格的路径转换为 Windows 风格的路径,该工具随 [Cygwin](http://www.cygwin.com) 一起提供。 例如,要在 Windows 上执行这个配方: ```just echo: #!/bin/sh echo "Hello!" ``` 解释器路径 `/bin/sh` 在执行前将被 `cygpath` 翻译成 Windows 风格的路径。 如果解释器路径不包含 `/`,它将被执行而不被翻译。这主要用于 `cygpath` 不可用或者你希望向解释器传递一个 Windows 风格的路径的情况下。 ### 在配方中设置变量 配方代码行是由 Shell 解释的,而不是 `just`,所以不可能在配方中设置 `just` 变量: ```mf foo: x := "hello" # This doesn't work! echo {{x}} ``` 使用 Shell 变量是可能的,但还有一个问题:每一行配方都由一个新的 Shell 实例运行,所以在一行中设置的变量不会在下一行中生效: ```just foo: x=hello && echo $x # 这个没问题! y=bye echo $y # 这个是有问题的, `y` 在此处未定义! ``` 解决这个问题的最好方法是使用 Shebang 配方。Shebang 配方体被提取出来并作为脚本运行,所以一个 Shell 实例就可以运行整个配方体: ```just foo: #!/usr/bin/env bash set -euxo pipefail x=hello echo $x ``` ### 在配方之间共享环境变量 每个配方的每一行都由一个新的shell执行,所以不可能在配方之间共享环境变量。 #### 使用 Python 虚拟环境 一些工具,像 [Python 的 venv](https://docs.python.org/3/library/venv.html),需要加载环境变量才能工作,这使得它们在使用 `just` 时具有挑战性。作为一种变通方法,你可以直接执行虚拟环境二进制文件: ```just venv: [ -d foo ] || python3 -m venv foo run: venv ./foo/bin/python3 main.py ``` ### 改变配方中的工作目录 每一行配方都由一个新的 Shell 执行,所以如果你在某一行改变了工作目录,对后面的行不会有影响: ```just foo: pwd # This `pwd` will print the same directory… cd bar pwd # …as this `pwd`! ``` 有几个方法可以解决这个问题。一个是在你想运行的命令的同一行调用 `cd`: ```just foo: cd bar && pwd ``` 另一种方法是使用 Shebang 配方。Shebang 配方体被提取并作为脚本运行,因此一个 Shell 实例将运行整个配方体,所以一行的 `pwd` 改变将影响后面的行,就像一个 Shell 脚本: ```just foo: #!/usr/bin/env bash set -euxo pipefail cd bar pwd ``` ### 缩进 配方代码行可以用空格或制表符缩进,但不能两者混合使用。一个配方的所有行必须有相同的缩进,但同一 `justfile` 中的不同配方可以使用不同的缩进。 ### 多行结构 没有初始 Shebang 的配方会被逐行评估和运行,这意味着多行结构可能不会像你预期的那样工作。 例如对于下面的 `justfile`: ```mf conditional: if true; then echo 'True!' fi ``` 在 `conditional` 配方的第二行前有额外的前导空格,会产生一个解析错误: ```sh $ just conditional error: Recipe line has extra leading whitespace | 3 | echo 'True!' | ^^^^^^^^^^^^^^^^ ``` 为了解决这个问题,你可以在一行上写条件,用斜线转义换行,或者在你的配方中添加一个 Shebang。我们提供了一些多行结构的例子可供参考。 #### `if` 语句 ```just conditional: if true; then echo 'True!'; fi ``` ```just conditional: if true; then \ echo 'True!'; \ fi ``` ```just conditional: #!/usr/bin/env sh if true; then echo 'True!' fi ``` #### `for` 循环 ```just for: for file in `ls .`; do echo $file; done ``` ```just for: for file in `ls .`; do \ echo $file; \ done ``` ```just for: #!/usr/bin/env sh for file in `ls .`; do echo $file done ``` #### `while` 循环 ```just while: while `server-is-dead`; do ping -c 1 server; done ``` ```just while: while `server-is-dead`; do \ ping -c 1 server; \ done ``` ```just while: #!/usr/bin/env sh while `server-is-dead`; do ping -c 1 server done ``` ### 命令行选项 `just` 提供了一些有用的命令行选项,用于列出、Dump 和调试配方以及变量: ```sh $ just --list Available recipes: js perl polyglot python ruby $ just --show perl perl: #!/usr/bin/env perl print "Larry Wall says Hi!\n"; $ just --show polyglot polyglot: python js perl sh ruby ``` 可以通过 `just --help` 命令查看所有选项。 ### 私有配方 名字以 `_` 开头的配方和别名将在 `just --list` 中被忽略: ```just test: _test-helper ./bin/test _test-helper: ./bin/super-secret-test-helper-stuff ``` ```sh $ just --list Available recipes: test ``` `just --summary` 亦然: ```sh $ just --summary test ``` `[private]` 属性1.10.0也可用于隐藏配方,而不需要改变名称: ```just [private] foo: [private] alias b := bar bar: ``` ```sh $ just --list Available recipes: bar ``` 这对那些只作为其他配方的依赖使用的辅助配方很有用。 ### 安静配方 配方名称可在前面加上 `@`,可以在每行反转行首 `@` 的含义: ```just @quiet: echo hello echo goodbye @# all done! ``` 现在只有以 `@` 开头的行才会被回显: ```sh $ j quiet hello goodbye # all done! ``` Shebang 配方默认是安静的: ```just foo: #!/usr/bin/env bash echo 'Foo!' ``` ```sh $ just foo Foo! ``` 在 Shebang 配方名称前面添加 `@`,使 `just` 在执行配方前打印该配方: ```just @bar: #!/usr/bin/env bash echo 'Bar!' ``` ```sh $ just bar #!/usr/bin/env bash echo 'Bar!' Bar! ``` `just` 在配方行失败时通常会打印错误信息,这些错误信息可以通过 `[no-exit-message]`1.7.0 属性来抑制。你可能会发现这在包装工具的配方中特别有用: ```just git *args: @git {{args}} ``` ```sh $ just git status fatal: not a git repository (or any of the parent directories): .git error: Recipe `git` failed on line 2 with exit code 128 ``` 添加属性,当工具以非零代码退出时抑制退出错误信息: ```just [no-exit-message] git *args: @git {{args}} ``` ```sh $ just git status fatal: not a git repository (or any of the parent directories): .git ``` ### 通过交互式选择器选择要运行的配方 `--choose` 子命令可以使 `just` 唤起一个选择器来让您选择要运行的配方。选择器应该从标准输入中读取包含配方名称的行,并将其中一个或多个用空格分隔的名称打印到标准输出。 因为目前没有办法通过 `--choose` 运行一个需要传入参数的配方,所以这样的配方将不会在选择器中列出。另外,私有配方和别名也会被忽略。 选择器可以用 `--chooser` 标志来覆写。如果 `--chooser` 没有给出,那么 `just` 首先检查 `$JUST_CHOOSER` 是否被设置。如果没有,那么将使用默认选择器 `fzf`,这是一个流行的模糊查找器。 参数可以包含在选择器中,例如:`fzf --exact`。 选择器的调用方式与配方行的调用方式相同。例如,如果选择器是 `fzf`,它将被通过 `sh -cu 'fzf'` 调用,如果 Shell 或 Shell 参数被覆写,选择器的调用将尊重这些覆写。 如果你希望 `just` 默认用选择器来选择配方,你可以用这个作为你的默认配方: ```just default: @just --choose ``` ### 在其他目录下调用 `justfile` 如果传递给 `just` 的第一个参数包含 `/`,那么就会发生以下情况: 1. 参数在最后的 `/` 处被分割; 2. 最后一个 `/` 之前的部分将被视为一个目录。`just` 将从这里开始搜索 `justfile`,而不是在当前目录下; 3. 最后一个斜线之后的部分被视为正常参数,如果是空的,则被忽略; 这可能看起来有点奇怪,但如果你想在一个子目录下的 `justfile` 中运行一个命令,这很有用。 例如,如果你在一个目录中,该目录包含一个名为 `foo` 的子目录,该目录包含一个 `justfile`,其配方为 `build`,也是默认的配方,以下都是等同的: ```sh $ (cd foo && just build) $ just foo/build $ just foo/ ``` ### 隐藏 `justfile` `just` 会寻找名为 `justfile` 和 `.justfile` 的 `justfile`,因此你也可以使用隐藏的 `justfile`(即 `.justfile`)。 ### Just 脚本 通过在 `justfile` 的顶部添加 Shebang 行并使其可执行,`just` 可以作为脚本的解释器使用: ```sh $ cat > script < just.zsh ``` *macOS 注意:* 最近版本的 macOS 使用 zsh 作为默认的 Shell。如果你使用 Homebrew 安装 `just`,它会自动安装 zsh 补全脚本的最新副本到 Homebrew zsh 目录下,而内置默认版本的 zsh 是不知道的。如果可能的话,最好使用这个脚本副本,因为当你通过 Homebrew 更新 `just` 时,它也会被更新。另外,许多其他的 Homebrew 软件包也使用相同位置的补全脚本,而内置的 zsh 也不知道这些。为了在这种情况下在 zsh 中使用 `just` 的补全,你可以在调用 `compinit` 之前将 `fpath` 设置为 Homebrew 的位置。还要注意,Oh My Zsh 默认会运行 `compinit`,所以你的 `.zshrc` 文件看起来像这样: ```zsh # 启动Homebrew,添加环境变量 eval "$(brew shellenv)" fpath=($HOMEBREW_PREFIX/share/zsh/site-functions $fpath) # 然后从这些选项中选择一个: # 1. 如果你使用的是 Oh My Zsh,你可以在这里初始化它 # source $ZSH/oh-my-zsh.sh # 2. 否则就自己运行 compinit # autoload -U compinit # compinit ``` ### 语法 在 [GRAMMAR.md](https://github.com/casey/just/blob/master/GRAMMAR.md) 中可以找到一个非正式的 `justfile` 语法说明。 ### just.sh 在 `just` 成为一个精致的 Rust 程序之前,它是一个很小的 Shell 脚本,叫 `make`。你可以在 [contrib/just.sh](https://github.com/casey/just/blob/master/contrib/just.sh) 中找到旧版本。 ### 用户 `justfile` 如果你想让一些配方在任何地方都能使用,你有几个选择。 首先,在 `~/.user.justfile` 中创建一个带有一些配方的 `justfile`。 #### 配方别名 如果你想通过名称来调用 `~/.user.justfile` 中的配方,并且不介意为每个配方创建一个别名,可以在你的 Shell 初始化脚本中加入以下内容: ```sh for recipe in `just --justfile ~/.user.justfile --summary`; do alias $recipe="just --justfile ~/.user.justfile --working-directory . $recipe" done ``` 现在,如果你在 `~/.user.justfile` 里有一个叫 `foo` 的配方,你可以在命令行输入 `foo` 来运行它。 我花了很长时间才意识到你可以像这样创建配方别名。尽管有点迟,但我很高兴给你带来这个 `justfile` 技术的重大进步。 #### 别名转发 如果你不想为每个配方创建别名,你可以创建一个别名: ```sh alias .j='just --justfile ~/.user.justfile --working-directory .' ``` 现在,如果你在 `~/.user.justfile` 里有一个叫 `foo` 的配方,你可以在命令行输入 `.j foo` 来运行它。 我很确定没有人真正使用这个功能,但它确实存在。 ¯\\\_(ツ)\_/¯ #### 定制化 你可以用额外的选项来定制上述别名。例如,如果你想让你的 `justfile` 中的配方在你的主目录中运行,而不是在当前目录中运行: ```sh alias .j='just --justfile ~/.user.justfile --working-directory ~' ``` ### Node.js `package.json` 脚本兼容性 下面的导出语句使 `just` 配方能够访问本地 Node 模块二进制文件,并使 `just` 配方命令的行为更像 Node.js `package.json` 文件中的 `script` 条目: ```just export PATH := "./node_modules/.bin:" + env_var('PATH') ``` ### 替代方案 现在并不缺少命令运行器!在这里,有一些或多或少比较类似于 `just` 的替代方案,包括: - [make](https://en.wikipedia.org/wiki/Make_(software)): 启发了 `just` 的 Unix 构建工具。最初的 `make` 有几个不同的现代后裔, 包括 [FreeBSD Make](https://www.freebsd.org/cgi/man.cgi?make(1)) 和 [GNU Make](https://www.gnu.org/software/make/)。 - [task](https://github.com/go-task/task): 一个用 Go 编写的基于 YAML 的命令运行器。 - [maid](https://github.com/egoist/maid): 一个用 JavaScript 编写的基于 Markdown 的命令运行器。 - [microsoft/just](https://github.com/microsoft/just): 一个用 JavaScript 编写的基于 JavasScript 的命令运行器。 - [cargo-make](https://github.com/sagiegurari/cargo-make): 一个用于 Rust 项目的命令运行器。 - [mmake](https://github.com/tj/mmake): 一个针对 `make` 的包装器,有很多改进,包括远程包含。 - [robo](https://github.com/tj/robo): 一个用 Go 编写的基于 YAML 的命令运行器。 - [mask](https://github.com/jakedeichert/mask): 一个用 Rust 编写的基于 Markdown 的命令运行器。 - [makesure](https://github.com/xonixx/makesure): 一个用 AWK 和 Shell 编写的简单而便携的命令运行器。 - [haku](https://github.com/VladimirMarkelov/haku): 一个用 Rust 编写的类似 make 的命令运行器。 贡献 ------------ `just` 欢迎你的贡献! `just` 是在最大许可的 [CC0](https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt) 公共领域奉献和后备许可下发布的,所以你的修改也必须在这个许可下发布。 ### Janus [Janus](https://github.com/casey/janus) 是一个收集和分析 `justfile` 的工具,可以确定新版本的 `just` 是否会破坏或改变现有 `justfile` 的解析。 在合并一个特别大的或可怕的变化之前,应该运行 `Janus` 以确保没有任何破坏。不要担心自己运行 `Janus`,Casey 会很乐意在需要时为你运行它。 ### 最小支持的 Rust 版本 最低支持的 Rust 版本,或 MSRV,是当前稳定的(current stable) Rust。它可能可以在旧版本的 Rust 上构建,但这并不保证。 ### 新版本 `just` 会经常发布新版本,以便用户快速获得新功能。 发布的提交信息使用如下模板: ``` Release x.y.z - Bump version: x.y.z → x.y.z - Update changelog - Update changelog contributor credits - Update dependencies - Update man page - Update version references in readme ``` 常见问题 -------------------------- ### Just 避免了 Make 的哪些特异性? `make` 有一些行为令人感到困惑、复杂,或者使它不适合作为通用的命令运行器。 一个例子是,在某些情况下,`make` 不会实际运行配方中的命令。例如,如果你有一个名为 `test` 的文件和以下 makefile: ```just test: ./test ``` `make` 将会拒绝运行你的测试: ```sh $ make test make: `test' is up to date. ``` `make` 假定 `test` 配方产生一个名为 `test` 的文件。由于这个文件已经存在,而且由于配方没有其他依赖,`make` 认为它没有任何事情可做并退出。 公平地说,当把 `make` 作为一个构建系统时,这种行为是可取的,但当把它作为一个命令运行器时就不可取了。你可以使用 `make` 内置的 [`.PHONY` 目标名称](https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html) 为特定的目标禁用这种行为,但其语法很冗长,而且很难记住。明确的虚假目标列表与配方定义分开写,也带来了意外定义新的非虚假目标的风险。在 `just` 中,所有的配方都被当作是虚假的。 其他 `make` 特异行为的例子包括赋值中 `=` 和 `:=` 的区别;如果你弄乱了你的 makefile,将会产生混乱的错误信息;需要 `$$` 在配方中使用环境变量;以及不同口味的 `make` 之间的不相容性。 ### Just 和 Cargo 构建脚本之间有什么关系? [`cargo` 构建脚本](http://doc.crates.io/build-script.html) 有一个相当特定的用途,就是控制 `cargo` 如何构建你的 Rust 项目。这可能包括给 `rustc` 调用添加标志,构建外部依赖,或运行某种 codegen 步骤。 另一方面,`just` 是用于你可能在开发中会运行的所有其他的杂项命令。比如在不同的配置下运行测试,对代码进行检查,将构建的产出推送到服务器,删除临时文件,等等。 另外,尽管 `just` 是用 Rust 编写的,但它可以被用于任何语言或项目使用的构建系统。 进一步漫谈 ----------------- 我个人认为为几乎每个项目写一个 `justfile` 非常有用,无论大小。 在一个有多个贡献者的大项目中,有一个包含项目工作所需的所有命令的文件是非常有用的,这样所有命令唾手可得。 可能有不同的命令来测试、构建、检查、部署等等,把它们都放在一个地方是很方便的,可以减少你花在告诉人们要运行哪些命令和如何输入这些命令的时间。 而且,有了一个容易放置命令的地方,你很可能会想出其他有用的东西,这些东西是项目集体智慧的一部分,但没有写在任何地方,比如修订控制工作流程的某些部分需要的神秘命令,安装你项目的所有依赖,或者所有你可能需要传递给构建系统的任意标志等。 一些关于配方的想法: - 部署/发布项目 - 在发布模式与调试模式下进行构建 - 在调试模式下运行或启用日志记录功能 - 复杂的 git 工作流程 - 更新依赖 - 运行不同的测试集,例如快速测试与慢速测试,或以更多输出模式运行它们 - 任何复杂的命令集,你真的应该写下来,如果只是为了能够记住它们的话 即使是小型的个人项目,能够通过名字记住命令,而不是通过 ^Reverse 搜索你的 Shell 历史,这也是一个巨大的福音,能够进入一个用任意语言编写的旧项目,并知道你需要用到的所有命令都在 `justfile` 中,如果你输入 `just`,就可能会输出一些有用的(或至少是有趣的!)信息。 关于配方的想法,请查看 [这个项目的 `justfile`](https://github.com/casey/just/blob/master/justfile),或一些 [在其他项目里](https://github.com/search?q=path%3A**%2Fjustfile&type=code) 的 `justfile`。 总之,我想这个令人难以置信地啰嗦的 README 就到此为止了。 我希望你喜欢使用 `just`,并在你所有的计算工作中找到巨大的成功和满足! 😸 just-1.40.0/Vagrantfile000064400000000000000000000010001046102023000130470ustar 00000000000000Vagrant.configure(2) do |config| config.vm.box = 'debian/jessie64' config.vm.provision "shell", inline: <<-EOS apt-get -y update apt-get install -y clang git vim curl EOS config.vm.provision "shell", privileged: false, inline: <<-EOS curl https://sh.rustup.rs -sSf > install-rustup chmod +x install-rustup ./install-rustup -y source ~/.cargo/env rustup target add x86_64-unknown-linux-musl cargo install -f just git clone https://github.com/casey/just.git EOS end just-1.40.0/bin/forbid000075500000000000000000000004331046102023000126360ustar 00000000000000#!/usr/bin/env bash set -euo pipefail if ! which rg > /dev/null; then echo 'error: `rg` not found, please install ripgrep: https://github.com/BurntSushi/ripgrep/' exit 1 fi ! rg \ --glob !CHANGELOG.md \ --glob !bin/forbid \ --ignore-case \ 'dbg!|fixme|todo|xxx' \ . just-1.40.0/bin/package000075500000000000000000000021751046102023000127710ustar 00000000000000#!/usr/bin/env bash set -euxo pipefail VERSION=${REF#"refs/tags/"} DIST=`pwd`/dist echo "Packaging just $VERSION for $TARGET..." test -f Cargo.lock || cargo generate-lockfile echo "Installing rust toolchain for $TARGET..." rustup target add $TARGET if [[ $TARGET == aarch64-unknown-linux-musl ]]; then export CC=aarch64-linux-gnu-gcc fi echo "Building just..." RUSTFLAGS="--deny warnings --codegen target-feature=+crt-static $TARGET_RUSTFLAGS" \ cargo build --bin just --target $TARGET --release EXECUTABLE=target/$TARGET/release/just if [[ $OS == windows-latest ]]; then EXECUTABLE=$EXECUTABLE.exe fi echo "Copying release files..." mkdir dist cp -r \ $EXECUTABLE \ Cargo.lock \ Cargo.toml \ GRAMMAR.md \ LICENSE \ README.md \ completions \ man/just.1 \ $DIST cd $DIST echo "Creating release archive..." case $OS in ubuntu-latest | macos-latest) ARCHIVE=just-$VERSION-$TARGET.tar.gz tar czf $ARCHIVE * echo "archive=$DIST/$ARCHIVE" >> $GITHUB_OUTPUT ;; windows-latest) ARCHIVE=just-$VERSION-$TARGET.zip 7z a $ARCHIVE * echo "archive=`pwd -W`/$ARCHIVE" >> $GITHUB_OUTPUT ;; esac just-1.40.0/clippy.toml000064400000000000000000000001311046102023000130630ustar 00000000000000cognitive-complexity-threshold = 1337 source-item-ordering = ['enum', 'struct', 'trait'] just-1.40.0/contrib/just.sh000075500000000000000000000012051046102023000136550ustar 00000000000000#!/usr/bin/env bash # cd upwards to the justfile while [[ ! -e justfile ]]; do if [[ $PWD = / ]] || [[ $PWD = $JUSTSTOP ]] || [[ -e juststop ]]; then echo 'No justfile found.' exit 1 fi cd .. done # prefer gmake if it exists if command -v gmake > /dev/null; then MAKE=gmake else MAKE=make fi declare -a RECIPES for ARG in "$@"; do test $ARG = '--' && shift && break RECIPES+=($ARG) && shift done # export arguments after '--' so they can be used in recipes I=0 for ARG in "$@"; do export ARG$I=$ARG I=$((I + 1)) done # go! exec $MAKE MAKEFLAGS='' --always-make --no-print-directory -f justfile ${RECIPES[*]} just-1.40.0/crates-io-readme.md000064400000000000000000000011111046102023000143300ustar 00000000000000`just` is a handy way to save and run project-specific commands. Commands are stored in a file called `justfile` or `Justfile` with syntax inspired by `make`: ```make build: cc *.c -o main # test everything test-all: build ./test --all # run a specific test test TEST: build ./test --test {{TEST}} ``` `just` produces detailed error messages and avoids `make`'s idiosyncrasies, so debugging a justfile is easier and less surprising than debugging a makefile. It works on all operating systems supported by Rust. Read more on [GitHub](https://github.com/casey/just). just-1.40.0/examples/cross-platform.just000064400000000000000000000014341046102023000163750ustar 00000000000000# use with https://github.com/casey/just # # Example cross-platform Python project # python_dir := if os_family() == "windows" { "./.venv/Scripts" } else { "./.venv/bin" } python := python_dir + if os_family() == "windows" { "/python.exe" } else { "/python3" } system_python := if os_family() == "windows" { "py.exe -3.9" } else { "python3.9" } # Set up development environment bootstrap: if test ! -e .venv; then {{ system_python }} -m venv .venv; fi {{ python }} -m pip install --upgrade pip wheel pip-tools {{ python_dir }}/pip-sync # Upgrade Python dependencies upgrade-deps: && bootstrap {{ python_dir }}/pip-compile --upgrade # Sample project script 1 script1: {{ python }} script1.py # Sample project script 2 script2 *ARGS: {{ python }} script2.py {{ ARGS }} just-1.40.0/examples/keybase.just000064400000000000000000000005441046102023000150460ustar 00000000000000# use with https://github.com/casey/just # Be inspired to use just to notify a chat # channel, this examples shows use with keybase # since it - practically - authenticates at the # device level and needs no additional secrets # notify update in keybase notify m="": keybase chat send --topic-type "chat" --channel "upd(): {{m}}" just-1.40.0/examples/kitchen-sink.just000064400000000000000000000105621046102023000160130ustar 00000000000000set shell := ["sh", "-c"] set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] set allow-duplicate-recipes set positional-arguments set dotenv-load set export alias s := serve bt := '0' export RUST_BACKTRACE_1 := bt log := "warn" export JUST_LOG := (log + "ing" + `grep loop /etc/networks | cut -f2`) tmpdir := `mktemp` version := "0.2.7" tardir := tmpdir / "awesomesauce-" + version foo1 := / "tmp" foo2_3 := "a/" tarball := tardir + ".tar.gz" export RUST_BACKTRACE_2 := "1" string-with-tab := "\t" string-with-newline := "\n" string-with-carriage-return := "\r" string-with-double-quote := "\"" string-with-slash := "\\" string-with-no-newline := "\ " # Newlines in variables single := ' hello ' double := " goodbye " escapes := '\t\n\r\"\\' # this string will evaluate to `foo\nbar\n` x := ''' foo bar ''' # this string will evaluate to `abc\n wuv\nbar\n` y := """ abc wuv xyz """ for: for file in `ls .`; do \ echo $file; \ done serve: touch {{tmpdir}}/file # This backtick evaluates the command `echo foo\necho bar\n`, which produces the value `foo\nbar\n`. stuff := ``` echo foo echo bar ``` an_arch := trim(lowercase(justfile())) + arch() trim_end := trim_end("99.99954% ") home_dir := replace(env_var('HOME') / "yep", 'yep', '') quoted := quote("some things beyond\"$()^%#@!|-+=_*&'`") smartphone := trim_end_match('blah.txt', 'txt') museum := trim_start_match(trim_start(trim_end_matches(' yep_blah.txt.txt', '.txt')), 'yep_') water := trim_start_matches('ssssssoup.txt', 's') congress := uppercase(os()) fam := os_family() path_1 := absolute_path('test') path_2 := '/tmp/subcommittee.txt' ext_z := extension(path_2) exe_name := file_name(just_executable()) a_stem := file_stem(path_2) a_parent := parent_directory(path_2) sans_ext := without_extension(path_2) camera := join('tmp', 'dir1', 'dir2', path_2) cleaned := clean('/tmp/blah/..///thing.txt') id__path := '/tmp' / sha256('blah') / sha256_file(justfile()) _another_var := env_var_or_default("HOME", justfile_directory()) python := `which python` exists := if path_exists(just_executable()) =~ '^/User' { uuid() } else { 'yeah' } foo := if env_var("_") == "/usr/bin/env" { `touch /tmp/a_file` } else { "dummy-value" } foo_b := if "hello" == "goodbye" { "xyz" } else { if "no" == "no" { "yep"} else { error("123") } } foo_c := if "hello" == "goodbye" { "xyz" } else if "a" == "a" { "abc" } else { "123" } bar: @echo {{foo}} bar2 foo_stuff: echo {{ if foo_stuff == "bar" { "hello" } else { "goodbye" } }} executable: @echo The executable is at: {{just_executable()}} rustfmt: find {{invocation_directory()}} -name \*.rs -exec rustfmt {} \; test: echo "{{home_dir}}" linewise: Write-Host "Hello, world!" serve2: @echo "Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT…" shebang := if os() == 'windows' { 'powershell.exe' } else { '/usr/bin/env pwsh' } shebang: #!{{shebang}} $PSV = $PSVersionTable.PSVersion | % {"$_" -split "\." } $psver = $PSV[0] + "." + $PSV[1] if ($PSV[2].Length -lt 4) { $psver += "." + $PSV[2] + " Core" } else { $psver += " Desktop" } echo "PowerShell $psver" @foo: echo bar @test5 *args='': bash -c 'while (( "$#" )); do echo - $1; shift; done' -- "$@" test2 $RUST_BACKTRACE="1": # will print a stack trace if it crashes cargo test notify m="": keybase chat send --topic-type "chat" --channel "upd(): {{m}}" # Sample project script 2 script2 *ARGS: {{ python }} script2.py {{ ARGS }} braces: echo 'I {{{{LOVE}} curly braces!' _braces2: echo '{{'I {{LOVE}} curly braces!'}}' _braces3: echo 'I {{ "{{" }}LOVE}} curly braces!' foo2: -@cat foo echo 'Done!' test3 target tests=path_1: @echo 'Testing {{target}}:{{tests}}…' ./test --tests {{tests}} {{target}} test4 triple=(an_arch + "-unknown-unknown") input=(an_arch / "input.dat"): ./test {{triple}} variadic $VAR1_1 VAR2 VAR3 VAR4=("a") +$FLAGS='-q': foo2 braces cargo test {{FLAGS}} time: @-date +"%H:%S" -cat /tmp/nonexistent_file.txt @echo "finished" justwords: grep just \ --text /usr/share/dict/words \ > /tmp/justwords # Subsequent dependencies # https://just.systems/man/en/chapter_37.html # To test, run `$ just -f test-suite.just b` a: echo 'A!' b: a && d echo 'B start!' just -f {{justfile()}} c echo 'B end!' c: echo 'C!' d: echo 'D!' just-1.40.0/examples/powershell.just000064400000000000000000000012271046102023000156060ustar 00000000000000# Cross platform shebang: shebang := if os() == 'windows' { 'powershell.exe' } else { '/usr/bin/env pwsh' } # Set shell for non-Windows OSs: set shell := ["powershell", "-c"] # Set shell for Windows OSs: set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] # If you have PowerShell Core installed and want to use it, # use `pwsh.exe` instead of `powershell.exe` linewise: Write-Host "Hello, world!" shebang: #!{{shebang}} $PSV = $PSVersionTable.PSVersion | % {"$_" -split "\." } $psver = $PSV[0] + "." + $PSV[1] if ($PSV[2].Length -lt 4) { $psver += "." + $PSV[2] + " Core" } else { $psver += " Desktop" } echo "PowerShell $psver" just-1.40.0/examples/pre-commit.just000064400000000000000000000042211046102023000154730ustar 00000000000000# use with https://github.com/casey/just # Example combining just + pre-commit # pre-commit: https://pre-commit.com/ # > A framework for managing and maintaining # > multi-language pre-commit hooks. # pre-commit brings about encapsulation of your # most common repo scripting tasks. It is perfectly # usable without actually setting up precommit hooks. # If you chose to, this justfiles includes shorthands # for git commit and amend to keep pre-commit out of # the way when in flow on a feature branch. # uses: https://github.com/tekwizely/pre-commit-golang # uses: https://github.com/prettier/prettier (pre-commit hook) # configures: https://www.git-town.com/ (setup receipt) # fix auto-fixable lint issues in staged files fix: pre-commit run go-returns # fixes all Go lint issues pre-commit run prettier # fixes all Markdown (& other) lint issues # lint most common issues in - or due - to staged files lint: pre-commit run go-vet-mod || true # runs go vet pre-commit run go-lint || true # runs golint pre-commit run go-critic || true # runs gocritic # lint all issues in - or due - to staged files: lint-all: pre-commit run golangci-lint-mod || true # runs golangci-lint # run tests in - or due - to staged files test: pre-commit run go-test-mod || true # runs go test # commit skipping pre-commit hooks commit m: git commit --no-verify -m "{{m}}" # amend skipping pre-commit hooks amend: git commit --amend --no-verify # install/update code automation (prettier, pre-commit, goreturns, lintpack, gocritic, golangci-lint) install: npm i -g prettier curl https://pre-commit.com/install-local.py | python3 - go get github.com/sqs/goreturns go get github.com/go-lintpack/lintpack/... go get github.com/go-critic/go-critic/... curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $(go env GOPATH)/bin v1.27.0 # setup/update pre-commit hooks (optional) setup: pre-commit install --install-hooks # uninstall: `pre-commit uninstall` git config git-town.code-hosting-driver gitea # setup git-town with gitea git config git-town.code-hosting-origin-hostname gitea.example.org # setup git-town origin hostname just-1.40.0/examples/screenshot.just000064400000000000000000000003041046102023000155720ustar 00000000000000alias b := build host := `uname -a` # build main build: cc *.c -o main # test everything test-all: build ./test --all # run a specific test test TEST: build ./test --test {{TEST}} just-1.40.0/justfile000075500000000000000000000111461046102023000124510ustar 00000000000000#!/usr/bin/env -S just --justfile # ^ A shebang isn't required, but allows a justfile to be executed # like a script, with `./justfile test`, for example. alias t := test log := "warn" export JUST_LOG := log [group: 'dev'] watch +args='test': cargo watch --clear --exec '{{ args }}' [group: 'test'] test: cargo test --all [group: 'check'] ci: forbid test build-book clippy cargo fmt --all -- --check cargo update --locked --package just [group: 'check'] fuzz: cargo +nightly fuzz run fuzz-compiler [group: 'misc'] run: cargo run # only run tests matching `PATTERN` [group: 'test'] filter PATTERN: cargo test {{PATTERN}} [group: 'misc'] build: cargo build [group: 'misc'] fmt: cargo fmt --all [group: 'check'] shellcheck: shellcheck www/install.sh [group: 'doc'] man: mkdir -p man cargo run -- --man > man/just.1 [group: 'doc'] view-man: man man man/just.1 # add git log messages to changelog [group: 'release'] update-changelog: echo >> CHANGELOG.md git log --pretty='format:- %s' >> CHANGELOG.md [group: 'release'] update-contributors: cargo run --release --package update-contributors [group: 'check'] outdated: cargo outdated -R [group: 'check'] unused: cargo +nightly udeps --workspace # publish current GitHub master branch [group: 'release'] publish: #!/usr/bin/env bash set -euxo pipefail rm -rf tmp/release git clone git@github.com:casey/just.git tmp/release cd tmp/release ! grep 'master' README.md VERSION=`sed -En 's/version[[:space:]]*=[[:space:]]*"([^"]+)"/\1/p' Cargo.toml | head -1` git tag -a $VERSION -m "Release $VERSION" git push origin $VERSION cargo publish cd ../.. rm -rf tmp/release [group: 'release'] readme-version-notes: grep 'master' README.md # clean up feature branch BRANCH [group: 'dev'] done BRANCH=`git rev-parse --abbrev-ref HEAD`: git checkout master git diff --no-ext-diff --quiet --exit-code git pull --rebase github master git diff --no-ext-diff --quiet --exit-code {{BRANCH}} git branch -D {{BRANCH}} # install just from crates.io [group: 'misc'] install: cargo install -f just # install development dependencies [group: 'dev'] install-dev-deps: rustup install nightly rustup update nightly cargo +nightly install cargo-fuzz cargo install cargo-check cargo install cargo-watch cargo install mdbook mdbook-linkcheck # everyone's favorite animate paper clip [group: 'check'] clippy: cargo clippy --all --all-targets --all-features -- --deny warnings [group: 'check'] forbid: ./bin/forbid [group: 'dev'] replace FROM TO: sd '{{FROM}}' '{{TO}}' src/*.rs [group: 'demo'] test-quine: cargo run -- quine # make a quine, compile it, and verify it [group: 'demo'] quine: mkdir -p tmp @echo '{{quine-text}}' > tmp/gen0.c cc tmp/gen0.c -o tmp/gen0 ./tmp/gen0 > tmp/gen1.c cc tmp/gen1.c -o tmp/gen1 ./tmp/gen1 > tmp/gen2.c diff tmp/gen1.c tmp/gen2.c rm -r tmp @echo 'It was a quine!' quine-text := ' int printf(const char*, ...); int main() { char *s = "int printf(const char*, ...);" "int main() {" " char *s = %c%s%c;" " printf(s, 34, s, 34);" " return 0;" "}"; printf(s, 34, s, 34); return 0; } ' [group: 'test'] test-completions: ./tests/completions/just.bash [group: 'check'] build-book: cargo run --package generate-book mdbook build book/en mdbook build book/zh [group: 'dev'] print-readme-constants-table: cargo test constants::tests::readme_table -- --nocapture # run all polyglot recipes [group: 'demo'] polyglot: _python _js _perl _sh _ruby _python: #!/usr/bin/env python3 print('Hello from python!') _js: #!/usr/bin/env node console.log('Greetings from JavaScript!') _perl: #!/usr/bin/env perl print "Larry Wall says Hi!\n"; _sh: #!/usr/bin/env sh hello='Yo' echo "$hello from a shell script!" _nu: #!/usr/bin/env nu let hellos = ["Greetings", "Yo", "Howdy"] $hellos | each {|el| print $"($el) from a nushell script!" } _ruby: #!/usr/bin/env ruby puts "Hello from ruby!" # Print working directory, for demonstration purposes! [group: 'demo'] pwd: echo {{invocation_directory()}} [group: 'test'] test-bash-completions: rm -rf tmp mkdir -p tmp/bin cargo build cp target/debug/just tmp/bin ./tmp/bin/just --completions bash > tmp/just.bash echo 'mod foo' > tmp/justfile echo 'bar:' > tmp/foo.just cd tmp && PATH="`realpath bin`:$PATH" bash --init-file just.bash [group: 'test'] test-release-workflow: -git tag -d test-release -git push origin :test-release git tag test-release git push origin test-release # Local Variables: # mode: makefile # End: # vim: set ft=make : just-1.40.0/rustfmt.toml000064400000000000000000000002001046102023000132640ustar 00000000000000edition = "2018" max_width = 100 newline_style = "Unix" tab_spaces = 2 use_field_init_shorthand = true use_try_shorthand = true just-1.40.0/src/alias.rs000064400000000000000000000024111046102023000131170ustar 00000000000000use super::*; /// An alias, e.g. `name := target` #[derive(Debug, PartialEq, Clone, Serialize)] pub(crate) struct Alias<'src, T = Rc>> { pub(crate) attributes: AttributeSet<'src>, pub(crate) name: Name<'src>, #[serde( bound(serialize = "T: Keyed<'src>"), serialize_with = "keyed::serialize" )] pub(crate) target: T, } impl<'src> Alias<'src, Namepath<'src>> { pub(crate) fn resolve(self, target: Rc>) -> Alias<'src> { assert!(self.target.last().lexeme() == target.namepath.last().lexeme()); Alias { attributes: self.attributes, name: self.name, target, } } } impl Alias<'_> { pub(crate) fn is_private(&self) -> bool { self.name.lexeme().starts_with('_') || self.attributes.contains(AttributeDiscriminant::Private) } } impl<'src, T> Keyed<'src> for Alias<'src, T> { fn key(&self) -> &'src str { self.name.lexeme() } } impl<'src> Display for Alias<'src, Namepath<'src>> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "alias {} := {}", self.name.lexeme(), self.target) } } impl Display for Alias<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!( f, "alias {} := {}", self.name.lexeme(), self.target.name.lexeme() ) } } just-1.40.0/src/alias_style.rs000064400000000000000000000001711046102023000143400ustar 00000000000000use super::*; #[derive(Debug, PartialEq, Clone, ValueEnum)] pub(crate) enum AliasStyle { Left, Right, Separate, } just-1.40.0/src/analyzer.rs000064400000000000000000000274701046102023000136670ustar 00000000000000use {super::*, CompileErrorKind::*}; #[derive(Default)] pub(crate) struct Analyzer<'run, 'src> { aliases: Table<'src, Alias<'src, Namepath<'src>>>, assignments: Vec<&'run Binding<'src, Expression<'src>>>, modules: Table<'src, Justfile<'src>>, recipes: Vec<&'run Recipe<'src, UnresolvedDependency<'src>>>, sets: Table<'src, Set<'src>>, unexports: HashSet, warnings: Vec, } impl<'run, 'src> Analyzer<'run, 'src> { pub(crate) fn analyze( asts: &'run HashMap>, doc: Option, groups: &[String], loaded: &[PathBuf], name: Option>, paths: &HashMap, root: &Path, ) -> CompileResult<'src, Justfile<'src>> { Self::default().justfile(asts, doc, groups, loaded, name, paths, root) } fn justfile( mut self, asts: &'run HashMap>, doc: Option, groups: &[String], loaded: &[PathBuf], name: Option>, paths: &HashMap, root: &Path, ) -> CompileResult<'src, Justfile<'src>> { let mut definitions = HashMap::new(); let mut imports = HashSet::new(); let mut unstable_features = BTreeSet::new(); let mut stack = Vec::new(); let ast = asts.get(root).unwrap(); stack.push(ast); while let Some(ast) = stack.pop() { unstable_features.extend(&ast.unstable_features); for item in &ast.items { match item { Item::Alias(alias) => { Self::define(&mut definitions, alias.name, "alias", false)?; self.aliases.insert(alias.clone()); } Item::Assignment(assignment) => { self.assignments.push(assignment); } Item::Comment(_) => (), Item::Import { absolute, .. } => { if let Some(absolute) = absolute { if imports.insert(absolute) { stack.push(asts.get(absolute).unwrap()); } } } Item::Module { absolute, doc, groups, name, .. } => { if let Some(absolute) = absolute { Self::define(&mut definitions, *name, "module", false)?; self.modules.insert(Self::analyze( asts, doc.clone(), groups.as_slice(), loaded, Some(*name), paths, absolute, )?); } } Item::Recipe(recipe) => { if recipe.enabled() { Self::analyze_recipe(recipe)?; self.recipes.push(recipe); } } Item::Set(set) => { self.analyze_set(set)?; self.sets.insert(set.clone()); } Item::Unexport { name } => { if !self.unexports.insert(name.lexeme().to_string()) { return Err(name.token.error(DuplicateUnexport { variable: name.lexeme(), })); } } } } self.warnings.extend(ast.warnings.iter().cloned()); } let settings = Settings::from_table(self.sets); let mut assignments: Table<'src, Assignment<'src>> = Table::default(); for assignment in self.assignments { let variable = assignment.name.lexeme(); if !settings.allow_duplicate_variables && assignments.contains_key(variable) { return Err(assignment.name.token.error(DuplicateVariable { variable })); } if assignments.get(variable).map_or(true, |original| { assignment.file_depth <= original.file_depth }) { assignments.insert(assignment.clone()); } if self.unexports.contains(variable) { return Err(assignment.name.token.error(ExportUnexported { variable })); } } AssignmentResolver::resolve_assignments(&assignments)?; let mut deduplicated_recipes = Table::<'src, UnresolvedRecipe<'src>>::default(); for recipe in self.recipes { Self::define( &mut definitions, recipe.name, "recipe", settings.allow_duplicate_recipes, )?; if deduplicated_recipes .get(recipe.name.lexeme()) .map_or(true, |original| recipe.file_depth <= original.file_depth) { deduplicated_recipes.insert(recipe.clone()); } } let recipes = RecipeResolver::resolve_recipes(&assignments, &settings, deduplicated_recipes)?; let mut aliases = Table::new(); while let Some(alias) = self.aliases.pop() { aliases.insert(Self::resolve_alias(&self.modules, &recipes, alias)?); } for recipe in recipes.values() { if recipe.attributes.contains(AttributeDiscriminant::Script) { unstable_features.insert(UnstableFeature::ScriptAttribute); break; } } if settings.script_interpreter.is_some() { unstable_features.insert(UnstableFeature::ScriptInterpreterSetting); } let source = root.to_owned(); let root = paths.get(root).unwrap(); Ok(Justfile { aliases, assignments, default: recipes .values() .filter(|recipe| recipe.name.path == root) .fold(None, |accumulator, next| match accumulator { None => Some(Rc::clone(next)), Some(previous) => Some(if previous.line_number() < next.line_number() { previous } else { Rc::clone(next) }), }), doc: doc.filter(|doc| !doc.is_empty()), groups: groups.into(), loaded: loaded.into(), modules: self.modules, name, recipes, settings, source, unexports: self.unexports, unstable_features, warnings: self.warnings, working_directory: ast.working_directory.clone(), }) } fn define( definitions: &mut HashMap<&'src str, (&'static str, Name<'src>)>, name: Name<'src>, second_type: &'static str, duplicates_allowed: bool, ) -> CompileResult<'src> { if let Some((first_type, original)) = definitions.get(name.lexeme()) { if !(*first_type == second_type && duplicates_allowed) { let ((first_type, second_type), (original, redefinition)) = if name.line < original.line { ((second_type, *first_type), (name, *original)) } else { ((*first_type, second_type), (*original, name)) }; return Err(redefinition.token.error(Redefinition { first_type, second_type, name: name.lexeme(), first: original.line, })); } } definitions.insert(name.lexeme(), (second_type, name)); Ok(()) } fn analyze_recipe(recipe: &UnresolvedRecipe<'src>) -> CompileResult<'src> { let mut parameters = BTreeSet::new(); let mut passed_default = false; for parameter in &recipe.parameters { if parameters.contains(parameter.name.lexeme()) { return Err(parameter.name.token.error(DuplicateParameter { recipe: recipe.name.lexeme(), parameter: parameter.name.lexeme(), })); } parameters.insert(parameter.name.lexeme()); if parameter.default.is_some() { passed_default = true; } else if passed_default && parameter.is_required() { return Err( parameter .name .token .error(RequiredParameterFollowsDefaultParameter { parameter: parameter.name.lexeme(), }), ); } } let mut continued = false; for line in &recipe.body { if !recipe.is_script() && !continued { if let Some(Fragment::Text { token }) = line.fragments.first() { let text = token.lexeme(); if text.starts_with(' ') || text.starts_with('\t') { return Err(token.error(ExtraLeadingWhitespace)); } } } continued = line.is_continuation(); } if !recipe.is_script() { if let Some(attribute) = recipe.attributes.get(AttributeDiscriminant::Extension) { return Err(recipe.name.error(InvalidAttribute { item_kind: "Recipe", item_name: recipe.name.lexeme(), attribute: attribute.clone(), })); } } Ok(()) } fn analyze_set(&self, set: &Set<'src>) -> CompileResult<'src> { if let Some(original) = self.sets.get(set.name.lexeme()) { return Err(set.name.error(DuplicateSet { setting: original.name.lexeme(), first: original.name.line, })); } Ok(()) } fn resolve_alias<'a>( modules: &'a Table<'src, Justfile<'src>>, recipes: &'a Table<'src, Rc>>, alias: Alias<'src, Namepath<'src>>, ) -> CompileResult<'src, Alias<'src>> { match Self::alias_target(&alias.target, modules, recipes) { Some(target) => Ok(alias.resolve(target)), None => Err(alias.name.token.error(UnknownAliasTarget { alias: alias.name.lexeme(), target: alias.target, })), } } fn alias_target<'a>( path: &Namepath<'src>, mut modules: &'a Table<'src, Justfile<'src>>, mut recipes: &'a Table<'src, Rc>>, ) -> Option>> { let (name, path) = path.split_last(); for name in path { let module = modules.get(name.lexeme())?; modules = &module.modules; recipes = &module.recipes; } recipes.get(name.lexeme()).cloned() } } #[cfg(test)] mod tests { use super::*; analysis_error! { name: duplicate_alias, input: "alias foo := bar\nalias foo := baz", offset: 23, line: 1, column: 6, width: 3, kind: Redefinition { first_type: "alias", second_type: "alias", name: "foo", first: 0 }, } analysis_error! { name: unknown_alias_target, input: "alias foo := bar\n", offset: 6, line: 0, column: 6, width: 3, kind: UnknownAliasTarget { alias: "foo", target: Namepath::from(Name::from_identifier( Token{ column: 13, kind: TokenKind::Identifier, length: 3, line: 0, offset: 13, path: Path::new("justfile"), src: "alias foo := bar\n", } )) }, } analysis_error! { name: alias_shadows_recipe_before, input: "bar: \n echo bar\nalias foo := bar\nfoo:\n echo foo", offset: 34, line: 3, column: 0, width: 3, kind: Redefinition { first_type: "alias", second_type: "recipe", name: "foo", first: 2 }, } analysis_error! { name: alias_shadows_recipe_after, input: "foo:\n echo foo\nalias foo := bar\nbar:\n echo bar", offset: 22, line: 2, column: 6, width: 3, kind: Redefinition { first_type: "recipe", second_type: "alias", name: "foo", first: 0 }, } analysis_error! { name: required_after_default, input: "hello arg='foo' bar:", offset: 16, line: 0, column: 16, width: 3, kind: RequiredParameterFollowsDefaultParameter{parameter: "bar"}, } analysis_error! { name: duplicate_parameter, input: "a b b:", offset: 4, line: 0, column: 4, width: 1, kind: DuplicateParameter{recipe: "a", parameter: "b"}, } analysis_error! { name: duplicate_variadic_parameter, input: "a b +b:", offset: 5, line: 0, column: 5, width: 1, kind: DuplicateParameter{recipe: "a", parameter: "b"}, } analysis_error! { name: duplicate_recipe, input: "a:\nb:\na:", offset: 6, line: 2, column: 0, width: 1, kind: Redefinition { first_type: "recipe", second_type: "recipe", name: "a", first: 0 }, } analysis_error! { name: duplicate_variable, input: "a := \"0\"\na := \"0\"", offset: 9, line: 1, column: 0, width: 1, kind: DuplicateVariable{variable: "a"}, } analysis_error! { name: extra_whitespace, input: "a:\n blah\n blarg", offset: 10, line: 2, column: 1, width: 6, kind: ExtraLeadingWhitespace, } } just-1.40.0/src/argument_parser.rs000064400000000000000000000252671046102023000152420ustar 00000000000000use super::*; #[allow(clippy::doc_markdown)] /// The argument parser is responsible for grouping positional arguments into /// argument groups, which consist of a path to a recipe and its arguments. /// /// Argument parsing is substantially complicated by the fact that recipe paths /// can be given on the command line as multiple arguments, i.e., "foo" "bar" /// baz", or as a single "::"-separated argument. /// /// Error messages produced by the argument parser should use the format of the /// recipe path as passed on the command line. /// /// Additionally, if a recipe is specified with a "::"-separated path, extra /// components of that path after a valid recipe must not be used as arguments, /// whereas arguments after multiple argument path may be used as arguments. As /// an example, `foo bar baz` may refer to recipe `foo::bar` with argument /// `baz`, but `foo::bar::baz` is an error, since `bar` is a recipe, not a /// module. pub(crate) struct ArgumentParser<'src: 'run, 'run> { arguments: &'run [&'run str], next: usize, root: &'run Justfile<'src>, } #[derive(Debug, PartialEq)] pub(crate) struct ArgumentGroup<'run> { pub(crate) arguments: Vec<&'run str>, pub(crate) path: Vec, } impl<'src: 'run, 'run> ArgumentParser<'src, 'run> { pub(crate) fn parse_arguments( root: &'run Justfile<'src>, arguments: &'run [&'run str], ) -> RunResult<'src, Vec>> { let mut groups = Vec::new(); let mut invocation_parser = Self { arguments, next: 0, root, }; loop { groups.push(invocation_parser.parse_group()?); if invocation_parser.next == arguments.len() { break; } } Ok(groups) } fn parse_group(&mut self) -> RunResult<'src, ArgumentGroup<'run>> { let (recipe, path) = if let Some(next) = self.next() { if next.contains(':') { let module_path = ModulePath::try_from([next].as_slice()).map_err(|()| Error::UnknownRecipe { recipe: next.into(), suggestion: None, })?; let (recipe, path, _) = self.resolve_recipe(true, &module_path.path)?; self.next += 1; (recipe, path) } else { let (recipe, path, consumed) = self.resolve_recipe(false, self.rest())?; self.next += consumed; (recipe, path) } } else { let (recipe, path, consumed) = self.resolve_recipe(false, self.rest())?; assert_eq!(consumed, 0); (recipe, path) }; let rest = self.rest(); let argument_range = recipe.argument_range(); let argument_count = cmp::min(rest.len(), recipe.max_arguments()); if !argument_range.range_contains(&argument_count) { return Err(Error::ArgumentCountMismatch { recipe: recipe.name(), parameters: recipe.parameters.clone(), found: rest.len(), min: recipe.min_arguments(), max: recipe.max_arguments(), }); } let arguments = rest[..argument_count].to_vec(); self.next += argument_count; Ok(ArgumentGroup { arguments, path }) } fn resolve_recipe( &self, module_path: bool, args: &[impl AsRef], ) -> RunResult<'src, (&'run Recipe<'src>, Vec, usize)> { let mut current = self.root; let mut path = Vec::new(); for (i, arg) in args.iter().enumerate() { let arg = arg.as_ref(); path.push(arg.to_string()); if let Some(module) = current.modules.get(arg) { current = module; } else if let Some(recipe) = current.get_recipe(arg) { if module_path && i + 1 < args.len() { return Err(Error::ExpectedSubmoduleButFoundRecipe { path: if module_path { path.join("::") } else { path.join(" ") }, }); } return Ok((recipe, path, i + 1)); } else { if module_path && i + 1 < args.len() { return Err(Error::UnknownSubmodule { path: path.join("::"), }); } return Err(Error::UnknownRecipe { recipe: if module_path { path.join("::") } else { path.join(" ") }, suggestion: current.suggest_recipe(arg), }); } } if let Some(recipe) = ¤t.default { recipe.check_can_be_default_recipe()?; path.push(recipe.name().into()); Ok((recipe, path, args.len())) } else if current.recipes.is_empty() { Err(Error::NoRecipes) } else { Err(Error::NoDefaultRecipe) } } fn next(&self) -> Option<&'run str> { self.arguments.get(self.next).copied() } fn rest(&self) -> &[&'run str] { &self.arguments[self.next..] } } #[cfg(test)] mod tests { use {super::*, tempfile::TempDir}; trait TempDirExt { fn write(&self, path: &str, content: &str); } impl TempDirExt for TempDir { fn write(&self, path: &str, content: &str) { let path = self.path().join(path); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, content).unwrap(); } } #[test] fn single_no_arguments() { let justfile = testing::compile("foo:"); assert_eq!( ArgumentParser::parse_arguments(&justfile, &["foo"]).unwrap(), vec![ArgumentGroup { path: vec!["foo".into()], arguments: Vec::new() }], ); } #[test] fn single_with_argument() { let justfile = testing::compile("foo bar:"); assert_eq!( ArgumentParser::parse_arguments(&justfile, &["foo", "baz"]).unwrap(), vec![ArgumentGroup { path: vec!["foo".into()], arguments: vec!["baz"], }], ); } #[test] fn single_argument_count_mismatch() { let justfile = testing::compile("foo bar:"); assert_matches!( ArgumentParser::parse_arguments(&justfile, &["foo"]).unwrap_err(), Error::ArgumentCountMismatch { recipe: "foo", found: 0, min: 1, max: 1, .. }, ); } #[test] fn single_unknown() { let justfile = testing::compile("foo:"); assert_matches!( ArgumentParser::parse_arguments(&justfile, &["bar"]).unwrap_err(), Error::UnknownRecipe { recipe, suggestion: None } if recipe == "bar", ); } #[test] fn multiple_unknown() { let justfile = testing::compile("foo:"); assert_matches!( ArgumentParser::parse_arguments(&justfile, &["bar", "baz"]).unwrap_err(), Error::UnknownRecipe { recipe, suggestion: None } if recipe == "bar", ); } #[test] fn recipe_in_submodule() { let loader = Loader::new(); let tempdir = tempfile::tempdir().unwrap(); let path = tempdir.path().join("justfile"); fs::write(&path, "mod foo").unwrap(); fs::create_dir(tempdir.path().join("foo")).unwrap(); fs::write(tempdir.path().join("foo/mod.just"), "bar:").unwrap(); let compilation = Compiler::compile(&loader, &path).unwrap(); assert_eq!( ArgumentParser::parse_arguments(&compilation.justfile, &["foo", "bar"]).unwrap(), vec![ArgumentGroup { path: vec!["foo".into(), "bar".into()], arguments: Vec::new() }], ); } #[test] fn recipe_in_submodule_unknown() { let loader = Loader::new(); let tempdir = tempfile::tempdir().unwrap(); let path = tempdir.path().join("justfile"); fs::write(&path, "mod foo").unwrap(); fs::create_dir(tempdir.path().join("foo")).unwrap(); fs::write(tempdir.path().join("foo/mod.just"), "bar:").unwrap(); let compilation = Compiler::compile(&loader, &path).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &["foo", "zzz"]).unwrap_err(), Error::UnknownRecipe { recipe, suggestion: None } if recipe == "foo zzz", ); } #[test] fn recipe_in_submodule_path_unknown() { let tempdir = tempfile::tempdir().unwrap(); tempdir.write("justfile", "mod foo"); tempdir.write("foo.just", "bar:"); let loader = Loader::new(); let compilation = Compiler::compile(&loader, &tempdir.path().join("justfile")).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &["foo::zzz"]).unwrap_err(), Error::UnknownRecipe { recipe, suggestion: None } if recipe == "foo::zzz", ); } #[test] fn module_path_not_consumed() { let tempdir = tempfile::tempdir().unwrap(); tempdir.write("justfile", "mod foo"); tempdir.write("foo.just", "bar:"); let loader = Loader::new(); let compilation = Compiler::compile(&loader, &tempdir.path().join("justfile")).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &["foo::bar::baz"]).unwrap_err(), Error::ExpectedSubmoduleButFoundRecipe { path, } if path == "foo::bar", ); } #[test] fn no_recipes() { let tempdir = tempfile::tempdir().unwrap(); tempdir.write("justfile", ""); let loader = Loader::new(); let compilation = Compiler::compile(&loader, &tempdir.path().join("justfile")).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &[]).unwrap_err(), Error::NoRecipes, ); } #[test] fn default_recipe_requires_arguments() { let tempdir = tempfile::tempdir().unwrap(); tempdir.write("justfile", "foo bar:"); let loader = Loader::new(); let compilation = Compiler::compile(&loader, &tempdir.path().join("justfile")).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &[]).unwrap_err(), Error::DefaultRecipeRequiresArguments { recipe: "foo", min_arguments: 1, }, ); } #[test] fn no_default_recipe() { let tempdir = tempfile::tempdir().unwrap(); tempdir.write("justfile", "import 'foo.just'"); tempdir.write("foo.just", "bar:"); let loader = Loader::new(); let compilation = Compiler::compile(&loader, &tempdir.path().join("justfile")).unwrap(); assert_matches!( ArgumentParser::parse_arguments(&compilation.justfile, &[]).unwrap_err(), Error::NoDefaultRecipe, ); } #[test] fn complex_grouping() { let justfile = testing::compile( " FOO A B='blarg': echo foo: {{A}} {{B}} BAR X: echo bar: {{X}} BAZ +Z: echo baz: {{Z}} ", ); assert_eq!( ArgumentParser::parse_arguments( &justfile, &["BAR", "0", "FOO", "1", "2", "BAZ", "3", "4", "5"] ) .unwrap(), vec![ ArgumentGroup { path: vec!["BAR".into()], arguments: vec!["0"], }, ArgumentGroup { path: vec!["FOO".into()], arguments: vec!["1", "2"], }, ArgumentGroup { path: vec!["BAZ".into()], arguments: vec!["3", "4", "5"], }, ], ); } } just-1.40.0/src/assignment.rs000064400000000000000000000005741046102023000142060ustar 00000000000000use super::*; /// An assignment, e.g `foo := bar` pub(crate) type Assignment<'src> = Binding<'src, Expression<'src>>; impl Display for Assignment<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.private { writeln!(f, "[private]")?; } if self.export { write!(f, "export ")?; } write!(f, "{} := {}", self.name, self.value) } } just-1.40.0/src/assignment_resolver.rs000064400000000000000000000064561046102023000161340ustar 00000000000000use {super::*, CompileErrorKind::*}; pub(crate) struct AssignmentResolver<'src: 'run, 'run> { assignments: &'run Table<'src, Assignment<'src>>, evaluated: BTreeSet<&'src str>, stack: Vec<&'src str>, } impl<'src: 'run, 'run> AssignmentResolver<'src, 'run> { pub(crate) fn resolve_assignments( assignments: &'run Table<'src, Assignment<'src>>, ) -> CompileResult<'src> { let mut resolver = Self { stack: Vec::new(), evaluated: BTreeSet::new(), assignments, }; for name in assignments.keys() { resolver.resolve_assignment(name)?; } Ok(()) } fn resolve_assignment(&mut self, name: &'src str) -> CompileResult<'src> { if self.evaluated.contains(name) { return Ok(()); } self.stack.push(name); if let Some(assignment) = self.assignments.get(name) { for variable in assignment.value.variables() { let name = variable.lexeme(); if self.evaluated.contains(name) || constants().contains_key(name) { continue; } if self.stack.contains(&name) { self.stack.push(name); return Err( self.assignments[name] .name .error(CircularVariableDependency { variable: name, circle: self.stack.clone(), }), ); } else if self.assignments.contains_key(name) { self.resolve_assignment(name)?; } else { return Err(variable.error(UndefinedVariable { variable: name })); } } self.evaluated.insert(name); } else { let message = format!("attempted to resolve unknown assignment `{name}`"); let token = Token { src: "", offset: 0, line: 0, column: 0, length: 0, kind: TokenKind::Unspecified, path: "".as_ref(), }; return Err(CompileError::new(token, Internal { message })); } self.stack.pop(); Ok(()) } } #[cfg(test)] mod tests { use super::*; analysis_error! { name: circular_variable_dependency, input: "a := b\nb := a", offset: 0, line: 0, column: 0, width: 1, kind: CircularVariableDependency{variable: "a", circle: vec!["a", "b", "a"]}, } analysis_error! { name: self_variable_dependency, input: "a := a", offset: 0, line: 0, column: 0, width: 1, kind: CircularVariableDependency{variable: "a", circle: vec!["a", "a"]}, } analysis_error! { name: unknown_expression_variable, input: "x := yy", offset: 5, line: 0, column: 5, width: 2, kind: UndefinedVariable{variable: "yy"}, } analysis_error! { name: unknown_function_parameter, input: "x := env_var(yy)", offset: 13, line: 0, column: 13, width: 2, kind: UndefinedVariable{variable: "yy"}, } analysis_error! { name: unknown_function_parameter_binary_first, input: "x := env_var_or_default(yy, 'foo')", offset: 24, line: 0, column: 24, width: 2, kind: UndefinedVariable{variable: "yy"}, } analysis_error! { name: unknown_function_parameter_binary_second, input: "x := env_var_or_default('foo', yy)", offset: 31, line: 0, column: 31, width: 2, kind: UndefinedVariable{variable: "yy"}, } } just-1.40.0/src/ast.rs000064400000000000000000000016251046102023000126230ustar 00000000000000use super::*; /// The top-level type produced by the parser. Not all successful parses result /// in valid justfiles, so additional consistency checks and name resolution /// are performed by the `Analyzer`, which produces a `Justfile` from an `Ast`. #[derive(Debug, Clone)] pub(crate) struct Ast<'src> { pub(crate) items: Vec>, pub(crate) unstable_features: BTreeSet, pub(crate) warnings: Vec, pub(crate) working_directory: PathBuf, } impl Display for Ast<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut iter = self.items.iter().peekable(); while let Some(item) = iter.next() { writeln!(f, "{item}")?; if let Some(next_item) = iter.peek() { if matches!(item, Item::Recipe(_)) || mem::discriminant(item) != mem::discriminant(next_item) { writeln!(f)?; } } } Ok(()) } } just-1.40.0/src/attribute.rs000064400000000000000000000106751046102023000140440ustar 00000000000000use super::*; #[derive( EnumDiscriminants, PartialEq, Debug, Clone, Serialize, Ord, PartialOrd, Eq, IntoStaticStr, )] #[strum(serialize_all = "kebab-case")] #[serde(rename_all = "kebab-case")] #[strum_discriminants(name(AttributeDiscriminant))] #[strum_discriminants(derive(EnumString, Ord, PartialOrd))] #[strum_discriminants(strum(serialize_all = "kebab-case"))] pub(crate) enum Attribute<'src> { Confirm(Option>), Doc(Option>), ExitMessage, Extension(StringLiteral<'src>), Group(StringLiteral<'src>), Linux, Macos, NoCd, NoExitMessage, NoQuiet, Openbsd, PositionalArguments, Private, Script(Option>), Unix, Windows, WorkingDirectory(StringLiteral<'src>), } impl AttributeDiscriminant { fn argument_range(self) -> RangeInclusive { match self { Self::Confirm | Self::Doc => 0..=1, Self::Group | Self::Extension | Self::WorkingDirectory => 1..=1, Self::ExitMessage | Self::Linux | Self::Macos | Self::NoCd | Self::NoExitMessage | Self::NoQuiet | Self::Openbsd | Self::PositionalArguments | Self::Private | Self::Unix | Self::Windows => 0..=0, Self::Script => 0..=usize::MAX, } } } impl<'src> Attribute<'src> { pub(crate) fn new( name: Name<'src>, arguments: Vec>, ) -> CompileResult<'src, Self> { let discriminant = name .lexeme() .parse::() .ok() .ok_or_else(|| { name.error(CompileErrorKind::UnknownAttribute { attribute: name.lexeme(), }) })?; let found = arguments.len(); let range = discriminant.argument_range(); if !range.contains(&found) { return Err( name.error(CompileErrorKind::AttributeArgumentCountMismatch { attribute: name.lexeme(), found, min: *range.start(), max: *range.end(), }), ); } Ok(match discriminant { AttributeDiscriminant::Confirm => Self::Confirm(arguments.into_iter().next()), AttributeDiscriminant::Doc => Self::Doc(arguments.into_iter().next()), AttributeDiscriminant::ExitMessage => Self::ExitMessage, AttributeDiscriminant::Extension => Self::Extension(arguments.into_iter().next().unwrap()), AttributeDiscriminant::Group => Self::Group(arguments.into_iter().next().unwrap()), AttributeDiscriminant::Linux => Self::Linux, AttributeDiscriminant::Macos => Self::Macos, AttributeDiscriminant::NoCd => Self::NoCd, AttributeDiscriminant::NoExitMessage => Self::NoExitMessage, AttributeDiscriminant::NoQuiet => Self::NoQuiet, AttributeDiscriminant::Openbsd => Self::Openbsd, AttributeDiscriminant::PositionalArguments => Self::PositionalArguments, AttributeDiscriminant::Private => Self::Private, AttributeDiscriminant::Script => Self::Script({ let mut arguments = arguments.into_iter(); arguments.next().map(|command| Interpreter { command, arguments: arguments.collect(), }) }), AttributeDiscriminant::Unix => Self::Unix, AttributeDiscriminant::Windows => Self::Windows, AttributeDiscriminant::WorkingDirectory => { Self::WorkingDirectory(arguments.into_iter().next().unwrap()) } }) } pub(crate) fn discriminant(&self) -> AttributeDiscriminant { self.into() } pub(crate) fn name(&self) -> &'static str { self.into() } pub(crate) fn repeatable(&self) -> bool { matches!(self, Attribute::Group(_)) } } impl Display for Attribute<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.name())?; match self { Self::Confirm(Some(argument)) | Self::Doc(Some(argument)) | Self::Extension(argument) | Self::Group(argument) | Self::WorkingDirectory(argument) => write!(f, "({argument})")?, Self::Script(Some(shell)) => write!(f, "({shell})")?, Self::Confirm(None) | Self::Doc(None) | Self::ExitMessage | Self::Linux | Self::Macos | Self::NoCd | Self::NoExitMessage | Self::NoQuiet | Self::Openbsd | Self::PositionalArguments | Self::Private | Self::Script(None) | Self::Unix | Self::Windows => {} } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn name() { assert_eq!(Attribute::NoExitMessage.name(), "no-exit-message"); } } just-1.40.0/src/attribute_set.rs000064400000000000000000000035101046102023000147050ustar 00000000000000use {super::*, std::collections}; #[derive(Default, Debug, Clone, PartialEq, Serialize)] pub(crate) struct AttributeSet<'src>(BTreeSet>); impl<'src> AttributeSet<'src> { pub(crate) fn len(&self) -> usize { self.0.len() } pub(crate) fn contains(&self, target: AttributeDiscriminant) -> bool { self.0.iter().any(|attr| attr.discriminant() == target) } pub(crate) fn get(&self, discriminant: AttributeDiscriminant) -> Option<&Attribute<'src>> { self .0 .iter() .find(|attr| discriminant == attr.discriminant()) } pub(crate) fn iter<'a>(&'a self) -> collections::btree_set::Iter<'a, Attribute<'src>> { self.0.iter() } pub(crate) fn ensure_valid_attributes( &self, item_kind: &'static str, item_token: Token<'src>, valid: &[AttributeDiscriminant], ) -> Result<(), CompileError<'src>> { for attribute in &self.0 { let discriminant = attribute.discriminant(); if !valid.contains(&discriminant) { return Err(item_token.error(CompileErrorKind::InvalidAttribute { item_kind, item_name: item_token.lexeme(), attribute: attribute.clone(), })); } } Ok(()) } } impl<'src> FromIterator> for AttributeSet<'src> { fn from_iter>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } impl<'src, 'a> IntoIterator for &'a AttributeSet<'src> { type Item = &'a Attribute<'src>; type IntoIter = collections::btree_set::Iter<'a, Attribute<'src>>; fn into_iter(self) -> Self::IntoIter { self.0.iter() } } impl<'src> IntoIterator for AttributeSet<'src> { type Item = Attribute<'src>; type IntoIter = collections::btree_set::IntoIter>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } just-1.40.0/src/binding.rs000064400000000000000000000007101046102023000134400ustar 00000000000000use super::*; /// A binding of `name` to `value` #[derive(Debug, Clone, PartialEq, Serialize)] pub(crate) struct Binding<'src, V = String> { #[serde(skip)] pub(crate) constant: bool, pub(crate) export: bool, #[serde(skip)] pub(crate) file_depth: u32, pub(crate) name: Name<'src>, pub(crate) private: bool, pub(crate) value: V, } impl<'src, V> Keyed<'src> for Binding<'src, V> { fn key(&self) -> &'src str { self.name.lexeme() } } just-1.40.0/src/color.rs000064400000000000000000000062271046102023000131550ustar 00000000000000use { super::*, ansi_term::{ANSIGenericString, Color::*, Prefix, Style, Suffix}, std::io::{self, IsTerminal}, }; #[derive(Copy, Clone, Debug, PartialEq)] pub(crate) struct Color { is_terminal: bool, style: Style, use_color: UseColor, } impl Color { pub(crate) fn active(&self) -> bool { match self.use_color { UseColor::Always => true, UseColor::Never => false, UseColor::Auto => self.is_terminal, } } pub(crate) fn alias(self) -> Self { self.restyle(Style::new().fg(Purple)) } pub(crate) fn always() -> Self { Self { use_color: UseColor::Always, ..Self::default() } } pub(crate) fn annotation(self) -> Self { self.restyle(Style::new().fg(Purple)) } pub(crate) fn auto() -> Self { Self::default() } pub(crate) fn banner(self) -> Self { self.restyle(Style::new().fg(Cyan).bold()) } pub(crate) fn command(self, foreground: Option) -> Self { self.restyle(Style { foreground, is_bold: true, ..Style::default() }) } pub(crate) fn context(self) -> Self { self.restyle(Style::new().fg(Blue).bold()) } pub(crate) fn diff_added(self) -> Self { self.restyle(Style::new().fg(Green)) } pub(crate) fn diff_deleted(self) -> Self { self.restyle(Style::new().fg(Red)) } pub(crate) fn doc(self) -> Self { self.restyle(Style::new().fg(Blue)) } pub(crate) fn doc_backtick(self) -> Self { self.restyle(Style::new().fg(Cyan)) } fn effective_style(&self) -> Style { if self.active() { self.style } else { Style::new() } } pub(crate) fn error(self) -> Self { self.restyle(Style::new().fg(Red).bold()) } pub(crate) fn group(self) -> Self { self.restyle(Style::new().fg(Yellow).bold()) } pub(crate) fn message(self) -> Self { self.restyle(Style::new().bold()) } pub(crate) fn never() -> Self { Self { use_color: UseColor::Never, ..Self::default() } } pub(crate) fn paint<'a>(&self, text: &'a str) -> ANSIGenericString<'a, str> { self.effective_style().paint(text) } pub(crate) fn parameter(self) -> Self { self.restyle(Style::new().fg(Cyan)) } pub(crate) fn prefix(&self) -> Prefix { self.effective_style().prefix() } fn redirect(self, stream: impl IsTerminal) -> Self { Self { is_terminal: stream.is_terminal(), ..self } } fn restyle(self, style: Style) -> Self { Self { style, ..self } } pub(crate) fn stderr(self) -> Self { self.redirect(io::stderr()) } pub(crate) fn stdout(self) -> Self { self.redirect(io::stdout()) } pub(crate) fn string(self) -> Self { self.restyle(Style::new().fg(Green)) } pub(crate) fn suffix(&self) -> Suffix { self.effective_style().suffix() } pub(crate) fn warning(self) -> Self { self.restyle(Style::new().fg(Yellow).bold()) } } impl From for Color { fn from(use_color: UseColor) -> Self { Self { use_color, ..Default::default() } } } impl Default for Color { fn default() -> Self { Self { is_terminal: false, style: Style::new(), use_color: UseColor::Auto, } } } just-1.40.0/src/color_display.rs000064400000000000000000000006211046102023000146720ustar 00000000000000use super::*; pub(crate) trait ColorDisplay { fn color_display(&self, color: Color) -> Wrapper where Self: Sized, { Wrapper(self, color) } fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result; } pub(crate) struct Wrapper<'a>(&'a dyn ColorDisplay, Color); impl Display for Wrapper<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.0.fmt(f, self.1) } } just-1.40.0/src/command_color.rs000064400000000000000000000010701046102023000146420ustar 00000000000000use super::*; #[derive(Copy, Clone, ValueEnum)] pub(crate) enum CommandColor { Black, Blue, Cyan, Green, Purple, Red, Yellow, } impl From for ansi_term::Color { fn from(command_color: CommandColor) -> Self { match command_color { CommandColor::Black => Self::Black, CommandColor::Blue => Self::Blue, CommandColor::Cyan => Self::Cyan, CommandColor::Green => Self::Green, CommandColor::Purple => Self::Purple, CommandColor::Red => Self::Red, CommandColor::Yellow => Self::Yellow, } } } just-1.40.0/src/command_ext.rs000064400000000000000000000021221046102023000143230ustar 00000000000000use super::*; pub(crate) trait CommandExt { fn export( &mut self, settings: &Settings, dotenv: &BTreeMap, scope: &Scope, unexports: &HashSet, ); fn export_scope(&mut self, settings: &Settings, scope: &Scope, unexports: &HashSet); } impl CommandExt for Command { fn export( &mut self, settings: &Settings, dotenv: &BTreeMap, scope: &Scope, unexports: &HashSet, ) { for (name, value) in dotenv { self.env(name, value); } if let Some(parent) = scope.parent() { self.export_scope(settings, parent, unexports); } } fn export_scope(&mut self, settings: &Settings, scope: &Scope, unexports: &HashSet) { if let Some(parent) = scope.parent() { self.export_scope(settings, parent, unexports); } for unexport in unexports { self.env_remove(unexport); } for binding in scope.bindings() { if binding.export || (settings.export && !binding.constant) { self.env(binding.name.lexeme(), &binding.value); } } } } just-1.40.0/src/compilation.rs000064400000000000000000000007031046102023000143460ustar 00000000000000use super::*; #[derive(Debug)] pub(crate) struct Compilation<'src> { pub(crate) asts: HashMap>, pub(crate) justfile: Justfile<'src>, pub(crate) root: PathBuf, pub(crate) srcs: HashMap, } impl<'src> Compilation<'src> { pub(crate) fn root_ast(&self) -> &Ast<'src> { self.asts.get(&self.root).unwrap() } pub(crate) fn root_src(&self) -> &'src str { self.srcs.get(&self.root).unwrap() } } just-1.40.0/src/compile_error.rs000064400000000000000000000240251046102023000146740ustar 00000000000000use super::*; #[derive(Debug, PartialEq)] pub(crate) struct CompileError<'src> { pub(crate) kind: Box>, pub(crate) token: Token<'src>, } impl<'src> CompileError<'src> { pub(crate) fn context(&self) -> Token<'src> { self.token } pub(crate) fn new(token: Token<'src>, kind: CompileErrorKind<'src>) -> CompileError<'src> { Self { token, kind: kind.into(), } } } fn capitalize(s: &str) -> String { let mut chars = s.chars(); match chars.next() { None => String::new(), Some(first) => first.to_uppercase().collect::() + chars.as_str(), } } impl Display for CompileError<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use CompileErrorKind::*; match &*self.kind { AttributeArgumentCountMismatch { attribute, found, min, max, } => { write!( f, "Attribute `{attribute}` got {found} {} but takes ", Count("argument", *found), )?; if min == max { let expected = min; write!(f, "{expected} {}", Count("argument", *expected)) } else if found < min { write!(f, "at least {min} {}", Count("argument", *min)) } else { write!(f, "at most {max} {}", Count("argument", *max)) } } BacktickShebang => write!(f, "Backticks may not start with `#!`"), CircularRecipeDependency { recipe, circle } => { if circle.len() == 2 { write!(f, "Recipe `{recipe}` depends on itself") } else { write!( f, "Recipe `{recipe}` has circular dependency `{}`", circle.join(" -> ") ) } } CircularVariableDependency { variable, circle } => { if circle.len() == 2 { write!(f, "Variable `{variable}` is defined in terms of itself") } else { write!( f, "Variable `{variable}` depends on its own value: `{}`", circle.join(" -> "), ) } } DependencyArgumentCountMismatch { dependency, found, min, max, } => { write!( f, "Dependency `{dependency}` got {found} {} but takes ", Count("argument", *found), )?; if min == max { let expected = min; write!(f, "{expected} {}", Count("argument", *expected)) } else if found < min { write!(f, "at least {min} {}", Count("argument", *min)) } else { write!(f, "at most {max} {}", Count("argument", *max)) } } DuplicateAttribute { attribute, first } => write!( f, "Recipe attribute `{attribute}` first used on line {} is duplicated on line {}", first.ordinal(), self.token.line.ordinal(), ), DuplicateParameter { recipe, parameter } => { write!(f, "Recipe `{recipe}` has duplicate parameter `{parameter}`") } DuplicateSet { setting, first } => write!( f, "Setting `{setting}` first set on line {} is redefined on line {}", first.ordinal(), self.token.line.ordinal(), ), DuplicateVariable { variable } => { write!(f, "Variable `{variable}` has multiple definitions") } DuplicateUnexport { variable } => { write!(f, "Variable `{variable}` is unexported multiple times") } ExitMessageAndNoExitMessageAttribute { recipe } => write!( f, "Recipe `{recipe}` has both `[exit-message]` and `[no-exit-message]` attributes" ), ExpectedKeyword { expected, found } => { let expected = List::or_ticked(expected); if found.kind == TokenKind::Identifier { write!( f, "Expected keyword {expected} but found identifier `{}`", found.lexeme() ) } else { write!(f, "Expected keyword {expected} but found `{}`", found.kind) } } ExportUnexported { variable } => { write!(f, "Variable {variable} is both exported and unexported") } ExtraLeadingWhitespace => write!(f, "Recipe line has extra leading whitespace"), ExtraneousAttributes { count } => { write!(f, "Extraneous {}", Count("attribute", *count)) } FunctionArgumentCountMismatch { function, found, expected, } => write!( f, "Function `{function}` called with {found} {} but takes {}", Count("argument", *found), expected.display(), ), Include => write!( f, "The `!include` directive has been stabilized as `import`" ), InconsistentLeadingWhitespace { expected, found } => write!( f, "Recipe line has inconsistent leading whitespace. Recipe started with `{}` but found \ line with `{}`", ShowWhitespace(expected), ShowWhitespace(found) ), Internal { message } => write!( f, "Internal error, this may indicate a bug in just: {message}\n\ consider filing an issue: https://github.com/casey/just/issues/new" ), InvalidAttribute { item_name, item_kind, attribute, } => write!( f, "{item_kind} `{item_name}` has invalid attribute `{}`", attribute.name(), ), InvalidEscapeSequence { character } => write!( f, "`\\{}` is not a valid escape sequence", match character { '`' => r"\`".to_owned(), '\\' => r"\".to_owned(), '\'' => r"'".to_owned(), '"' => r#"""#.to_owned(), _ => character.escape_default().collect(), } ), MismatchedClosingDelimiter { open, open_line, close, } => write!( f, "Mismatched closing delimiter `{}`. (Did you mean to close the `{}` on line {}?)", close.close(), open.open(), open_line.ordinal(), ), MixedLeadingWhitespace { whitespace } => write!( f, "Found a mix of tabs and spaces in leading whitespace: `{}`\nLeading whitespace may \ consist of tabs or spaces, but not both", ShowWhitespace(whitespace) ), NoCdAndWorkingDirectoryAttribute { recipe } => write!( f, "Recipe `{recipe}` has both `[no-cd]` and `[working-directory]` attributes" ), ParameterFollowsVariadicParameter { parameter } => { write!(f, "Parameter `{parameter}` follows variadic parameter") } ParsingRecursionDepthExceeded => write!(f, "Parsing recursion depth exceeded"), Redefinition { first, first_type, name, second_type, } => { if first_type == second_type { write!( f, "{} `{name}` first defined on line {} is redefined on line {}", capitalize(first_type), first.ordinal(), self.token.line.ordinal(), ) } else { write!( f, "{} `{name}` defined on line {} is redefined as {} {second_type} on line {}", capitalize(first_type), first.ordinal(), if *second_type == "alias" { "an" } else { "a" }, self.token.line.ordinal(), ) } } ShebangAndScriptAttribute { recipe } => write!( f, "Recipe `{recipe}` has both shebang line and `[script]` attribute" ), ShellExpansion { err } => write!(f, "Shell expansion failed: {err}"), RequiredParameterFollowsDefaultParameter { parameter } => write!( f, "Non-default parameter `{parameter}` follows default parameter" ), UndefinedVariable { variable } => write!(f, "Variable `{variable}` not defined"), UnexpectedCharacter { expected } => { write!(f, "Expected character {}", List::or_ticked(expected)) } UnexpectedClosingDelimiter { close } => { write!(f, "Unexpected closing delimiter `{}`", close.close()) } UnexpectedEndOfToken { expected } => { write!( f, "Expected character {} but found end-of-file", List::or_ticked(expected), ) } UnexpectedToken { expected, found } => { write!(f, "Expected {}, but found {found}", List::or(expected)) } UnicodeEscapeCharacter { character } => { write!(f, "expected hex digit [0-9A-Fa-f] but found `{character}`") } UnicodeEscapeDelimiter { character } => write!( f, "expected unicode escape sequence delimiter `{{` but found `{character}`" ), UnicodeEscapeEmpty => write!(f, "unicode escape sequences must not be empty"), UnicodeEscapeLength { hex } => write!( f, "unicode escape sequence starting with `\\u{{{hex}` longer than six hex digits" ), UnicodeEscapeRange { hex } => { write!( f, "unicode escape sequence value `{hex}` greater than maximum valid code point `10FFFF`", ) } UnicodeEscapeUnterminated => write!(f, "unterminated unicode escape sequence"), UnknownAliasTarget { alias, target } => { write!(f, "Alias `{alias}` has an unknown target `{target}`") } UnknownAttribute { attribute } => write!(f, "Unknown attribute `{attribute}`"), UnknownDependency { recipe, unknown } => { write!(f, "Recipe `{recipe}` has unknown dependency `{unknown}`") } UnknownFunction { function } => write!(f, "Call to unknown function `{function}`"), UnknownSetting { setting } => write!(f, "Unknown setting `{setting}`"), UnknownStartOfToken { start } => { write!(f, "Unknown start of token '{start}'")?; if !start.is_ascii_graphic() { write!(f, " (U+{:04X})", *start as u32)?; } Ok(()) } UnpairedCarriageReturn => write!(f, "Unpaired carriage return"), UnterminatedBacktick => write!(f, "Unterminated backtick"), UnterminatedInterpolation => write!(f, "Unterminated interpolation"), UnterminatedString => write!(f, "Unterminated string"), } } } just-1.40.0/src/compile_error_kind.rs000064400000000000000000000061431046102023000157020ustar 00000000000000use super::*; #[derive(Debug, PartialEq)] pub(crate) enum CompileErrorKind<'src> { AttributeArgumentCountMismatch { attribute: &'src str, found: usize, min: usize, max: usize, }, BacktickShebang, CircularRecipeDependency { recipe: &'src str, circle: Vec<&'src str>, }, CircularVariableDependency { variable: &'src str, circle: Vec<&'src str>, }, DependencyArgumentCountMismatch { dependency: &'src str, found: usize, min: usize, max: usize, }, DuplicateAttribute { attribute: &'src str, first: usize, }, DuplicateParameter { recipe: &'src str, parameter: &'src str, }, DuplicateSet { setting: &'src str, first: usize, }, DuplicateUnexport { variable: &'src str, }, DuplicateVariable { variable: &'src str, }, ExitMessageAndNoExitMessageAttribute { recipe: &'src str, }, ExpectedKeyword { expected: Vec, found: Token<'src>, }, ExportUnexported { variable: &'src str, }, ExtraLeadingWhitespace, ExtraneousAttributes { count: usize, }, FunctionArgumentCountMismatch { function: &'src str, found: usize, expected: RangeInclusive, }, Include, InconsistentLeadingWhitespace { expected: &'src str, found: &'src str, }, Internal { message: String, }, InvalidAttribute { item_kind: &'static str, item_name: &'src str, attribute: Attribute<'src>, }, InvalidEscapeSequence { character: char, }, MismatchedClosingDelimiter { close: Delimiter, open: Delimiter, open_line: usize, }, MixedLeadingWhitespace { whitespace: &'src str, }, NoCdAndWorkingDirectoryAttribute { recipe: &'src str, }, ParameterFollowsVariadicParameter { parameter: &'src str, }, ParsingRecursionDepthExceeded, Redefinition { first: usize, first_type: &'static str, name: &'src str, second_type: &'static str, }, RequiredParameterFollowsDefaultParameter { parameter: &'src str, }, ShebangAndScriptAttribute { recipe: &'src str, }, ShellExpansion { err: shellexpand::LookupError, }, UndefinedVariable { variable: &'src str, }, UnexpectedCharacter { expected: Vec, }, UnexpectedClosingDelimiter { close: Delimiter, }, UnexpectedEndOfToken { expected: Vec, }, UnexpectedToken { expected: Vec, found: TokenKind, }, UnicodeEscapeCharacter { character: char, }, UnicodeEscapeDelimiter { character: char, }, UnicodeEscapeEmpty, UnicodeEscapeLength { hex: String, }, UnicodeEscapeRange { hex: String, }, UnicodeEscapeUnterminated, UnknownAliasTarget { alias: &'src str, target: Namepath<'src>, }, UnknownAttribute { attribute: &'src str, }, UnknownDependency { recipe: &'src str, unknown: &'src str, }, UnknownFunction { function: &'src str, }, UnknownSetting { setting: &'src str, }, UnknownStartOfToken { start: char, }, UnpairedCarriageReturn, UnterminatedBacktick, UnterminatedInterpolation, UnterminatedString, } just-1.40.0/src/compiler.rs000064400000000000000000000240051046102023000136430ustar 00000000000000use super::*; pub(crate) struct Compiler; impl Compiler { pub(crate) fn compile<'src>( loader: &'src Loader, root: &Path, ) -> RunResult<'src, Compilation<'src>> { let mut asts = HashMap::::new(); let mut loaded = Vec::new(); let mut paths = HashMap::::new(); let mut srcs = HashMap::::new(); let mut stack = Vec::new(); stack.push(Source::root(root)); while let Some(current) = stack.pop() { let (relative, src) = loader.load(root, ¤t.path)?; loaded.push(relative.into()); let tokens = Lexer::lex(relative, src)?; let mut ast = Parser::parse( current.file_depth, ¤t.import_offsets, current.namepath.as_ref(), &tokens, ¤t.working_directory, )?; paths.insert(current.path.clone(), relative.into()); srcs.insert(current.path.clone(), src); for item in &mut ast.items { match item { Item::Module { absolute, name, optional, relative, .. } => { let parent = current.path.parent().unwrap(); let relative = relative .as_ref() .map(|relative| Self::expand_tilde(&relative.cooked)) .transpose()?; let import = Self::find_module_file(parent, *name, relative.as_deref())?; if let Some(import) = import { if current.file_path.contains(&import) { return Err(Error::CircularImport { current: current.path, import, }); } *absolute = Some(import.clone()); stack.push(current.module(*name, import)); } else if !*optional { return Err(Error::MissingModuleFile { module: *name }); } } Item::Import { relative, absolute, optional, path, } => { let import = current .path .parent() .unwrap() .join(Self::expand_tilde(&relative.cooked)?) .lexiclean(); if import.is_file() { if current.file_path.contains(&import) { return Err(Error::CircularImport { current: current.path, import, }); } *absolute = Some(import.clone()); stack.push(current.import(import, path.offset)); } else if !*optional { return Err(Error::MissingImportFile { path: *path }); } } _ => {} } } asts.insert(current.path, ast.clone()); } let justfile = Analyzer::analyze(&asts, None, &[], &loaded, None, &paths, root)?; Ok(Compilation { asts, justfile, root: root.into(), srcs, }) } fn find_module_file<'src>( parent: &Path, module: Name<'src>, path: Option<&Path>, ) -> RunResult<'src, Option> { let mut candidates = Vec::new(); if let Some(path) = path { let full = parent.join(path); if full.is_file() { return Ok(Some(full)); } candidates.push((path.join("mod.just"), true)); for name in search::JUSTFILE_NAMES { candidates.push((path.join(name), false)); } } else { candidates.push((format!("{module}.just").into(), true)); candidates.push((format!("{module}/mod.just").into(), true)); for name in search::JUSTFILE_NAMES { candidates.push((format!("{module}/{name}").into(), false)); } } let mut grouped = BTreeMap::>::new(); for (candidate, case_sensitive) in candidates { let candidate = parent.join(candidate).lexiclean(); grouped .entry(candidate.parent().unwrap().into()) .or_default() .push((candidate, case_sensitive)); } let mut found = Vec::new(); for (directory, candidates) in grouped { let entries = match fs::read_dir(&directory) { Ok(entries) => entries, Err(io_error) => { if io_error.kind() == io::ErrorKind::NotFound { continue; } return Err( SearchError::Io { io_error, directory, } .into(), ); } }; for entry in entries { let entry = entry.map_err(|io_error| SearchError::Io { io_error, directory: directory.clone(), })?; if let Some(name) = entry.file_name().to_str() { for (candidate, case_sensitive) in &candidates { let candidate_name = candidate.file_name().unwrap().to_str().unwrap(); let eq = if *case_sensitive { name == candidate_name } else { name.eq_ignore_ascii_case(candidate_name) }; if eq { found.push(candidate.parent().unwrap().join(name)); } } } } } if found.len() > 1 { found.sort(); Err(Error::AmbiguousModuleFile { found: found .into_iter() .map(|found| found.strip_prefix(parent).unwrap().into()) .collect(), module, }) } else { Ok(found.into_iter().next()) } } fn expand_tilde(path: &str) -> RunResult<'static, PathBuf> { Ok(if let Some(path) = path.strip_prefix("~/") { dirs::home_dir() .ok_or(Error::Homedir)? .join(path.trim_start_matches('/')) } else { PathBuf::from(path) }) } #[cfg(test)] pub(crate) fn test_compile(src: &str) -> CompileResult { let tokens = Lexer::test_lex(src)?; let ast = Parser::parse(0, &[], None, &tokens, &PathBuf::new())?; let root = PathBuf::from("justfile"); let mut asts: HashMap = HashMap::new(); asts.insert(root.clone(), ast); let mut paths: HashMap = HashMap::new(); paths.insert(root.clone(), root.clone()); Analyzer::analyze(&asts, None, &[], &[], None, &paths, &root) } } #[cfg(test)] mod tests { use {super::*, temptree::temptree}; #[test] fn include_justfile() { let justfile_a = r#" # A comment at the top of the file import "./justfile_b" #some_recipe: recipe_b some_recipe: echo "some recipe" "#; let justfile_b = r#"import "./subdir/justfile_c" recipe_b: recipe_c echo "recipe b" "#; let justfile_c = r#"recipe_c: echo "recipe c" "#; let tmp = temptree! { justfile: justfile_a, justfile_b: justfile_b, subdir: { justfile_c: justfile_c } }; let loader = Loader::new(); let justfile_a_path = tmp.path().join("justfile"); let compilation = Compiler::compile(&loader, &justfile_a_path).unwrap(); assert_eq!(compilation.root_src(), justfile_a); } #[test] fn recursive_includes_fail() { let tmp = temptree! { justfile: "import './subdir/b'\na: b", subdir: { b: "import '../justfile'\nb:" } }; let loader = Loader::new(); let justfile_a_path = tmp.path().join("justfile"); let loader_output = Compiler::compile(&loader, &justfile_a_path).unwrap_err(); assert_matches!(loader_output, Error::CircularImport { current, import } if current == tmp.path().join("subdir").join("b").lexiclean() && import == tmp.path().join("justfile").lexiclean() ); } #[test] fn find_module_file() { #[track_caller] fn case(path: Option<&str>, files: &[&str], expected: Result, &[&str]>) { let module = Name { token: Token { column: 0, kind: TokenKind::Identifier, length: 3, line: 0, offset: 0, path: Path::new(""), src: "foo", }, }; let tempdir = tempfile::tempdir().unwrap(); for file in files { if let Some(parent) = Path::new(file).parent() { fs::create_dir_all(tempdir.path().join(parent)).unwrap(); } fs::write(tempdir.path().join(file), "").unwrap(); } let actual = Compiler::find_module_file(tempdir.path(), module, path.map(Path::new)); match expected { Err(expected) => match actual.unwrap_err() { Error::AmbiguousModuleFile { found, .. } => { assert_eq!( found, expected .iter() .map(|expected| expected.replace('/', std::path::MAIN_SEPARATOR_STR).into()) .collect::>() ); } _ => panic!("unexpected error"), }, Ok(Some(expected)) => assert_eq!( actual.unwrap().unwrap(), tempdir .path() .join(expected.replace('/', std::path::MAIN_SEPARATOR_STR)) ), Ok(None) => assert_eq!(actual.unwrap(), None), } } case(None, &["foo.just"], Ok(Some("foo.just"))); case(None, &["FOO.just"], Ok(None)); case(None, &["foo/mod.just"], Ok(Some("foo/mod.just"))); case(None, &["foo/MOD.just"], Ok(None)); case(None, &["foo/justfile"], Ok(Some("foo/justfile"))); case(None, &["foo/JUSTFILE"], Ok(Some("foo/JUSTFILE"))); case(None, &["foo/.justfile"], Ok(Some("foo/.justfile"))); case(None, &["foo/.JUSTFILE"], Ok(Some("foo/.JUSTFILE"))); case( None, &["foo/.justfile", "foo/justfile"], Err(&["foo/.justfile", "foo/justfile"]), ); case(None, &["foo/JUSTFILE"], Ok(Some("foo/JUSTFILE"))); case(Some("bar"), &["bar"], Ok(Some("bar"))); case(Some("bar"), &["bar/mod.just"], Ok(Some("bar/mod.just"))); case(Some("bar"), &["bar/justfile"], Ok(Some("bar/justfile"))); case(Some("bar"), &["bar/JUSTFILE"], Ok(Some("bar/JUSTFILE"))); case(Some("bar"), &["bar/.justfile"], Ok(Some("bar/.justfile"))); case(Some("bar"), &["bar/.JUSTFILE"], Ok(Some("bar/.JUSTFILE"))); case( Some("bar"), &["bar/justfile", "bar/mod.just"], Err(&["bar/justfile", "bar/mod.just"]), ); } } just-1.40.0/src/completions.rs000064400000000000000000000231001046102023000143600ustar 00000000000000use super::*; #[derive(ValueEnum, Debug, Clone, Copy, PartialEq)] pub(crate) enum Shell { Bash, Elvish, Fish, #[value(alias = "nu")] Nushell, Powershell, Zsh, } impl Shell { pub(crate) fn script(self) -> RunResult<'static, String> { match self { Self::Bash => completions::clap(clap_complete::Shell::Bash), Self::Elvish => completions::clap(clap_complete::Shell::Elvish), Self::Fish => completions::clap(clap_complete::Shell::Fish), Self::Nushell => Ok(completions::NUSHELL_COMPLETION_SCRIPT.into()), Self::Powershell => completions::clap(clap_complete::Shell::PowerShell), Self::Zsh => completions::clap(clap_complete::Shell::Zsh), } } } fn clap(shell: clap_complete::Shell) -> RunResult<'static, String> { fn replace(haystack: &mut String, needle: &str, replacement: &str) -> RunResult<'static, ()> { if let Some(index) = haystack.find(needle) { haystack.replace_range(index..index + needle.len(), replacement); Ok(()) } else { Err(Error::internal(format!( "Failed to find text:\n{needle}\n…in completion script:\n{haystack}" ))) } } let mut script = { let mut tempfile = tempfile().map_err(|io_error| Error::TempfileIo { io_error })?; clap_complete::generate( shell, &mut crate::config::Config::app(), env!("CARGO_PKG_NAME"), &mut tempfile, ); tempfile .rewind() .map_err(|io_error| Error::TempfileIo { io_error })?; let mut buffer = String::new(); tempfile .read_to_string(&mut buffer) .map_err(|io_error| Error::TempfileIo { io_error })?; buffer }; match shell { clap_complete::Shell::Bash => { for (needle, replacement) in completions::BASH_COMPLETION_REPLACEMENTS { replace(&mut script, needle, replacement)?; } } clap_complete::Shell::Fish => { script.insert_str(0, completions::FISH_RECIPE_COMPLETIONS); } clap_complete::Shell::PowerShell => { for (needle, replacement) in completions::POWERSHELL_COMPLETION_REPLACEMENTS { replace(&mut script, needle, replacement)?; } } clap_complete::Shell::Zsh => { for (needle, replacement) in completions::ZSH_COMPLETION_REPLACEMENTS { replace(&mut script, needle, replacement)?; } } _ => {} } Ok(script.trim().into()) } const NUSHELL_COMPLETION_SCRIPT: &str = r#"def "nu-complete just" [] { (^just --dump --unstable --dump-format json | from json).recipes | transpose recipe data | flatten | where {|row| $row.private == false } | select recipe doc parameters | rename value description } # Just: A Command Runner export extern "just" [ ...recipe: string@"nu-complete just", # Recipe(s) to run, may be with argument(s) ]"#; const FISH_RECIPE_COMPLETIONS: &str = r#"function __fish_just_complete_recipes if string match -rq '(-f|--justfile)\s*=?(?[^\s]+)' -- (string split -- ' -- ' (commandline -pc))[1] set -fx JUST_JUSTFILE "$justfile" end printf "%s\n" (string split " " (just --summary)) end # don't suggest files right off complete -c just -n "__fish_is_first_arg" --no-files # complete recipes complete -c just -a '(__fish_just_complete_recipes)' # autogenerated completions "#; const ZSH_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[ ( r#" _arguments "${_arguments_options[@]}" : \"#, r" local common=(", ), ( r"'*--set=[Override with ]:VARIABLE:_default:VARIABLE:_default' \", r"'*--set=[Override with ]: :(_just_variables)' \", ), ( r"'()-s+[Show recipe at ]:PATH:_default' \ '()--show=[Show recipe at ]:PATH:_default' \", r"'-s+[Show recipe at ]: :(_just_commands)' \ '--show=[Show recipe at ]: :(_just_commands)' \", ), ( "'*::ARGUMENTS -- Overrides and recipe(s) to run, defaulting to the first recipe in the \ justfile:_default' \\ && ret=0", r#") _arguments "${_arguments_options[@]}" $common \ '1: :_just_commands' \ '*: :->args' \ && ret=0 case $state in args) curcontext="${curcontext%:*}-${words[2]}:" local lastarg=${words[${#words}]} local recipe local cmds; cmds=( ${(s: :)$(_call_program commands just --summary)} ) # Find first recipe name for ((i = 2; i < $#words; i++ )) do if [[ ${cmds[(I)${words[i]}]} -gt 0 ]]; then recipe=${words[i]} break fi done if [[ $lastarg = */* ]]; then # Arguments contain slash would be recognised as a file _arguments -s -S $common '*:: :_files' elif [[ $lastarg = *=* ]]; then # Arguments contain equal would be recognised as a variable _message "value" elif [[ $recipe ]]; then # Show usage message _message "`just --show $recipe`" # Or complete with other commands #_arguments -s -S $common '*:: :_just_commands' else _arguments -s -S $common '*:: :_just_commands' fi ;; esac return ret "#, ), ( " local commands; commands=()", r#" [[ $PREFIX = -* ]] && return 1 integer ret=1 local variables; variables=( ${(s: :)$(_call_program commands just --variables)} ) local commands; commands=( ${${${(M)"${(f)$(_call_program commands just --list)}":# *}/ ##/}/ ##/:Args: } ) "#, ), ( r#" _describe -t commands 'just commands' commands "$@""#, r#" if compset -P '*='; then case "${${words[-1]%=*}#*=}" in *) _message 'value' && ret=0 ;; esac else _describe -t variables 'variables' variables -qS "=" && ret=0 _describe -t commands 'just commands' commands "$@" fi "#, ), ( r#"_just "$@""#, r#"(( $+functions[_just_variables] )) || _just_variables() { [[ $PREFIX = -* ]] && return 1 integer ret=1 local variables; variables=( ${(s: :)$(_call_program commands just --variables)} ) if compset -P '*='; then case "${${words[-1]%=*}#*=}" in *) _message 'value' && ret=0 ;; esac else _describe -t variables 'variables' variables && ret=0 fi return ret } _just "$@""#, ), ]; const POWERSHELL_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[( r#"$completions.Where{ $_.CompletionText -like "$wordToComplete*" } | Sort-Object -Property ListItemText"#, r#"function Get-JustFileRecipes([string[]]$CommandElements) { $justFileIndex = $commandElements.IndexOf("--justfile"); if ($justFileIndex -ne -1 -and $justFileIndex + 1 -le $commandElements.Length) { $justFileLocation = $commandElements[$justFileIndex + 1] } $justArgs = @("--summary") if (Test-Path $justFileLocation) { $justArgs += @("--justfile", $justFileLocation) } $recipes = $(just @justArgs) -split ' ' return $recipes | ForEach-Object { [CompletionResult]::new($_) } } $elementValues = $commandElements | Select-Object -ExpandProperty Value $recipes = Get-JustFileRecipes -CommandElements $elementValues $completions += $recipes $completions.Where{ $_.CompletionText -like "$wordToComplete*" } | Sort-Object -Property ListItemText"#, )]; const BASH_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[ ( r#" if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 fi"#, r#" if [[ ${cur} == -* ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 elif [[ ${COMP_CWORD} -eq 1 ]]; then local recipes=$(just --summary 2> /dev/null) if echo "${cur}" | \grep -qF '/'; then local path_prefix=$(echo "${cur}" | sed 's/[/][^/]*$/\//') local recipes=$(just --summary 2> /dev/null -- "${path_prefix}") local recipes=$(printf "${path_prefix}%s\t" $recipes) fi if [[ $? -eq 0 ]]; then COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") ) return 0 fi fi"#, ), ( r"local i cur prev opts cmd", r"local i cur prev words cword opts cmd", ), ( r#" cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}""#, r#" # Modules use "::" as the separator, which is considered a wordbreak character in bash. # The _get_comp_words_by_ref function is a hack to allow for exceptions to this rule without # modifying the global COMP_WORDBREAKS environment variable. if type _get_comp_words_by_ref &>/dev/null; then _get_comp_words_by_ref -n : cur prev words cword else cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" words=$COMP_WORDS cword=$COMP_CWORD fi "#, ), (r"for i in ${COMP_WORDS[@]}", r"for i in ${words[@]}"), ( r"elif [[ ${COMP_CWORD} -eq 1 ]]; then", r"elif [[ ${cword} -eq 1 ]]; then", ), ( r#"COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") )"#, r#"COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") ) if type __ltrim_colon_completions &>/dev/null; then __ltrim_colon_completions "$cur" fi"#, ), ]; just-1.40.0/src/condition.rs000064400000000000000000000013021046102023000140120ustar 00000000000000use super::*; #[derive(PartialEq, Debug, Clone)] pub(crate) struct Condition<'src> { pub(crate) lhs: Box>, pub(crate) operator: ConditionalOperator, pub(crate) rhs: Box>, } impl Display for Condition<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{} {} {}", self.lhs, self.operator, self.rhs) } } impl Serialize for Condition<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&self.operator.to_string())?; seq.serialize_element(&self.lhs)?; seq.serialize_element(&self.rhs)?; seq.end() } } just-1.40.0/src/conditional_operator.rs000064400000000000000000000010221046102023000162410ustar 00000000000000use super::*; /// A conditional expression operator. #[derive(PartialEq, Debug, Copy, Clone)] pub(crate) enum ConditionalOperator { /// `==` Equality, /// `!=` Inequality, /// `=~` RegexMatch, /// `!~` RegexMismatch, } impl Display for ConditionalOperator { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::Equality => write!(f, "=="), Self::Inequality => write!(f, "!="), Self::RegexMatch => write!(f, "=~"), Self::RegexMismatch => write!(f, "!~"), } } } just-1.40.0/src/config.rs000064400000000000000000001303651046102023000133050ustar 00000000000000use { super::*, clap::{ builder::{ styling::{AnsiColor, Effects}, FalseyValueParser, Styles, }, parser::ValuesRef, value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command, }, }; #[derive(Debug, PartialEq)] pub(crate) struct Config { pub(crate) alias_style: AliasStyle, pub(crate) allow_missing: bool, pub(crate) check: bool, pub(crate) color: Color, pub(crate) command_color: Option, pub(crate) dotenv_filename: Option, pub(crate) dotenv_path: Option, pub(crate) dry_run: bool, pub(crate) dump_format: DumpFormat, pub(crate) explain: bool, pub(crate) highlight: bool, pub(crate) invocation_directory: PathBuf, pub(crate) list_heading: String, pub(crate) list_prefix: String, pub(crate) list_submodules: bool, pub(crate) load_dotenv: bool, pub(crate) no_aliases: bool, pub(crate) no_dependencies: bool, pub(crate) one: bool, pub(crate) search_config: SearchConfig, pub(crate) shell: Option, pub(crate) shell_args: Option>, pub(crate) shell_command: bool, pub(crate) subcommand: Subcommand, pub(crate) timestamp: bool, pub(crate) timestamp_format: String, pub(crate) unsorted: bool, pub(crate) unstable: bool, pub(crate) verbosity: Verbosity, pub(crate) yes: bool, } mod cmd { pub(crate) const CHANGELOG: &str = "CHANGELOG"; pub(crate) const CHOOSE: &str = "CHOOSE"; pub(crate) const COMMAND: &str = "COMMAND"; pub(crate) const COMPLETIONS: &str = "COMPLETIONS"; pub(crate) const DUMP: &str = "DUMP"; pub(crate) const EDIT: &str = "EDIT"; pub(crate) const EVALUATE: &str = "EVALUATE"; pub(crate) const FORMAT: &str = "FORMAT"; pub(crate) const GROUPS: &str = "GROUPS"; pub(crate) const INIT: &str = "INIT"; pub(crate) const LIST: &str = "LIST"; pub(crate) const MAN: &str = "MAN"; pub(crate) const REQUEST: &str = "REQUEST"; pub(crate) const SHOW: &str = "SHOW"; pub(crate) const SUMMARY: &str = "SUMMARY"; pub(crate) const VARIABLES: &str = "VARIABLES"; pub(crate) const ALL: &[&str] = &[ CHANGELOG, CHOOSE, COMMAND, COMPLETIONS, DUMP, EDIT, EVALUATE, FORMAT, INIT, LIST, MAN, REQUEST, SHOW, SUMMARY, VARIABLES, ]; pub(crate) const ARGLESS: &[&str] = &[CHANGELOG, DUMP, EDIT, FORMAT, INIT, MAN, SUMMARY, VARIABLES]; pub(crate) const HEADING: &str = "Commands"; } mod arg { pub(crate) const ALIAS_STYLE: &str = "ALIAS_STYLE"; pub(crate) const ALLOW_MISSING: &str = "ALLOW-MISSING"; pub(crate) const ARGUMENTS: &str = "ARGUMENTS"; pub(crate) const CHECK: &str = "CHECK"; pub(crate) const CHOOSER: &str = "CHOOSER"; pub(crate) const CLEAR_SHELL_ARGS: &str = "CLEAR-SHELL-ARGS"; pub(crate) const COLOR: &str = "COLOR"; pub(crate) const COMMAND_COLOR: &str = "COMMAND-COLOR"; pub(crate) const DOTENV_FILENAME: &str = "DOTENV-FILENAME"; pub(crate) const DOTENV_PATH: &str = "DOTENV-PATH"; pub(crate) const DRY_RUN: &str = "DRY-RUN"; pub(crate) const DUMP_FORMAT: &str = "DUMP-FORMAT"; pub(crate) const EXPLAIN: &str = "EXPLAIN"; pub(crate) const GLOBAL_JUSTFILE: &str = "GLOBAL-JUSTFILE"; pub(crate) const HIGHLIGHT: &str = "HIGHLIGHT"; pub(crate) const JUSTFILE: &str = "JUSTFILE"; pub(crate) const LIST_HEADING: &str = "LIST-HEADING"; pub(crate) const LIST_PREFIX: &str = "LIST-PREFIX"; pub(crate) const LIST_SUBMODULES: &str = "LIST-SUBMODULES"; pub(crate) const NO_ALIASES: &str = "NO-ALIASES"; pub(crate) const NO_DEPS: &str = "NO-DEPS"; pub(crate) const NO_DOTENV: &str = "NO-DOTENV"; pub(crate) const NO_HIGHLIGHT: &str = "NO-HIGHLIGHT"; pub(crate) const ONE: &str = "ONE"; pub(crate) const QUIET: &str = "QUIET"; pub(crate) const SET: &str = "SET"; pub(crate) const SHELL: &str = "SHELL"; pub(crate) const SHELL_ARG: &str = "SHELL-ARG"; pub(crate) const SHELL_COMMAND: &str = "SHELL-COMMAND"; pub(crate) const TIMESTAMP: &str = "TIMESTAMP"; pub(crate) const TIMESTAMP_FORMAT: &str = "TIMESTAMP-FORMAT"; pub(crate) const UNSORTED: &str = "UNSORTED"; pub(crate) const UNSTABLE: &str = "UNSTABLE"; pub(crate) const VERBOSE: &str = "VERBOSE"; pub(crate) const WORKING_DIRECTORY: &str = "WORKING-DIRECTORY"; pub(crate) const YES: &str = "YES"; } impl Config { pub(crate) fn app() -> Command { Command::new(env!("CARGO_PKG_NAME")) .bin_name(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(concat!( env!("CARGO_PKG_DESCRIPTION"), " - ", env!("CARGO_PKG_HOMEPAGE") )) .trailing_var_arg(true) .styles( Styles::styled() .error(AnsiColor::Red.on_default() | Effects::BOLD) .header(AnsiColor::Yellow.on_default() | Effects::BOLD) .invalid(AnsiColor::Red.on_default()) .literal(AnsiColor::Green.on_default()) .placeholder(AnsiColor::Cyan.on_default()) .usage(AnsiColor::Yellow.on_default() | Effects::BOLD) .valid(AnsiColor::Green.on_default()), ) .arg( Arg::new(arg::ALIAS_STYLE) .long("alias-style") .env("JUST_ALIAS_STYLE") .action(ArgAction::Set) .value_parser(clap::value_parser!(AliasStyle)) .default_value("right") .help("Set list command alias display style") .conflicts_with(arg::NO_ALIASES), ) .arg( Arg::new(arg::CHECK) .long("check") .action(ArgAction::SetTrue) .requires(cmd::FORMAT) .help( "Run `--fmt` in 'check' mode. Exits with 0 if justfile is formatted correctly. \ Exits with 1 and prints a diff if formatting is required.", ), ) .arg( Arg::new(arg::CHOOSER) .long("chooser") .env("JUST_CHOOSER") .action(ArgAction::Set) .help("Override binary invoked by `--choose`"), ) .arg( Arg::new(arg::CLEAR_SHELL_ARGS) .long("clear-shell-args") .action(ArgAction::SetTrue) .overrides_with(arg::SHELL_ARG) .help("Clear shell arguments"), ) .arg( Arg::new(arg::COLOR) .long("color") .env("JUST_COLOR") .action(ArgAction::Set) .value_parser(clap::value_parser!(UseColor)) .default_value("auto") .help("Print colorful output"), ) .arg( Arg::new(arg::COMMAND_COLOR) .long("command-color") .env("JUST_COMMAND_COLOR") .action(ArgAction::Set) .value_parser(clap::value_parser!(CommandColor)) .help("Echo recipe lines in "), ) .arg( Arg::new(arg::DOTENV_FILENAME) .long("dotenv-filename") .action(ArgAction::Set) .help("Search for environment file named instead of `.env`") .conflicts_with(arg::DOTENV_PATH), ) .arg( Arg::new(arg::DOTENV_PATH) .short('E') .long("dotenv-path") .action(ArgAction::Set) .value_parser(value_parser!(PathBuf)) .help("Load as environment file instead of searching for one"), ) .arg( Arg::new(arg::DRY_RUN) .short('n') .long("dry-run") .env("JUST_DRY_RUN") .action(ArgAction::SetTrue) .help("Print what just would do without doing it") .conflicts_with(arg::QUIET), ) .arg( Arg::new(arg::DUMP_FORMAT) .long("dump-format") .env("JUST_DUMP_FORMAT") .action(ArgAction::Set) .value_parser(clap::value_parser!(DumpFormat)) .default_value("just") .value_name("FORMAT") .help("Dump justfile as "), ) .arg( Arg::new(arg::EXPLAIN) .action(ArgAction::SetTrue) .long("explain") .env("JUST_EXPLAIN") .help("Print recipe doc comment before running it"), ) .arg( Arg::new(arg::GLOBAL_JUSTFILE) .action(ArgAction::SetTrue) .long("global-justfile") .short('g') .conflicts_with(arg::JUSTFILE) .conflicts_with(arg::WORKING_DIRECTORY) .help("Use global justfile"), ) .arg( Arg::new(arg::HIGHLIGHT) .long("highlight") .env("JUST_HIGHLIGHT") .action(ArgAction::SetTrue) .help("Highlight echoed recipe lines in bold") .overrides_with(arg::NO_HIGHLIGHT), ) .arg( Arg::new(arg::JUSTFILE) .short('f') .long("justfile") .env("JUST_JUSTFILE") .action(ArgAction::Set) .value_parser(value_parser!(PathBuf)) .help("Use as justfile"), ) .arg( Arg::new(arg::LIST_HEADING) .long("list-heading") .env("JUST_LIST_HEADING") .help("Print before list") .value_name("TEXT") .default_value("Available recipes:\n") .action(ArgAction::Set), ) .arg( Arg::new(arg::LIST_PREFIX) .long("list-prefix") .env("JUST_LIST_PREFIX") .help("Print before each list item") .value_name("TEXT") .default_value(" ") .action(ArgAction::Set), ) .arg( Arg::new(arg::LIST_SUBMODULES) .long("list-submodules") .env("JUST_LIST_SUBMODULES") .help("List recipes in submodules") .action(ArgAction::SetTrue) .requires(cmd::LIST), ) .arg( Arg::new(arg::NO_ALIASES) .long("no-aliases") .env("JUST_NO_ALIASES") .action(ArgAction::SetTrue) .help("Don't show aliases in list"), ) .arg( Arg::new(arg::NO_DEPS) .long("no-deps") .env("JUST_NO_DEPS") .alias("no-dependencies") .action(ArgAction::SetTrue) .help("Don't run recipe dependencies"), ) .arg( Arg::new(arg::NO_DOTENV) .long("no-dotenv") .env("JUST_NO_DOTENV") .action(ArgAction::SetTrue) .help("Don't load `.env` file"), ) .arg( Arg::new(arg::NO_HIGHLIGHT) .long("no-highlight") .env("JUST_NO_HIGHLIGHT") .action(ArgAction::SetTrue) .help("Don't highlight echoed recipe lines in bold") .overrides_with(arg::HIGHLIGHT), ) .arg( Arg::new(arg::ONE) .long("one") .env("JUST_ONE") .action(ArgAction::SetTrue) .help("Forbid multiple recipes from being invoked on the command line"), ) .arg( Arg::new(arg::QUIET) .short('q') .long("quiet") .env("JUST_QUIET") .action(ArgAction::SetTrue) .help("Suppress all output") .conflicts_with(arg::DRY_RUN), ) .arg( Arg::new(arg::ALLOW_MISSING) .long("allow-missing") .env("JUST_ALLOW_MISSING") .action(ArgAction::SetTrue) .help("Ignore missing recipe and module errors"), ) .arg( Arg::new(arg::SET) .long("set") .action(ArgAction::Append) .number_of_values(2) .value_names(["VARIABLE", "VALUE"]) .help("Override with "), ) .arg( Arg::new(arg::SHELL) .long("shell") .action(ArgAction::Set) .help("Invoke to run recipes"), ) .arg( Arg::new(arg::SHELL_ARG) .long("shell-arg") .action(ArgAction::Append) .allow_hyphen_values(true) .overrides_with(arg::CLEAR_SHELL_ARGS) .help("Invoke shell with as an argument"), ) .arg( Arg::new(arg::SHELL_COMMAND) .long("shell-command") .requires(cmd::COMMAND) .action(ArgAction::SetTrue) .help("Invoke with the shell used to run recipe lines and backticks"), ) .arg( Arg::new(arg::TIMESTAMP) .action(ArgAction::SetTrue) .long("timestamp") .env("JUST_TIMESTAMP") .help("Print recipe command timestamps"), ) .arg( Arg::new(arg::TIMESTAMP_FORMAT) .action(ArgAction::Set) .long("timestamp-format") .env("JUST_TIMESTAMP_FORMAT") .default_value("%H:%M:%S") .help("Timestamp format string"), ) .arg( Arg::new(arg::UNSORTED) .long("unsorted") .env("JUST_UNSORTED") .short('u') .action(ArgAction::SetTrue) .help("Return list and summary entries in source order"), ) .arg( Arg::new(arg::UNSTABLE) .long("unstable") .env("JUST_UNSTABLE") .action(ArgAction::SetTrue) .value_parser(FalseyValueParser::new()) .help("Enable unstable features"), ) .arg( Arg::new(arg::VERBOSE) .short('v') .long("verbose") .env("JUST_VERBOSE") .action(ArgAction::Count) .help("Use verbose output"), ) .arg( Arg::new(arg::WORKING_DIRECTORY) .short('d') .long("working-directory") .env("JUST_WORKING_DIRECTORY") .action(ArgAction::Set) .value_parser(value_parser!(PathBuf)) .help("Use as working directory. --justfile must also be set") .requires(arg::JUSTFILE), ) .arg( Arg::new(arg::YES) .long("yes") .env("JUST_YES") .action(ArgAction::SetTrue) .help("Automatically confirm all recipes."), ) .arg( Arg::new(cmd::CHANGELOG) .long("changelog") .action(ArgAction::SetTrue) .help("Print changelog") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::CHOOSE) .long("choose") .action(ArgAction::SetTrue) .help( "Select one or more recipes to run using a binary chooser. If `--chooser` is not \ passed the chooser defaults to the value of $JUST_CHOOSER, falling back to `fzf`", ) .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::COMMAND) .long("command") .short('c') .num_args(1..) .allow_hyphen_values(true) .action(ArgAction::Append) .value_parser(value_parser!(std::ffi::OsString)) .help( "Run an arbitrary command with the working directory, `.env`, overrides, and exports \ set", ) .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::COMPLETIONS) .long("completions") .action(ArgAction::Set) .value_name("SHELL") .value_parser(value_parser!(completions::Shell)) .ignore_case(true) .help("Print shell completion script for ") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::DUMP) .long("dump") .action(ArgAction::SetTrue) .help("Print justfile") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::EDIT) .short('e') .long("edit") .action(ArgAction::SetTrue) .help("Edit justfile with editor given by $VISUAL or $EDITOR, falling back to `vim`") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::EVALUATE) .long("evaluate") .alias("eval") .action(ArgAction::SetTrue) .help( "Evaluate and print all variables. If a variable name is given as an argument, only \ print that variable's value.", ) .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::FORMAT) .long("fmt") .alias("format") .action(ArgAction::SetTrue) .help("Format and overwrite justfile") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::GROUPS) .long("groups") .action(ArgAction::SetTrue) .help("List recipe groups") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::INIT) .long("init") .alias("initialize") .action(ArgAction::SetTrue) .help("Initialize new justfile in project root") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::LIST) .short('l') .long("list") .num_args(0..) .value_name("MODULE") .action(ArgAction::Set) .conflicts_with(arg::ARGUMENTS) .help("List available recipes in or root if omitted") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::MAN) .long("man") .action(ArgAction::SetTrue) .help("Print man page") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::REQUEST) .long("request") .action(ArgAction::Set) .hide(true) .help( "Execute . For internal testing purposes only. May be changed or removed at \ any time.", ) .help_heading(cmd::REQUEST), ) .arg( Arg::new(cmd::SHOW) .short('s') .long("show") .num_args(1..) .action(ArgAction::Set) .value_name("PATH") .conflicts_with(arg::ARGUMENTS) .help("Show recipe at ") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::SUMMARY) .long("summary") .action(ArgAction::SetTrue) .help("List names of available recipes") .help_heading(cmd::HEADING), ) .arg( Arg::new(cmd::VARIABLES) .long("variables") .action(ArgAction::SetTrue) .help("List names of variables") .help_heading(cmd::HEADING), ) .group(ArgGroup::new("SUBCOMMAND").args(cmd::ALL)) .arg( Arg::new(arg::ARGUMENTS) .num_args(1..) .action(ArgAction::Append) .help("Overrides and recipe(s) to run, defaulting to the first recipe in the justfile"), ) } fn parse_module_path(values: ValuesRef) -> ConfigResult { let path = values.clone().map(|s| (*s).as_str()).collect::>(); let path = if path.len() == 1 && path[0].contains(' ') { path[0].split_whitespace().collect::>() } else { path }; path .as_slice() .try_into() .map_err(|()| ConfigError::ModulePath { path: values.cloned().collect(), }) } fn search_config(matches: &ArgMatches, positional: &Positional) -> ConfigResult { if matches.get_flag(arg::GLOBAL_JUSTFILE) { return Ok(SearchConfig::GlobalJustfile); } let justfile = matches.get_one::(arg::JUSTFILE).map(Into::into); let working_directory = matches .get_one::(arg::WORKING_DIRECTORY) .map(Into::into); if let Some(search_directory) = positional.search_directory.as_ref().map(PathBuf::from) { if justfile.is_some() || working_directory.is_some() { return Err(ConfigError::SearchDirConflict); } Ok(SearchConfig::FromSearchDirectory { search_directory }) } else { match (justfile, working_directory) { (None, None) => Ok(SearchConfig::FromInvocationDirectory), (Some(justfile), None) => Ok(SearchConfig::WithJustfile { justfile }), (Some(justfile), Some(working_directory)) => { Ok(SearchConfig::WithJustfileAndWorkingDirectory { justfile, working_directory, }) } (None, Some(_)) => Err(ConfigError::internal( "--working-directory set without --justfile", )), } } } pub(crate) fn from_matches(matches: &ArgMatches) -> ConfigResult { let mut overrides = BTreeMap::new(); if let Some(mut values) = matches.get_many::(arg::SET) { while let (Some(k), Some(v)) = (values.next(), values.next()) { overrides.insert(k.into(), v.into()); } } let positional = Positional::from_values( matches .get_many::(arg::ARGUMENTS) .map(|s| s.map(String::as_str)), ); for (name, value) in &positional.overrides { overrides.insert(name.clone(), value.clone()); } let search_config = Self::search_config(matches, &positional)?; for subcommand in cmd::ARGLESS { if matches.get_flag(subcommand) { match (!overrides.is_empty(), !positional.arguments.is_empty()) { (false, false) => {} (true, false) => { return Err(ConfigError::SubcommandOverrides { subcommand, overrides, }); } (false, true) => { return Err(ConfigError::SubcommandArguments { arguments: positional.arguments, subcommand, }); } (true, true) => { return Err(ConfigError::SubcommandOverridesAndArguments { arguments: positional.arguments, subcommand, overrides, }); } } } } let subcommand = if matches.get_flag(cmd::CHANGELOG) { Subcommand::Changelog } else if matches.get_flag(cmd::CHOOSE) { Subcommand::Choose { chooser: matches.get_one::(arg::CHOOSER).map(Into::into), overrides, } } else if let Some(values) = matches.get_many::(cmd::COMMAND) { let mut arguments = values.map(Into::into).collect::>(); Subcommand::Command { binary: arguments.remove(0), arguments, overrides, } } else if let Some(&shell) = matches.get_one::(cmd::COMPLETIONS) { Subcommand::Completions { shell } } else if matches.get_flag(cmd::DUMP) { Subcommand::Dump } else if matches.get_flag(cmd::EDIT) { Subcommand::Edit } else if matches.get_flag(cmd::EVALUATE) { if positional.arguments.len() > 1 { return Err(ConfigError::SubcommandArguments { subcommand: cmd::EVALUATE, arguments: positional .arguments .into_iter() .skip(1) .collect::>(), }); } Subcommand::Evaluate { variable: positional.arguments.into_iter().next(), overrides, } } else if matches.get_flag(cmd::FORMAT) { Subcommand::Format } else if matches.get_flag(cmd::GROUPS) { Subcommand::Groups } else if matches.get_flag(cmd::INIT) { Subcommand::Init } else if let Some(path) = matches.get_many::(cmd::LIST) { Subcommand::List { path: Self::parse_module_path(path)?, } } else if matches.get_flag(cmd::MAN) { Subcommand::Man } else if let Some(request) = matches.get_one::(cmd::REQUEST) { Subcommand::Request { request: serde_json::from_str(request) .map_err(|source| ConfigError::RequestParse { source })?, } } else if let Some(path) = matches.get_many::(cmd::SHOW) { Subcommand::Show { path: Self::parse_module_path(path)?, } } else if matches.get_flag(cmd::SUMMARY) { Subcommand::Summary } else if matches.get_flag(cmd::VARIABLES) { Subcommand::Variables } else { Subcommand::Run { arguments: positional.arguments, overrides, } }; let unstable = matches.get_flag(arg::UNSTABLE) || subcommand == Subcommand::Summary; let explain = matches.get_flag(arg::EXPLAIN); Ok(Self { alias_style: matches .get_one::(arg::ALIAS_STYLE) .unwrap() .clone(), allow_missing: matches.get_flag(arg::ALLOW_MISSING), check: matches.get_flag(arg::CHECK), color: (*matches.get_one::(arg::COLOR).unwrap()).into(), command_color: matches .get_one::(arg::COMMAND_COLOR) .copied() .map(CommandColor::into), dotenv_filename: matches .get_one::(arg::DOTENV_FILENAME) .map(Into::into), dotenv_path: matches.get_one::(arg::DOTENV_PATH).map(Into::into), dry_run: matches.get_flag(arg::DRY_RUN), dump_format: matches .get_one::(arg::DUMP_FORMAT) .unwrap() .clone(), explain, highlight: !matches.get_flag(arg::NO_HIGHLIGHT), invocation_directory: env::current_dir().context(config_error::CurrentDirContext)?, list_heading: matches.get_one::(arg::LIST_HEADING).unwrap().into(), list_prefix: matches.get_one::(arg::LIST_PREFIX).unwrap().into(), list_submodules: matches.get_flag(arg::LIST_SUBMODULES), load_dotenv: !matches.get_flag(arg::NO_DOTENV), no_aliases: matches.get_flag(arg::NO_ALIASES), no_dependencies: matches.get_flag(arg::NO_DEPS), one: matches.get_flag(arg::ONE), search_config, shell: matches.get_one::(arg::SHELL).map(Into::into), shell_args: if matches.get_flag(arg::CLEAR_SHELL_ARGS) { Some(Vec::new()) } else { matches .get_many::(arg::SHELL_ARG) .map(|s| s.map(Into::into).collect()) }, shell_command: matches.get_flag(arg::SHELL_COMMAND), subcommand, timestamp: matches.get_flag(arg::TIMESTAMP), timestamp_format: matches .get_one::(arg::TIMESTAMP_FORMAT) .unwrap() .into(), unsorted: matches.get_flag(arg::UNSORTED), unstable, verbosity: if matches.get_flag(arg::QUIET) { Verbosity::Quiet } else { Verbosity::from_flag_occurrences(matches.get_count(arg::VERBOSE)) }, yes: matches.get_flag(arg::YES), }) } pub(crate) fn require_unstable( &self, justfile: &Justfile, unstable_feature: UnstableFeature, ) -> RunResult<'static> { if self.unstable || justfile.settings.unstable { Ok(()) } else { Err(Error::UnstableFeature { unstable_feature }) } } } #[cfg(test)] mod tests { use { super::*, clap::error::{ContextKind, ContextValue}, pretty_assertions::assert_eq, }; macro_rules! test { { name: $name:ident, args: [$($arg:expr),*], $(color: $color:expr,)? $(dry_run: $dry_run:expr,)? $(dump_format: $dump_format:expr,)? $(highlight: $highlight:expr,)? $(no_dependencies: $no_dependencies:expr,)? $(search_config: $search_config:expr,)? $(shell: $shell:expr,)? $(shell_args: $shell_args:expr,)? $(subcommand: $subcommand:expr,)? $(unsorted: $unsorted:expr,)? $(unstable: $unstable:expr,)? $(verbosity: $verbosity:expr,)? } => { #[test] fn $name() { let arguments = &[ "just", $($arg,)* ]; let want = Config { $(color: $color,)? $(dry_run: $dry_run,)? $(dump_format: $dump_format,)? $(highlight: $highlight,)? $(no_dependencies: $no_dependencies,)? $(search_config: $search_config,)? $(shell: $shell,)? $(shell_args: $shell_args,)? $(subcommand: $subcommand,)? $(unsorted: $unsorted,)? $(unstable: $unstable,)? $(verbosity: $verbosity,)? ..testing::config(&[]) }; test(arguments, want); } } } #[track_caller] fn test(arguments: &[&str], want: Config) { let app = Config::app(); let matches = app .try_get_matches_from(arguments) .expect("argument parsing failed"); let have = Config::from_matches(&matches).expect("config parsing failed"); assert_eq!(have, want); } macro_rules! error { { name: $name:ident, args: [$($arg:expr),*], } => { #[test] fn $name() { let arguments = &[ "just", $($arg,)* ]; let app = Config::app(); app.try_get_matches_from(arguments).expect_err("Expected clap error"); } }; { name: $name:ident, args: [$($arg:expr),*], error: $error:pat, $(check: $check:block,)? } => { #[test] fn $name() { let arguments = &[ "just", $($arg,)* ]; let app = Config::app(); let matches = app.try_get_matches_from(arguments).expect("Matching fails"); match Config::from_matches(&matches).expect_err("config parsing succeeded") { $error => { $($check)? } other => panic!("Unexpected config error: {other}"), } } } } macro_rules! error_matches { ( name: $name:ident, args: [$($arg:expr),*], error: $error:pat, $(check: $check:block,)? ) => { #[test] fn $name() { let arguments = &[ "just", $($arg,)* ]; let app = Config::app(); match app.try_get_matches_from(arguments) { Err($error) => { $($check)? } other => panic!("Unexpected result from get matches: {other:?}") } } }; } macro_rules! map { {} => { BTreeMap::new() }; { $($key:literal : $value:literal),* $(,)? } => { { let mut map: BTreeMap = BTreeMap::new(); $( map.insert($key.to_owned(), $value.to_owned()); )* map } } } test! { name: default_config, args: [], } test! { name: color_default, args: [], color: Color::auto(), } test! { name: color_never, args: ["--color", "never"], color: Color::never(), } test! { name: color_always, args: ["--color", "always"], color: Color::always(), } test! { name: color_auto, args: ["--color", "auto"], color: Color::auto(), } error! { name: color_bad_value, args: ["--color", "foo"], } test! { name: dry_run_default, args: [], dry_run: false, } test! { name: dry_run_long, args: ["--dry-run"], dry_run: true, } test! { name: dry_run_short, args: ["-n"], dry_run: true, } error! { name: dry_run_quiet, args: ["--dry-run", "--quiet"], } test! { name: highlight_default, args: [], highlight: true, } test! { name: highlight_yes, args: ["--highlight"], highlight: true, } test! { name: highlight_no, args: ["--no-highlight"], highlight: false, } test! { name: highlight_no_yes, args: ["--no-highlight", "--highlight"], highlight: true, } test! { name: highlight_no_yes_no, args: ["--no-highlight", "--highlight", "--no-highlight"], highlight: false, } test! { name: highlight_yes_no, args: ["--highlight", "--no-highlight"], highlight: false, } test! { name: no_deps, args: ["--no-deps"], no_dependencies: true, } test! { name: no_dependencies, args: ["--no-dependencies"], no_dependencies: true, } test! { name: unsorted_default, args: [], unsorted: false, } test! { name: unsorted_long, args: ["--unsorted"], unsorted: true, } test! { name: unsorted_short, args: ["-u"], unsorted: true, } test! { name: quiet_default, args: [], verbosity: Verbosity::Taciturn, } test! { name: quiet_long, args: ["--quiet"], verbosity: Verbosity::Quiet, } test! { name: quiet_short, args: ["-q"], verbosity: Verbosity::Quiet, } error! { name: dotenv_both_filename_and_path, args: ["--dotenv-filename", "foo", "--dotenv-path", "bar"], } test! { name: set_default, args: [], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!(), }, } test! { name: set_one, args: ["--set", "foo", "bar"], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "bar"}, }, } test! { name: set_empty, args: ["--set", "foo", ""], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": ""}, }, } test! { name: set_two, args: ["--set", "foo", "bar", "--set", "bar", "baz"], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "bar", "bar": "baz"}, }, } test! { name: set_override, args: ["--set", "foo", "bar", "--set", "foo", "baz"], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "baz"}, }, } error! { name: set_bad, args: ["--set", "foo"], } test! { name: shell_default, args: [], shell: None, shell_args: None, } test! { name: shell_set, args: ["--shell", "tclsh"], shell: Some("tclsh".to_owned()), } test! { name: shell_args_set, args: ["--shell-arg", "hello"], shell: None, shell_args: Some(vec!["hello".into()]), } test! { name: verbosity_default, args: [], verbosity: Verbosity::Taciturn, } test! { name: verbosity_long, args: ["--verbose"], verbosity: Verbosity::Loquacious, } test! { name: verbosity_loquacious, args: ["-v"], verbosity: Verbosity::Loquacious, } test! { name: verbosity_grandiloquent, args: ["-v", "-v"], verbosity: Verbosity::Grandiloquent, } test! { name: verbosity_great_grandiloquent, args: ["-v", "-v", "-v"], verbosity: Verbosity::Grandiloquent, } test! { name: subcommand_default, args: [], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{}, }, } error! { name: subcommand_conflict_changelog, args: ["--list", "--changelog"], } error! { name: subcommand_conflict_summary, args: ["--list", "--summary"], } error! { name: subcommand_conflict_dump, args: ["--list", "--dump"], } error! { name: subcommand_conflict_fmt, args: ["--list", "--fmt"], } error! { name: subcommand_conflict_init, args: ["--list", "--init"], } error! { name: subcommand_conflict_evaluate, args: ["--list", "--evaluate"], } error! { name: subcommand_conflict_show, args: ["--list", "--show"], } error! { name: subcommand_conflict_completions, args: ["--list", "--completions"], } error! { name: subcommand_conflict_variables, args: ["--list", "--variables"], } error! { name: subcommand_conflict_choose, args: ["--list", "--choose"], } test! { name: subcommand_completions, args: ["--completions", "bash"], subcommand: Subcommand::Completions{ shell: completions::Shell::Bash }, } test! { name: subcommand_completions_uppercase, args: ["--completions", "BASH"], subcommand: Subcommand::Completions{ shell: completions::Shell::Bash }, } error! { name: subcommand_completions_invalid, args: ["--completions", "monstersh"], } test! { name: subcommand_dump, args: ["--dump"], subcommand: Subcommand::Dump, } test! { name: dump_format, args: ["--dump-format", "json"], dump_format: DumpFormat::Json, } test! { name: subcommand_edit, args: ["--edit"], subcommand: Subcommand::Edit, } test! { name: subcommand_evaluate, args: ["--evaluate"], subcommand: Subcommand::Evaluate { overrides: map!{}, variable: None, }, } test! { name: subcommand_evaluate_overrides, args: ["--evaluate", "x=y"], subcommand: Subcommand::Evaluate { overrides: map!{"x": "y"}, variable: None, }, } test! { name: subcommand_evaluate_overrides_with_argument, args: ["--evaluate", "x=y", "foo"], subcommand: Subcommand::Evaluate { overrides: map!{"x": "y"}, variable: Some("foo".to_owned()), }, } test! { name: subcommand_list_long, args: ["--list"], subcommand: Subcommand::List{ path: ModulePath { path: Vec::new(), spaced: false } }, } test! { name: subcommand_list_short, args: ["-l"], subcommand: Subcommand::List{ path: ModulePath { path: Vec::new(), spaced: false } }, } test! { name: subcommand_list_arguments, args: ["--list", "bar"], subcommand: Subcommand::List{ path: ModulePath { path: vec!["bar".into()], spaced: false } }, } test! { name: subcommand_show_long, args: ["--show", "build"], subcommand: Subcommand::Show { path: ModulePath { path: vec!["build".into()], spaced: false } }, } test! { name: subcommand_show_short, args: ["-s", "build"], subcommand: Subcommand::Show { path: ModulePath { path: vec!["build".into()], spaced: false } }, } test! { name: subcommand_show_multiple_args, args: ["--show", "foo", "bar"], subcommand: Subcommand::Show { path: ModulePath { path: vec!["foo".into(), "bar".into()], spaced: true, }, }, } test! { name: subcommand_summary, args: ["--summary"], subcommand: Subcommand::Summary, unstable: true, } test! { name: arguments, args: ["foo", "bar"], subcommand: Subcommand::Run { arguments: vec![String::from("foo"), String::from("bar")], overrides: map!{}, }, } test! { name: arguments_leading_equals, args: ["=foo"], subcommand: Subcommand::Run { arguments: vec!["=foo".to_owned()], overrides: map!{}, }, } test! { name: overrides, args: ["foo=bar", "bar=baz"], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "bar", "bar": "baz"}, }, } test! { name: overrides_empty, args: ["foo=", "bar="], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "", "bar": ""}, }, } test! { name: overrides_override_sets, args: ["--set", "foo", "0", "--set", "bar", "1", "foo=bar", "bar=baz"], subcommand: Subcommand::Run { arguments: Vec::new(), overrides: map!{"foo": "bar", "bar": "baz"}, }, } test! { name: shell_args_default, args: [], } test! { name: shell_args_set_hyphen, args: ["--shell-arg", "--foo"], shell_args: Some(vec!["--foo".to_owned()]), } test! { name: shell_args_set_word, args: ["--shell-arg", "foo"], shell_args: Some(vec!["foo".to_owned()]), } test! { name: shell_args_set_multiple, args: ["--shell-arg", "foo", "--shell-arg", "bar"], shell_args: Some(vec!["foo".to_owned(), "bar".to_owned()]), } test! { name: shell_args_clear, args: ["--clear-shell-args"], shell_args: Some(Vec::new()), } test! { name: shell_args_clear_and_set, args: ["--clear-shell-args", "--shell-arg", "bar"], shell_args: Some(vec!["bar".to_owned()]), } test! { name: shell_args_set_and_clear, args: ["--shell-arg", "bar", "--clear-shell-args"], shell_args: Some(Vec::new()), } test! { name: shell_args_set_multiple_and_clear, args: ["--shell-arg", "bar", "--shell-arg", "baz", "--clear-shell-args"], shell_args: Some(Vec::new()), } test! { name: search_config_default, args: [], search_config: SearchConfig::FromInvocationDirectory, } test! { name: search_config_from_working_directory_and_justfile, args: ["--working-directory", "foo", "--justfile", "bar"], search_config: SearchConfig::WithJustfileAndWorkingDirectory { justfile: PathBuf::from("bar"), working_directory: PathBuf::from("foo"), }, } test! { name: search_config_justfile_long, args: ["--justfile", "foo"], search_config: SearchConfig::WithJustfile { justfile: PathBuf::from("foo"), }, } test! { name: search_config_justfile_short, args: ["-f", "foo"], search_config: SearchConfig::WithJustfile { justfile: PathBuf::from("foo"), }, } test! { name: search_directory_parent, args: ["../"], search_config: SearchConfig::FromSearchDirectory { search_directory: PathBuf::from(".."), }, } test! { name: search_directory_parent_with_recipe, args: ["../build"], search_config: SearchConfig::FromSearchDirectory { search_directory: PathBuf::from(".."), }, subcommand: Subcommand::Run { arguments: vec!["build".to_owned()], overrides: BTreeMap::new() }, } test! { name: search_directory_child, args: ["foo/"], search_config: SearchConfig::FromSearchDirectory { search_directory: PathBuf::from("foo"), }, } test! { name: search_directory_deep, args: ["foo/bar/"], search_config: SearchConfig::FromSearchDirectory { search_directory: PathBuf::from("foo/bar"), }, } test! { name: search_directory_child_with_recipe, args: ["foo/build"], search_config: SearchConfig::FromSearchDirectory { search_directory: PathBuf::from("foo"), }, subcommand: Subcommand::Run { arguments: vec!["build".to_owned()], overrides: BTreeMap::new() }, } error! { name: search_directory_conflict_justfile, args: ["--justfile", "bar", "foo/build"], error: ConfigError::SearchDirConflict, } error! { name: search_directory_conflict_working_directory, args: ["--justfile", "bar", "--working-directory", "baz", "foo/build"], error: ConfigError::SearchDirConflict, } error_matches! { name: completions_argument, args: ["--completions", "foo"], error: error, check: { assert_eq!(error.kind(), clap::error::ErrorKind::InvalidValue); assert_eq!(error.context().collect::>(), vec![ ( ContextKind::InvalidArg, &ContextValue::String("--completions ".into())), ( ContextKind::InvalidValue, &ContextValue::String("foo".into()), ), ( ContextKind::ValidValue, &ContextValue::Strings([ "bash".into(), "elvish".into(), "fish".into(), "nushell".into(), "powershell".into(), "zsh".into()].into() ), ), ]); }, } error! { name: changelog_arguments, args: ["--changelog", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::CHANGELOG); assert_eq!(arguments, &["bar"]); }, } error! { name: dump_arguments, args: ["--dump", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::DUMP); assert_eq!(arguments, &["bar"]); }, } error! { name: edit_arguments, args: ["--edit", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::EDIT); assert_eq!(arguments, &["bar"]); }, } error! { name: fmt_arguments, args: ["--fmt", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::FORMAT); assert_eq!(arguments, &["bar"]); }, } error! { name: fmt_alias, args: ["--format", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::FORMAT); assert_eq!(arguments, &["bar"]); }, } error! { name: init_arguments, args: ["--init", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::INIT); assert_eq!(arguments, &["bar"]); }, } error! { name: init_alias, args: ["--initialize", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::INIT); assert_eq!(arguments, &["bar"]); }, } error! { name: summary_arguments, args: ["--summary", "bar"], error: ConfigError::SubcommandArguments { subcommand, arguments }, check: { assert_eq!(subcommand, cmd::SUMMARY); assert_eq!(arguments, &["bar"]); }, } error! { name: subcommand_overrides_and_arguments, args: ["--summary", "bar=baz", "bar"], error: ConfigError::SubcommandOverridesAndArguments { subcommand, arguments, overrides }, check: { assert_eq!(subcommand, cmd::SUMMARY); assert_eq!(overrides, map!{"bar": "baz"}); assert_eq!(arguments, &["bar"]); }, } error! { name: summary_overrides, args: ["--summary", "bar=baz"], error: ConfigError::SubcommandOverrides { subcommand, overrides }, check: { assert_eq!(subcommand, cmd::SUMMARY); assert_eq!(overrides, map!{"bar": "baz"}); }, } } just-1.40.0/src/config_error.rs000064400000000000000000000035071046102023000145130ustar 00000000000000use super::*; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)), context(suffix(Context)))] pub(crate) enum ConfigError { #[snafu(display("Failed to get current directory: {}", source))] CurrentDir { source: io::Error }, #[snafu(display( "Internal config error, this may indicate a bug in just: {message} \ consider filing an issue: https://github.com/casey/just/issues/new", ))] Internal { message: String }, #[snafu(display("Invalid module path `{}`", path.join(" ")))] ModulePath { path: Vec }, #[snafu(display("Failed to parse request: {source}"))] RequestParse { source: serde_json::Error }, #[snafu(display( "Path-prefixed recipes may not be used with `--working-directory` or `--justfile`." ))] SearchDirConflict, #[snafu(display( "`--{}` used with unexpected {}: {}", subcommand.to_lowercase(), Count("argument", arguments.len()), List::and_ticked(arguments) ))] SubcommandArguments { subcommand: &'static str, arguments: Vec, }, #[snafu(display( "`--{}` used with unexpected overrides: {}", subcommand.to_lowercase(), List::and_ticked(overrides.iter().map(|(key, value)| format!("{key}={value}"))), ))] SubcommandOverrides { subcommand: &'static str, overrides: BTreeMap, }, #[snafu(display( "`--{}` used with unexpected overrides: {}; and arguments: {}", subcommand.to_lowercase(), List::and_ticked(overrides.iter().map(|(key, value)| format!("{key}={value}"))), List::and_ticked(arguments))) ] SubcommandOverridesAndArguments { subcommand: &'static str, overrides: BTreeMap, arguments: Vec, }, } impl ConfigError { pub(crate) fn internal(message: impl Into) -> Self { Self::Internal { message: message.into(), } } } just-1.40.0/src/constants.rs000064400000000000000000000031721046102023000140470ustar 00000000000000use super::*; const CONSTANTS: [(&str, &str, &str); 27] = [ ("HEX", "0123456789abcdef", "1.27.0"), ("HEXLOWER", "0123456789abcdef", "1.27.0"), ("HEXUPPER", "0123456789ABCDEF", "1.27.0"), ("CLEAR", "\x1bc", "master"), ("NORMAL", "\x1b[0m", "master"), ("BOLD", "\x1b[1m", "master"), ("ITALIC", "\x1b[3m", "master"), ("UNDERLINE", "\x1b[4m", "master"), ("INVERT", "\x1b[7m", "master"), ("HIDE", "\x1b[8m", "master"), ("STRIKETHROUGH", "\x1b[9m", "master"), ("BLACK", "\x1b[30m", "master"), ("RED", "\x1b[31m", "master"), ("GREEN", "\x1b[32m", "master"), ("YELLOW", "\x1b[33m", "master"), ("BLUE", "\x1b[34m", "master"), ("MAGENTA", "\x1b[35m", "master"), ("CYAN", "\x1b[36m", "master"), ("WHITE", "\x1b[37m", "master"), ("BG_BLACK", "\x1b[40m", "master"), ("BG_RED", "\x1b[41m", "master"), ("BG_GREEN", "\x1b[42m", "master"), ("BG_YELLOW", "\x1b[43m", "master"), ("BG_BLUE", "\x1b[44m", "master"), ("BG_MAGENTA", "\x1b[45m", "master"), ("BG_CYAN", "\x1b[46m", "master"), ("BG_WHITE", "\x1b[47m", "master"), ]; pub(crate) fn constants() -> &'static HashMap<&'static str, &'static str> { static MAP: OnceLock> = OnceLock::new(); MAP.get_or_init(|| { CONSTANTS .into_iter() .map(|(name, value, _version)| (name, value)) .collect() }) } #[cfg(test)] mod tests { use super::*; #[test] fn readme_table() { println!("| Name | Value |"); println!("|------|-------------|"); for (name, value, version) in CONSTANTS { println!( "| `{name}`{version} | `\"{}\"` |", value.replace('\x1b', "\\e") ); } } } just-1.40.0/src/count.rs000064400000000000000000000007571046102023000131710ustar 00000000000000use super::*; pub struct Count(pub T, pub usize); impl Display for Count { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.1 == 1 { write!(f, "{}", self.0) } else { write!(f, "{}s", self.0) } } } #[cfg(test)] mod tests { use super::*; #[test] fn count() { assert_eq!(Count("dog", 0).to_string(), "dogs"); assert_eq!(Count("dog", 1).to_string(), "dog"); assert_eq!(Count("dog", 2).to_string(), "dogs"); } } just-1.40.0/src/delimiter.rs000064400000000000000000000006361046102023000140130ustar 00000000000000#[derive(PartialEq, Eq, Debug, Copy, Clone)] pub(crate) enum Delimiter { Brace, Bracket, Paren, } impl Delimiter { pub(crate) fn open(self) -> char { match self { Self::Brace => '{', Self::Bracket => '[', Self::Paren => '(', } } pub(crate) fn close(self) -> char { match self { Self::Brace => '}', Self::Bracket => ']', Self::Paren => ')', } } } just-1.40.0/src/dependency.rs000064400000000000000000000010671046102023000141520ustar 00000000000000use super::*; #[derive(PartialEq, Debug, Serialize)] pub(crate) struct Dependency<'src> { pub(crate) arguments: Vec>, #[serde(serialize_with = "keyed::serialize")] pub(crate) recipe: Rc>, } impl Display for Dependency<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.arguments.is_empty() { write!(f, "{}", self.recipe.name()) } else { write!(f, "({}", self.recipe.name())?; for argument in &self.arguments { write!(f, " {argument}")?; } write!(f, ")") } } } just-1.40.0/src/dump_format.rs000064400000000000000000000001541046102023000143450ustar 00000000000000use super::*; #[derive(Debug, PartialEq, Clone, ValueEnum)] pub(crate) enum DumpFormat { Json, Just, } just-1.40.0/src/enclosure.rs000064400000000000000000000010211046102023000140210ustar 00000000000000use super::*; pub struct Enclosure { enclosure: &'static str, value: T, } impl Enclosure { pub fn tick(value: T) -> Enclosure { Self { enclosure: "`", value, } } } impl Display for Enclosure { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}{}{}", self.enclosure, self.value, self.enclosure) } } #[cfg(test)] mod tests { use super::*; #[test] fn tick() { assert_eq!(Enclosure::tick("foo").to_string(), "`foo`"); } } just-1.40.0/src/error.rs000064400000000000000000000406201046102023000131630ustar 00000000000000use super::*; #[derive(Debug)] pub(crate) enum Error<'src> { AmbiguousModuleFile { module: Name<'src>, found: Vec, }, ArgumentCountMismatch { recipe: &'src str, parameters: Vec>, found: usize, min: usize, max: usize, }, Assert { message: String, }, Backtick { token: Token<'src>, output_error: OutputError, }, ChooserInvoke { shell_binary: String, shell_arguments: String, chooser: OsString, io_error: io::Error, }, ChooserRead { chooser: OsString, io_error: io::Error, }, ChooserStatus { chooser: OsString, status: ExitStatus, }, ChooserWrite { chooser: OsString, io_error: io::Error, }, CircularImport { current: PathBuf, import: PathBuf, }, Code { recipe: &'src str, line_number: Option, code: i32, print_message: bool, }, CommandInvoke { binary: OsString, arguments: Vec, io_error: io::Error, }, CommandStatus { binary: OsString, arguments: Vec, status: ExitStatus, }, Compile { compile_error: CompileError<'src>, }, Config { config_error: ConfigError, }, Cygpath { recipe: &'src str, output_error: OutputError, }, DefaultRecipeRequiresArguments { recipe: &'src str, min_arguments: usize, }, Dotenv { dotenv_error: dotenvy::Error, }, DotenvRequired, DumpJson { source: serde_json::Error, }, EditorInvoke { editor: OsString, io_error: io::Error, }, EditorStatus { editor: OsString, status: ExitStatus, }, EvalUnknownVariable { variable: String, suggestion: Option>, }, ExcessInvocations { invocations: usize, }, ExpectedSubmoduleButFoundRecipe { path: String, }, FormatCheckFoundDiff, FunctionCall { function: Name<'src>, message: String, }, GetConfirmation { io_error: io::Error, }, Homedir, InitExists { justfile: PathBuf, }, Internal { message: String, }, Io { recipe: &'src str, io_error: io::Error, }, Load { path: PathBuf, io_error: io::Error, }, MissingImportFile { path: Token<'src>, }, MissingModuleFile { module: Name<'src>, }, NoChoosableRecipes, NoDefaultRecipe, NoRecipes, NotConfirmed { recipe: &'src str, }, RegexCompile { source: regex::Error, }, RuntimeDirIo { io_error: io::Error, path: PathBuf, }, Script { command: String, io_error: io::Error, recipe: &'src str, }, Search { search_error: SearchError, }, Shebang { argument: Option, command: String, io_error: io::Error, recipe: &'src str, }, Signal { recipe: &'src str, line_number: Option, signal: i32, }, StdoutIo { io_error: io::Error, }, TempdirIo { recipe: &'src str, io_error: io::Error, }, TempfileIo { io_error: io::Error, }, Unknown { recipe: &'src str, line_number: Option, }, UnknownOverrides { overrides: Vec, }, UnknownRecipe { recipe: String, suggestion: Option>, }, UnknownSubmodule { path: String, }, UnstableFeature { unstable_feature: UnstableFeature, }, WriteJustfile { justfile: PathBuf, io_error: io::Error, }, } impl<'src> Error<'src> { pub(crate) fn code(&self) -> Option { match self { Self::Code { code, .. } | Self::Backtick { output_error: OutputError::Code(code), .. } => Some(*code), Self::ChooserStatus { status, .. } | Self::EditorStatus { status, .. } => status.code(), _ => None, } } fn context(&self) -> Option> { match self { Self::AmbiguousModuleFile { module, .. } | Self::MissingModuleFile { module, .. } => { Some(module.token) } Self::Backtick { token, .. } => Some(*token), Self::Compile { compile_error } => Some(compile_error.context()), Self::FunctionCall { function, .. } => Some(function.token), Self::MissingImportFile { path } => Some(*path), _ => None, } } pub(crate) fn internal(message: impl Into) -> Self { Self::Internal { message: message.into(), } } pub(crate) fn print_message(&self) -> bool { !matches!( self, Error::Code { print_message: false, .. } ) } } impl<'src> From> for Error<'src> { fn from(compile_error: CompileError<'src>) -> Self { Self::Compile { compile_error } } } impl From for Error<'_> { fn from(config_error: ConfigError) -> Self { Self::Config { config_error } } } impl<'src> From for Error<'src> { fn from(dotenv_error: dotenvy::Error) -> Error<'src> { Self::Dotenv { dotenv_error } } } impl From for Error<'_> { fn from(search_error: SearchError) -> Self { Self::Search { search_error } } } impl ColorDisplay for Error<'_> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { use Error::*; let error = color.error().paint("error"); let message = color.message().prefix(); write!(f, "{error}: {message}")?; match self { AmbiguousModuleFile { module, found } => write!(f, "Found multiple source files for module `{module}`: {}", List::and_ticked(found.iter().map(|path| path.display())), )?, ArgumentCountMismatch { recipe, found, min, max, .. } => { let count = Count("argument", *found); if min == max { let expected = min; let only = if expected < found { "only " } else { "" }; write!(f, "Recipe `{recipe}` got {found} {count} but {only}takes {expected}")?; } else if found < min { write!(f, "Recipe `{recipe}` got {found} {count} but takes at least {min}")?; } else if found > max { write!(f, "Recipe `{recipe}` got {found} {count} but takes at most {max}")?; } } Assert { message }=> { write!(f, "Assert failed: {message}")?; } Backtick { output_error, .. } => match output_error { OutputError::Code(code) => write!(f, "Backtick failed with exit code {code}")?, OutputError::Signal(signal) => write!(f, "Backtick was terminated by signal {signal}")?, OutputError::Unknown => write!(f, "Backtick failed for an unknown reason")?, OutputError::Io(io_error) => match io_error.kind() { io::ErrorKind::NotFound => write!(f, "Backtick could not be run because just could not find the shell:\n{io_error}"), io::ErrorKind::PermissionDenied => write!(f, "Backtick could not be run because just could not run the shell:\n{io_error}"), _ => write!(f, "Backtick could not be run because of an IO error while launching the shell:\n{io_error}"), }?, OutputError::Utf8(utf8_error) => write!(f, "Backtick succeeded but stdout was not utf8: {utf8_error}")?, } ChooserInvoke { shell_binary, shell_arguments, chooser, io_error} => { let chooser = chooser.to_string_lossy(); write!(f, "Chooser `{shell_binary} {shell_arguments} {chooser}` invocation failed: {io_error}")?; } ChooserRead { chooser, io_error } => { let chooser = chooser.to_string_lossy(); write!(f, "Failed to read output from chooser `{chooser}`: {io_error}")?; } ChooserStatus { chooser, status } => { let chooser = chooser.to_string_lossy(); write!(f, "Chooser `{chooser}` failed: {status}")?; } ChooserWrite { chooser, io_error } => { let chooser = chooser.to_string_lossy(); write!(f, "Failed to write to chooser `{chooser}`: {io_error}")?; } CircularImport { current, import } => { let import = import.display(); let current = current.display(); write!(f, "Import `{import}` in `{current}` is circular")?; } Code { recipe, line_number, code, .. } => { if let Some(n) = line_number { write!(f, "Recipe `{recipe}` failed on line {n} with exit code {code}")?; } else { write!(f, "Recipe `{recipe}` failed with exit code {code}")?; } } CommandInvoke { binary, arguments, io_error } => { let cmd = format_cmd(binary, arguments); write!(f, "Failed to invoke {cmd}: {io_error}")?; } CommandStatus { binary, arguments, status} => { let cmd = format_cmd(binary, arguments); write!(f, "Command {cmd} failed: {status}")?; } Compile { compile_error } => Display::fmt(compile_error, f)?, Config { config_error } => Display::fmt(config_error, f)?, Cygpath { recipe, output_error} => match output_error { OutputError::Code(code) => write!(f, "Cygpath failed with exit code {code} while translating recipe `{recipe}` shebang interpreter path")?, OutputError::Signal(signal) => write!(f, "Cygpath terminated by signal {signal} while translating recipe `{recipe}` shebang interpreter path")?, OutputError::Unknown => write!(f, "Cygpath experienced an unknown failure while translating recipe `{recipe}` shebang interpreter path")?, OutputError::Io(io_error) => { match io_error.kind() { io::ErrorKind::NotFound => write!(f, "Could not find `cygpath` executable to translate recipe `{recipe}` shebang interpreter path:\n{io_error}"), io::ErrorKind::PermissionDenied => write!(f, "Could not run `cygpath` executable to translate recipe `{recipe}` shebang interpreter path:\n{io_error}"), _ => write!(f, "Could not run `cygpath` executable:\n{io_error}"), }?; } OutputError::Utf8(utf8_error) => write!(f, "Cygpath successfully translated recipe `{recipe}` shebang interpreter path, but output was not utf8: {utf8_error}")?, } DefaultRecipeRequiresArguments { recipe, min_arguments} => { let count = Count("argument", *min_arguments); write!(f, "Recipe `{recipe}` cannot be used as default recipe since it requires at least {min_arguments} {count}.")?; } Dotenv { dotenv_error } => { write!(f, "Failed to load environment file: {dotenv_error}")?; } DotenvRequired => { write!(f, "Dotenv file not found")?; } DumpJson { source } => { write!(f, "Failed to dump JSON to stdout: {source}")?; } EditorInvoke { editor, io_error } => { let editor = editor.to_string_lossy(); write!(f, "Editor `{editor}` invocation failed: {io_error}")?; } EditorStatus { editor, status } => { let editor = editor.to_string_lossy(); write!(f, "Editor `{editor}` failed: {status}")?; } EvalUnknownVariable { variable, suggestion} => { write!(f, "Justfile does not contain variable `{variable}`.")?; if let Some(suggestion) = suggestion { write!(f, "\n{suggestion}")?; } } ExcessInvocations { invocations } => { write!(f, "Expected 1 command-line recipe invocation but found {invocations}.")?; }, ExpectedSubmoduleButFoundRecipe { path } => { write!(f, "Expected submodule at `{path}` but found recipe.")?; }, FormatCheckFoundDiff => { write!(f, "Formatted justfile differs from original.")?; } FunctionCall { function, message } => { let function = function.lexeme(); write!(f, "Call to function `{function}` failed: {message}")?; } GetConfirmation { io_error } => { write!(f, "Failed to read confirmation from stdin: {io_error}")?; } Homedir => { write!(f, "Failed to get homedir")?; } InitExists { justfile } => { write!(f, "Justfile `{}` already exists", justfile.display())?; } Internal { message } => { write!(f, "Internal runtime error, this may indicate a bug in just: {message} \ consider filing an issue: https://github.com/casey/just/issues/new")?; } Io { recipe, io_error } => { match io_error.kind() { io::ErrorKind::NotFound => write!(f, "Recipe `{recipe}` could not be run because just could not find the shell: {io_error}"), io::ErrorKind::PermissionDenied => write!(f, "Recipe `{recipe}` could not be run because just could not run the shell: {io_error}"), _ => write!(f, "Recipe `{recipe}` could not be run because of an IO error while launching the shell: {io_error}"), }?; } Load { io_error, path } => { write!(f, "Failed to read justfile at `{}`: {io_error}", path.display())?; } MissingImportFile { .. } => write!(f, "Could not find source file for import.")?, MissingModuleFile { module } => write!(f, "Could not find source file for module `{module}`.")?, NoChoosableRecipes => write!(f, "Justfile contains no choosable recipes.")?, NoDefaultRecipe => write!(f, "Justfile contains no default recipe.")?, NoRecipes => write!(f, "Justfile contains no recipes.")?, NotConfirmed { recipe } => { write!(f, "Recipe `{recipe}` was not confirmed")?; } RegexCompile { source } => write!(f, "{source}")?, RuntimeDirIo { io_error, path } => { write!(f, "I/O error in runtime dir `{}`: {io_error}", path.display())?; } Script { command, io_error, recipe } => { write!(f, "Recipe `{recipe}` with command `{command}` execution error: {io_error}")?; } Search { search_error } => Display::fmt(search_error, f)?, Shebang { recipe, command, argument, io_error} => { if let Some(argument) = argument { write!(f, "Recipe `{recipe}` with shebang `#!{command} {argument}` execution error: {io_error}")?; } else { write!(f, "Recipe `{recipe}` with shebang `#!{command}` execution error: {io_error}")?; } } Signal { recipe, line_number, signal } => { if let Some(n) = line_number { write!(f, "Recipe `{recipe}` was terminated on line {n} by signal {signal}")?; } else { write!(f, "Recipe `{recipe}` was terminated by signal {signal}")?; } } StdoutIo { io_error } => { write!(f, "I/O error writing to stdout: {io_error}?")?; } TempdirIo { recipe, io_error } => { write!(f, "Recipe `{recipe}` could not be run because of an IO error while trying to create a temporary \ directory or write a file to that directory: {io_error}")?; } TempfileIo { io_error } => { write!(f, "Tempfile I/O error: {io_error}")?; } Unknown { recipe, line_number} => { if let Some(n) = line_number { write!(f, "Recipe `{recipe}` failed on line {n} for an unknown reason")?; } else { write!(f, "Recipe `{recipe}` failed for an unknown reason")?; } } UnknownSubmodule { path } => { write!(f, "Justfile does not contain submodule `{path}`")?; } UnknownOverrides { overrides } => { let count = Count("Variable", overrides.len()); let overrides = List::and_ticked(overrides); write!(f, "{count} {overrides} overridden on the command line but not present in justfile")?; } UnknownRecipe { recipe, suggestion } => { write!(f, "Justfile does not contain recipe `{recipe}`")?; if let Some(suggestion) = suggestion { write!(f, "\n{suggestion}")?; } } UnstableFeature { unstable_feature } => { write!(f, "{unstable_feature} Invoke `just` with `--unstable`, set the `JUST_UNSTABLE` environment variable, or add `set unstable` to your `justfile` to enable unstable features.")?; } WriteJustfile { justfile, io_error } => { let justfile = justfile.display(); write!(f, "Failed to write justfile to `{justfile}`: {io_error}")?; } } write!(f, "{}", color.message().suffix())?; if let ArgumentCountMismatch { recipe, parameters, .. } = self { writeln!(f)?; write!(f, "{}:\n just {recipe}", color.message().paint("usage"))?; for param in parameters { write!(f, " {}", param.color_display(color))?; } } if let Some(token) = self.context() { writeln!(f)?; write!(f, "{}", token.color_display(color.error()))?; } Ok(()) } } fn format_cmd(binary: &OsString, arguments: &Vec) -> String { iter::once(binary) .chain(arguments) .map(|value| Enclosure::tick(value.to_string_lossy()).to_string()) .collect::>() .join(" ") } just-1.40.0/src/evaluator.rs000064400000000000000000000272671046102023000140500ustar 00000000000000use super::*; pub(crate) struct Evaluator<'src: 'run, 'run> { pub(crate) assignments: Option<&'run Table<'src, Assignment<'src>>>, pub(crate) context: ExecutionContext<'src, 'run>, pub(crate) is_dependency: bool, pub(crate) scope: Scope<'src, 'run>, } impl<'src, 'run> Evaluator<'src, 'run> { pub(crate) fn evaluate_assignments( config: &'run Config, dotenv: &'run BTreeMap, module: &'run Justfile<'src>, overrides: &BTreeMap, parent: &'run Scope<'src, 'run>, search: &'run Search, ) -> RunResult<'src, Scope<'src, 'run>> where 'src: 'run, { let context = ExecutionContext { config, dotenv, module, scope: parent, search, }; let mut scope = context.scope.child(); let mut unknown_overrides = Vec::new(); for (name, value) in overrides { if let Some(assignment) = module.assignments.get(name) { scope.bind(Binding { constant: false, export: assignment.export, file_depth: 0, name: assignment.name, private: assignment.private, value: value.clone(), }); } else { unknown_overrides.push(name.clone()); } } if !unknown_overrides.is_empty() { return Err(Error::UnknownOverrides { overrides: unknown_overrides, }); } let mut evaluator = Self { context, assignments: Some(&module.assignments), scope, is_dependency: false, }; for assignment in module.assignments.values() { evaluator.evaluate_assignment(assignment)?; } Ok(evaluator.scope) } fn evaluate_assignment(&mut self, assignment: &Assignment<'src>) -> RunResult<'src, &str> { let name = assignment.name.lexeme(); if !self.scope.bound(name) { let value = self.evaluate_expression(&assignment.value)?; self.scope.bind(Binding { constant: false, export: assignment.export, file_depth: 0, name: assignment.name, private: assignment.private, value, }); } Ok(self.scope.value(name).unwrap()) } pub(crate) fn evaluate_expression( &mut self, expression: &Expression<'src>, ) -> RunResult<'src, String> { match expression { Expression::And { lhs, rhs } => { let lhs = self.evaluate_expression(lhs)?; if lhs.is_empty() { return Ok(String::new()); } self.evaluate_expression(rhs) } Expression::Assert { condition, error } => { if self.evaluate_condition(condition)? { Ok(String::new()) } else { Err(Error::Assert { message: self.evaluate_expression(error)?, }) } } Expression::Backtick { contents, token } => { if self.context.config.dry_run { Ok(format!("`{contents}`")) } else { Ok(self.run_backtick(contents, token)?) } } Expression::Call { thunk } => { use Thunk::*; let result = match thunk { Nullary { function, .. } => function(function::Context::new(self, thunk.name())), Unary { function, arg, .. } => { let arg = self.evaluate_expression(arg)?; function(function::Context::new(self, thunk.name()), &arg) } UnaryOpt { function, args: (a, b), .. } => { let a = self.evaluate_expression(a)?; let b = match b.as_ref() { Some(b) => Some(self.evaluate_expression(b)?), None => None, }; function(function::Context::new(self, thunk.name()), &a, b.as_deref()) } UnaryPlus { function, args: (a, rest), .. } => { let a = self.evaluate_expression(a)?; let mut rest_evaluated = Vec::new(); for arg in rest { rest_evaluated.push(self.evaluate_expression(arg)?); } function( function::Context::new(self, thunk.name()), &a, &rest_evaluated, ) } Binary { function, args: [a, b], .. } => { let a = self.evaluate_expression(a)?; let b = self.evaluate_expression(b)?; function(function::Context::new(self, thunk.name()), &a, &b) } BinaryPlus { function, args: ([a, b], rest), .. } => { let a = self.evaluate_expression(a)?; let b = self.evaluate_expression(b)?; let mut rest_evaluated = Vec::new(); for arg in rest { rest_evaluated.push(self.evaluate_expression(arg)?); } function( function::Context::new(self, thunk.name()), &a, &b, &rest_evaluated, ) } Ternary { function, args: [a, b, c], .. } => { let a = self.evaluate_expression(a)?; let b = self.evaluate_expression(b)?; let c = self.evaluate_expression(c)?; function(function::Context::new(self, thunk.name()), &a, &b, &c) } }; result.map_err(|message| Error::FunctionCall { function: thunk.name(), message, }) } Expression::Concatenation { lhs, rhs } => { let lhs = self.evaluate_expression(lhs)?; let rhs = self.evaluate_expression(rhs)?; Ok(lhs + &rhs) } Expression::Conditional { condition, then, otherwise, } => { if self.evaluate_condition(condition)? { self.evaluate_expression(then) } else { self.evaluate_expression(otherwise) } } Expression::Group { contents } => self.evaluate_expression(contents), Expression::Join { lhs: None, rhs } => Ok("/".to_string() + &self.evaluate_expression(rhs)?), Expression::Join { lhs: Some(lhs), rhs, } => { let lhs = self.evaluate_expression(lhs)?; let rhs = self.evaluate_expression(rhs)?; Ok(lhs + "/" + &rhs) } Expression::Or { lhs, rhs } => { let lhs = self.evaluate_expression(lhs)?; if !lhs.is_empty() { return Ok(lhs); } self.evaluate_expression(rhs) } Expression::StringLiteral { string_literal } => Ok(string_literal.cooked.clone()), Expression::Variable { name, .. } => { let variable = name.lexeme(); if let Some(value) = self.scope.value(variable) { Ok(value.to_owned()) } else if let Some(assignment) = self .assignments .and_then(|assignments| assignments.get(variable)) { Ok(self.evaluate_assignment(assignment)?.to_owned()) } else { Err(Error::Internal { message: format!("attempted to evaluate undefined variable `{variable}`"), }) } } } } fn evaluate_condition(&mut self, condition: &Condition<'src>) -> RunResult<'src, bool> { let lhs_value = self.evaluate_expression(&condition.lhs)?; let rhs_value = self.evaluate_expression(&condition.rhs)?; let condition = match condition.operator { ConditionalOperator::Equality => lhs_value == rhs_value, ConditionalOperator::Inequality => lhs_value != rhs_value, ConditionalOperator::RegexMatch => Regex::new(&rhs_value) .map_err(|source| Error::RegexCompile { source })? .is_match(&lhs_value), ConditionalOperator::RegexMismatch => !Regex::new(&rhs_value) .map_err(|source| Error::RegexCompile { source })? .is_match(&lhs_value), }; Ok(condition) } fn run_backtick(&self, raw: &str, token: &Token<'src>) -> RunResult<'src, String> { self .run_command(raw, &[]) .map_err(|output_error| Error::Backtick { token: *token, output_error, }) } pub(crate) fn run_command(&self, command: &str, args: &[&str]) -> Result { let mut cmd = self .context .module .settings .shell_command(self.context.config); cmd.arg(command); cmd.args(args); cmd.current_dir(self.context.working_directory()); cmd.export( &self.context.module.settings, self.context.dotenv, &self.scope, &self.context.module.unexports, ); cmd.stdin(Stdio::inherit()); cmd.stderr(if self.context.config.verbosity.quiet() { Stdio::null() } else { Stdio::inherit() }); InterruptHandler::guard(|| output(cmd)) } pub(crate) fn evaluate_line( &mut self, line: &Line<'src>, continued: bool, ) -> RunResult<'src, String> { let mut evaluated = String::new(); for (i, fragment) in line.fragments.iter().enumerate() { match fragment { Fragment::Text { token } => { let lexeme = token.lexeme().replace("{{{{", "{{"); if i == 0 && continued { evaluated += lexeme.trim_start(); } else { evaluated += &lexeme; } } Fragment::Interpolation { expression } => { evaluated += &self.evaluate_expression(expression)?; } } } Ok(evaluated) } pub(crate) fn evaluate_parameters( context: &ExecutionContext<'src, 'run>, is_dependency: bool, arguments: &[String], parameters: &[Parameter<'src>], ) -> RunResult<'src, (Scope<'src, 'run>, Vec)> { let mut evaluator = Self::new(context, is_dependency, context.scope); let mut positional = Vec::new(); let mut rest = arguments; for parameter in parameters { let value = if rest.is_empty() { if let Some(ref default) = parameter.default { let value = evaluator.evaluate_expression(default)?; positional.push(value.clone()); value } else if parameter.kind == ParameterKind::Star { String::new() } else { return Err(Error::Internal { message: "missing parameter without default".to_owned(), }); } } else if parameter.kind.is_variadic() { for value in rest { positional.push(value.clone()); } let value = rest.to_vec().join(" "); rest = &[]; value } else { let value = rest[0].clone(); positional.push(value.clone()); rest = &rest[1..]; value }; evaluator.scope.bind(Binding { constant: false, export: parameter.export, file_depth: 0, name: parameter.name, private: false, value, }); } Ok((evaluator.scope, positional)) } pub(crate) fn new( context: &ExecutionContext<'src, 'run>, is_dependency: bool, scope: &'run Scope<'src, 'run>, ) -> Self { Self { assignments: None, context: *context, is_dependency, scope: scope.child(), } } } #[cfg(test)] mod tests { use super::*; run_error! { name: backtick_code, src: " a: echo {{`f() { return 100; }; f`}} ", args: ["a"], error: Error::Backtick { token, output_error: OutputError::Code(code), }, check: { assert_eq!(code, 100); assert_eq!(token.lexeme(), "`f() { return 100; }; f`"); } } run_error! { name: export_assignment_backtick, src: r#" export exported_variable := "A" b := `echo $exported_variable` recipe: echo {{b}} "#, args: ["--quiet", "recipe"], error: Error::Backtick { token, output_error: OutputError::Code(_), }, check: { assert_eq!(token.lexeme(), "`echo $exported_variable`"); } } } just-1.40.0/src/execution_context.rs000064400000000000000000000012661046102023000156040ustar 00000000000000use super::*; #[derive(Copy, Clone)] pub(crate) struct ExecutionContext<'src: 'run, 'run> { pub(crate) config: &'run Config, pub(crate) dotenv: &'run BTreeMap, pub(crate) module: &'run Justfile<'src>, pub(crate) scope: &'run Scope<'src, 'run>, pub(crate) search: &'run Search, } impl<'src: 'run, 'run> ExecutionContext<'src, 'run> { pub(crate) fn working_directory(&self) -> PathBuf { let base = if self.module.is_submodule() { &self.module.working_directory } else { &self.search.working_directory }; if let Some(setting) = &self.module.settings.working_directory { base.join(setting) } else { base.into() } } } just-1.40.0/src/executor.rs000064400000000000000000000102401046102023000136630ustar 00000000000000use super::*; pub(crate) enum Executor<'a> { Command(&'a Interpreter<'a>), Shebang(Shebang<'a>), } impl Executor<'_> { pub(crate) fn command<'src>( &self, path: &Path, recipe: &'src str, working_directory: Option<&Path>, ) -> RunResult<'src, Command> { match self { Self::Command(interpreter) => { let mut command = Command::new(&interpreter.command.cooked); if let Some(working_directory) = working_directory { command.current_dir(working_directory); } for arg in &interpreter.arguments { command.arg(&arg.cooked); } command.arg(path); Ok(command) } Self::Shebang(shebang) => { // make script executable Platform::set_execute_permission(path).map_err(|error| Error::TempdirIo { recipe, io_error: error, })?; // create command to run script Platform::make_shebang_command(path, working_directory, *shebang).map_err(|output_error| { Error::Cygpath { recipe, output_error, } }) } } } pub(crate) fn script_filename(&self, recipe: &str, extension: Option<&str>) -> String { let extension = extension.unwrap_or_else(|| { let interpreter = match self { Self::Command(interpreter) => &interpreter.command.cooked, Self::Shebang(shebang) => shebang.interpreter_filename(), }; match interpreter { "cmd" | "cmd.exe" => ".bat", "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => ".ps1", _ => "", } }); format!("{recipe}{extension}") } pub(crate) fn error<'src>(&self, io_error: io::Error, recipe: &'src str) -> Error<'src> { match self { Self::Command(Interpreter { command, arguments }) => { let mut command = command.cooked.clone(); for arg in arguments { command.push(' '); command.push_str(&arg.cooked); } Error::Script { command, io_error, recipe, } } Self::Shebang(shebang) => Error::Shebang { argument: shebang.argument.map(String::from), command: shebang.interpreter.to_owned(), io_error, recipe, }, } } // Script text for `recipe` given evaluated `lines` including blanks so line // numbers in errors from generated script match justfile source lines. pub(crate) fn script(&self, recipe: &Recipe, lines: &[String]) -> String { let mut script = String::new(); let mut n = 0; let shebangs = recipe .body .iter() .take_while(|line| line.is_shebang()) .count(); if let Self::Shebang(shebang) = self { for shebang_line in &lines[..shebangs] { if shebang.include_shebang_line() { script.push_str(shebang_line); } script.push('\n'); n += 1; } } for (line, text) in recipe.body.iter().zip(lines).skip(n) { while n < line.number { script.push('\n'); n += 1; } script.push_str(text); script.push('\n'); n += 1; } script } } #[cfg(test)] mod tests { use super::*; #[test] fn shebang_script_filename() { #[track_caller] fn case(interpreter: &str, recipe: &str, extension: Option<&str>, expected: &str) { assert_eq!( Executor::Shebang(Shebang::new(&format!("#!{interpreter}")).unwrap()) .script_filename(recipe, extension), expected ); assert_eq!( Executor::Command(&Interpreter { command: StringLiteral::from_raw(interpreter), arguments: Vec::new() }) .script_filename(recipe, extension), expected ); } case("bar", "foo", Some(".sh"), "foo.sh"); case("pwsh.exe", "foo", Some(".sh"), "foo.sh"); case("cmd.exe", "foo", Some(".sh"), "foo.sh"); case("powershell", "foo", None, "foo.ps1"); case("pwsh", "foo", None, "foo.ps1"); case("powershell.exe", "foo", None, "foo.ps1"); case("pwsh.exe", "foo", None, "foo.ps1"); case("cmd", "foo", None, "foo.bat"); case("cmd.exe", "foo", None, "foo.bat"); case("bar", "foo", None, "foo"); } } just-1.40.0/src/expression.rs000064400000000000000000000120251046102023000142270ustar 00000000000000use super::*; /// An expression. Note that the Just language grammar has both an `expression` /// production of additions (`a + b`) and values, and a `value` production of /// all other value types (for example strings, function calls, and /// parenthetical groups). /// /// The parser parses both values and expressions into `Expression`s. #[derive(PartialEq, Debug, Clone)] pub(crate) enum Expression<'src> { /// `lhs && rhs` And { lhs: Box>, rhs: Box>, }, /// `assert(condition, error)` Assert { condition: Condition<'src>, error: Box>, }, /// `contents` Backtick { contents: String, token: Token<'src>, }, /// `name(arguments)` Call { thunk: Thunk<'src> }, /// `lhs + rhs` Concatenation { lhs: Box>, rhs: Box>, }, /// `if condition { then } else { otherwise }` Conditional { condition: Condition<'src>, then: Box>, otherwise: Box>, }, /// `(contents)` Group { contents: Box> }, /// `lhs / rhs` Join { lhs: Option>>, rhs: Box>, }, /// `lhs || rhs` Or { lhs: Box>, rhs: Box>, }, /// `"string_literal"` or `'string_literal'` StringLiteral { string_literal: StringLiteral<'src> }, /// `variable` Variable { name: Name<'src> }, } impl<'src> Expression<'src> { pub(crate) fn variables<'expression>(&'expression self) -> Variables<'expression, 'src> { Variables::new(self) } } impl Display for Expression<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::And { lhs, rhs } => write!(f, "{lhs} && {rhs}"), Self::Assert { condition, error } => write!(f, "assert({condition}, {error})"), Self::Backtick { token, .. } => write!(f, "{}", token.lexeme()), Self::Call { thunk } => write!(f, "{thunk}"), Self::Concatenation { lhs, rhs } => write!(f, "{lhs} + {rhs}"), Self::Conditional { condition, then, otherwise, } => { if let Self::Conditional { .. } = **otherwise { write!(f, "if {condition} {{ {then} }} else {otherwise}") } else { write!(f, "if {condition} {{ {then} }} else {{ {otherwise} }}") } } Self::Group { contents } => write!(f, "({contents})"), Self::Join { lhs: None, rhs } => write!(f, "/ {rhs}"), Self::Join { lhs: Some(lhs), rhs, } => write!(f, "{lhs} / {rhs}"), Self::Or { lhs, rhs } => write!(f, "{lhs} || {rhs}"), Self::StringLiteral { string_literal } => write!(f, "{string_literal}"), Self::Variable { name } => write!(f, "{}", name.lexeme()), } } } impl Serialize for Expression<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { match self { Self::And { lhs, rhs } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("and")?; seq.serialize_element(lhs)?; seq.serialize_element(rhs)?; seq.end() } Self::Assert { condition, error } => { let mut seq: ::SerializeSeq = serializer.serialize_seq(None)?; seq.serialize_element("assert")?; seq.serialize_element(condition)?; seq.serialize_element(error)?; seq.end() } Self::Backtick { contents, .. } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("evaluate")?; seq.serialize_element(contents)?; seq.end() } Self::Call { thunk } => thunk.serialize(serializer), Self::Concatenation { lhs, rhs } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("concatenate")?; seq.serialize_element(lhs)?; seq.serialize_element(rhs)?; seq.end() } Self::Conditional { condition, then, otherwise, } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("if")?; seq.serialize_element(condition)?; seq.serialize_element(then)?; seq.serialize_element(otherwise)?; seq.end() } Self::Group { contents } => contents.serialize(serializer), Self::Join { lhs, rhs } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("join")?; seq.serialize_element(lhs)?; seq.serialize_element(rhs)?; seq.end() } Self::Or { lhs, rhs } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("or")?; seq.serialize_element(lhs)?; seq.serialize_element(rhs)?; seq.end() } Self::StringLiteral { string_literal } => string_literal.serialize(serializer), Self::Variable { name } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("variable")?; seq.serialize_element(name)?; seq.end() } } } } just-1.40.0/src/fragment.rs000064400000000000000000000012571046102023000136400ustar 00000000000000use super::*; /// A line fragment consisting either of… #[derive(PartialEq, Debug, Clone)] pub(crate) enum Fragment<'src> { /// …an interpolation containing `expression`. Interpolation { expression: Expression<'src> }, /// …raw text… Text { token: Token<'src> }, } impl Serialize for Fragment<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { match self { Self::Text { token } => serializer.serialize_str(token.lexeme()), Self::Interpolation { expression } => { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(expression)?; seq.end() } } } } just-1.40.0/src/function.rs000064400000000000000000000474761046102023000136770ustar 00000000000000use { super::*, heck::{ ToKebabCase, ToLowerCamelCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnakeCase, ToTitleCase, ToUpperCamelCase, }, semver::{Version, VersionReq}, std::collections::HashSet, Function::*, }; #[allow(clippy::arbitrary_source_item_ordering)] pub(crate) enum Function { Nullary(fn(Context) -> FunctionResult), Unary(fn(Context, &str) -> FunctionResult), UnaryOpt(fn(Context, &str, Option<&str>) -> FunctionResult), UnaryPlus(fn(Context, &str, &[String]) -> FunctionResult), Binary(fn(Context, &str, &str) -> FunctionResult), BinaryPlus(fn(Context, &str, &str, &[String]) -> FunctionResult), Ternary(fn(Context, &str, &str, &str) -> FunctionResult), } pub(crate) struct Context<'src: 'run, 'run> { pub(crate) evaluator: &'run Evaluator<'src, 'run>, pub(crate) name: Name<'src>, } impl<'src: 'run, 'run> Context<'src, 'run> { pub(crate) fn new(evaluator: &'run Evaluator<'src, 'run>, name: Name<'src>) -> Self { Self { evaluator, name } } } pub(crate) fn get(name: &str) -> Option { let name = if let Some(prefix) = name.strip_suffix("_dir") { format!("{prefix}_directory") } else if let Some(prefix) = name.strip_suffix("_dir_native") { format!("{prefix}_directory_native") } else { name.into() }; let function = match name.as_str() { "absolute_path" => Unary(absolute_path), "append" => Binary(append), "arch" => Nullary(arch), "blake3" => Unary(blake3), "blake3_file" => Unary(blake3_file), "cache_directory" => Nullary(|_| dir("cache", dirs::cache_dir)), "canonicalize" => Unary(canonicalize), "capitalize" => Unary(capitalize), "choose" => Binary(choose), "clean" => Unary(clean), "config_directory" => Nullary(|_| dir("config", dirs::config_dir)), "config_local_directory" => Nullary(|_| dir("local config", dirs::config_local_dir)), "data_directory" => Nullary(|_| dir("data", dirs::data_dir)), "data_local_directory" => Nullary(|_| dir("local data", dirs::data_local_dir)), "datetime" => Unary(datetime), "datetime_utc" => Unary(datetime_utc), "encode_uri_component" => Unary(encode_uri_component), "env" => UnaryOpt(env), "env_var" => Unary(env_var), "env_var_or_default" => Binary(env_var_or_default), "error" => Unary(error), "executable_directory" => Nullary(|_| dir("executable", dirs::executable_dir)), "extension" => Unary(extension), "file_name" => Unary(file_name), "file_stem" => Unary(file_stem), "home_directory" => Nullary(|_| dir("home", dirs::home_dir)), "invocation_directory" => Nullary(invocation_directory), "invocation_directory_native" => Nullary(invocation_directory_native), "is_dependency" => Nullary(is_dependency), "join" => BinaryPlus(join), "just_executable" => Nullary(just_executable), "just_pid" => Nullary(just_pid), "justfile" => Nullary(justfile), "justfile_directory" => Nullary(justfile_directory), "kebabcase" => Unary(kebabcase), "lowercamelcase" => Unary(lowercamelcase), "lowercase" => Unary(lowercase), "module_directory" => Nullary(module_directory), "module_file" => Nullary(module_file), "num_cpus" => Nullary(num_cpus), "os" => Nullary(os), "os_family" => Nullary(os_family), "parent_directory" => Unary(parent_directory), "path_exists" => Unary(path_exists), "prepend" => Binary(prepend), "quote" => Unary(quote), "read" => Unary(read), "replace" => Ternary(replace), "replace_regex" => Ternary(replace_regex), "require" => Unary(require), "semver_matches" => Binary(semver_matches), "sha256" => Unary(sha256), "sha256_file" => Unary(sha256_file), "shell" => UnaryPlus(shell), "shoutykebabcase" => Unary(shoutykebabcase), "shoutysnakecase" => Unary(shoutysnakecase), "snakecase" => Unary(snakecase), "source_directory" => Nullary(source_directory), "source_file" => Nullary(source_file), "style" => Unary(style), "titlecase" => Unary(titlecase), "trim" => Unary(trim), "trim_end" => Unary(trim_end), "trim_end_match" => Binary(trim_end_match), "trim_end_matches" => Binary(trim_end_matches), "trim_start" => Unary(trim_start), "trim_start_match" => Binary(trim_start_match), "trim_start_matches" => Binary(trim_start_matches), "uppercamelcase" => Unary(uppercamelcase), "uppercase" => Unary(uppercase), "uuid" => Nullary(uuid), "which" => Unary(which), "without_extension" => Unary(without_extension), _ => return None, }; Some(function) } impl Function { pub(crate) fn argc(&self) -> RangeInclusive { match *self { Nullary(_) => 0..=0, Unary(_) => 1..=1, UnaryOpt(_) => 1..=2, UnaryPlus(_) => 1..=usize::MAX, Binary(_) => 2..=2, BinaryPlus(_) => 2..=usize::MAX, Ternary(_) => 3..=3, } } } fn absolute_path(context: Context, path: &str) -> FunctionResult { let abs_path_unchecked = context .evaluator .context .working_directory() .join(path) .lexiclean(); match abs_path_unchecked.to_str() { Some(absolute_path) => Ok(absolute_path.to_owned()), None => Err(format!( "Working directory is not valid unicode: {}", context.evaluator.context.search.working_directory.display() )), } } fn append(_context: Context, suffix: &str, s: &str) -> FunctionResult { Ok( s.split_whitespace() .map(|s| format!("{s}{suffix}")) .collect::>() .join(" "), ) } fn arch(_context: Context) -> FunctionResult { Ok(target::arch().to_owned()) } fn blake3(_context: Context, s: &str) -> FunctionResult { Ok(blake3::hash(s.as_bytes()).to_string()) } fn blake3_file(context: Context, path: &str) -> FunctionResult { let path = context.evaluator.context.working_directory().join(path); let mut hasher = blake3::Hasher::new(); hasher .update_mmap_rayon(&path) .map_err(|err| format!("Failed to hash `{}`: {err}", path.display()))?; Ok(hasher.finalize().to_string()) } fn canonicalize(context: Context, path: &str) -> FunctionResult { let canonical = std::fs::canonicalize(context.evaluator.context.working_directory().join(path)) .map_err(|err| format!("I/O error canonicalizing path: {err}"))?; canonical.to_str().map(str::to_string).ok_or_else(|| { format!( "Canonical path is not valid unicode: {}", canonical.display(), ) }) } fn capitalize(_context: Context, s: &str) -> FunctionResult { let mut capitalized = String::new(); for (i, c) in s.chars().enumerate() { if i == 0 { capitalized.extend(c.to_uppercase()); } else { capitalized.extend(c.to_lowercase()); } } Ok(capitalized) } fn choose(_context: Context, n: &str, alphabet: &str) -> FunctionResult { let mut chars = HashSet::::with_capacity(alphabet.len()); for c in alphabet.chars() { if !chars.insert(c) { return Err(format!("alphabet contains repeated character `{c}`")); } } let alphabet = alphabet.chars().collect::>(); let n = n .parse::() .map_err(|err| format!("failed to parse `{n}` as positive integer: {err}"))?; let mut rng = rand::rng(); (0..n) .map(|_| { alphabet .choose(&mut rng) .ok_or_else(|| "empty alphabet".to_string()) }) .collect() } fn clean(_context: Context, path: &str) -> FunctionResult { Ok(Path::new(path).lexiclean().to_str().unwrap().to_owned()) } fn dir(name: &'static str, f: fn() -> Option) -> FunctionResult { match f() { Some(path) => path .as_os_str() .to_str() .map(str::to_string) .ok_or_else(|| { format!( "unable to convert {name} directory path to string: {}", path.display(), ) }), None => Err(format!("{name} directory not found")), } } fn datetime(_context: Context, format: &str) -> FunctionResult { Ok(chrono::Local::now().format(format).to_string()) } fn datetime_utc(_context: Context, format: &str) -> FunctionResult { Ok(chrono::Utc::now().format(format).to_string()) } fn encode_uri_component(_context: Context, s: &str) -> FunctionResult { static PERCENT_ENCODE: percent_encoding::AsciiSet = percent_encoding::NON_ALPHANUMERIC .remove(b'-') .remove(b'_') .remove(b'.') .remove(b'!') .remove(b'~') .remove(b'*') .remove(b'\'') .remove(b'(') .remove(b')'); Ok(percent_encoding::utf8_percent_encode(s, &PERCENT_ENCODE).to_string()) } fn env(context: Context, key: &str, default: Option<&str>) -> FunctionResult { match default { Some(val) => env_var_or_default(context, key, val), None => env_var(context, key), } } fn env_var(context: Context, key: &str) -> FunctionResult { use std::env::VarError::*; if let Some(value) = context.evaluator.context.dotenv.get(key) { return Ok(value.clone()); } match env::var(key) { Err(NotPresent) => Err(format!("environment variable `{key}` not present")), Err(NotUnicode(os_string)) => Err(format!( "environment variable `{key}` not unicode: {os_string:?}" )), Ok(value) => Ok(value), } } fn env_var_or_default(context: Context, key: &str, default: &str) -> FunctionResult { use std::env::VarError::*; if let Some(value) = context.evaluator.context.dotenv.get(key) { return Ok(value.clone()); } match env::var(key) { Err(NotPresent) => Ok(default.to_owned()), Err(NotUnicode(os_string)) => Err(format!( "environment variable `{key}` not unicode: {os_string:?}" )), Ok(value) => Ok(value), } } fn error(_context: Context, message: &str) -> FunctionResult { Err(message.to_owned()) } fn extension(_context: Context, path: &str) -> FunctionResult { Utf8Path::new(path) .extension() .map(str::to_owned) .ok_or_else(|| format!("Could not extract extension from `{path}`")) } fn file_name(_context: Context, path: &str) -> FunctionResult { Utf8Path::new(path) .file_name() .map(str::to_owned) .ok_or_else(|| format!("Could not extract file name from `{path}`")) } fn file_stem(_context: Context, path: &str) -> FunctionResult { Utf8Path::new(path) .file_stem() .map(str::to_owned) .ok_or_else(|| format!("Could not extract file stem from `{path}`")) } fn invocation_directory(context: Context) -> FunctionResult { Platform::convert_native_path( &context.evaluator.context.search.working_directory, &context.evaluator.context.config.invocation_directory, ) .map_err(|e| format!("Error getting shell path: {e}")) } fn invocation_directory_native(context: Context) -> FunctionResult { context .evaluator .context .config .invocation_directory .to_str() .map(str::to_owned) .ok_or_else(|| { format!( "Invocation directory is not valid unicode: {}", context .evaluator .context .config .invocation_directory .display() ) }) } fn is_dependency(context: Context) -> FunctionResult { Ok(context.evaluator.is_dependency.to_string()) } fn prepend(_context: Context, prefix: &str, s: &str) -> FunctionResult { Ok( s.split_whitespace() .map(|s| format!("{prefix}{s}")) .collect::>() .join(" "), ) } fn join(_context: Context, base: &str, with: &str, and: &[String]) -> FunctionResult { let mut result = Utf8Path::new(base).join(with); for arg in and { result.push(arg); } Ok(result.to_string()) } fn just_executable(_context: Context) -> FunctionResult { let exe_path = env::current_exe().map_err(|e| format!("Error getting current executable: {e}"))?; exe_path.to_str().map(str::to_owned).ok_or_else(|| { format!( "Executable path is not valid unicode: {}", exe_path.display() ) }) } fn just_pid(_context: Context) -> FunctionResult { Ok(std::process::id().to_string()) } fn justfile(context: Context) -> FunctionResult { context .evaluator .context .search .justfile .to_str() .map(str::to_owned) .ok_or_else(|| { format!( "Justfile path is not valid unicode: {}", context.evaluator.context.search.justfile.display() ) }) } fn justfile_directory(context: Context) -> FunctionResult { let justfile_directory = context .evaluator .context .search .justfile .parent() .ok_or_else(|| { format!( "Could not resolve justfile directory. Justfile `{}` had no parent.", context.evaluator.context.search.justfile.display() ) })?; justfile_directory .to_str() .map(str::to_owned) .ok_or_else(|| { format!( "Justfile directory is not valid unicode: {}", justfile_directory.display() ) }) } fn kebabcase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_kebab_case()) } fn lowercamelcase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_lower_camel_case()) } fn lowercase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_lowercase()) } fn module_directory(context: Context) -> FunctionResult { let module_directory = context.evaluator.context.module.source.parent().unwrap(); module_directory.to_str().map(str::to_owned).ok_or_else(|| { format!( "Module directory is not valid unicode: {}", module_directory.display(), ) }) } fn module_file(context: Context) -> FunctionResult { let module_file = &context.evaluator.context.module.source; module_file.to_str().map(str::to_owned).ok_or_else(|| { format!( "Module file path is not valid unicode: {}", module_file.display(), ) }) } fn num_cpus(_context: Context) -> FunctionResult { let num = num_cpus::get(); Ok(num.to_string()) } fn os(_context: Context) -> FunctionResult { Ok(target::os().to_owned()) } fn os_family(_context: Context) -> FunctionResult { Ok(target::family().to_owned()) } fn parent_directory(_context: Context, path: &str) -> FunctionResult { Utf8Path::new(path) .parent() .map(Utf8Path::to_string) .ok_or_else(|| format!("Could not extract parent directory from `{path}`")) } fn path_exists(context: Context, path: &str) -> FunctionResult { Ok( context .evaluator .context .working_directory() .join(path) .exists() .to_string(), ) } fn quote(_context: Context, s: &str) -> FunctionResult { Ok(format!("'{}'", s.replace('\'', "'\\''"))) } fn read(context: Context, filename: &str) -> FunctionResult { fs::read_to_string(context.evaluator.context.working_directory().join(filename)) .map_err(|err| format!("I/O error reading `{filename}`: {err}")) } fn replace(_context: Context, s: &str, from: &str, to: &str) -> FunctionResult { Ok(s.replace(from, to)) } fn require(context: Context, name: &str) -> FunctionResult { crate::which(context, name)?.ok_or_else(|| format!("could not find executable `{name}`")) } fn replace_regex(_context: Context, s: &str, regex: &str, replacement: &str) -> FunctionResult { Ok( Regex::new(regex) .map_err(|err| err.to_string())? .replace_all(s, replacement) .to_string(), ) } fn sha256(_context: Context, s: &str) -> FunctionResult { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(s); let hash = hasher.finalize(); Ok(format!("{hash:x}")) } fn sha256_file(context: Context, path: &str) -> FunctionResult { use sha2::{Digest, Sha256}; let path = context.evaluator.context.working_directory().join(path); let mut hasher = Sha256::new(); let mut file = fs::File::open(&path).map_err(|err| format!("Failed to open `{}`: {err}", path.display()))?; std::io::copy(&mut file, &mut hasher) .map_err(|err| format!("Failed to read `{}`: {err}", path.display()))?; let hash = hasher.finalize(); Ok(format!("{hash:x}")) } fn shell(context: Context, command: &str, args: &[String]) -> FunctionResult { let args = iter::once(command) .chain(args.iter().map(String::as_str)) .collect::>(); context .evaluator .run_command(command, &args) .map_err(|output_error| output_error.to_string()) } fn shoutykebabcase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_shouty_kebab_case()) } fn shoutysnakecase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_shouty_snake_case()) } fn snakecase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_snake_case()) } fn source_directory(context: Context) -> FunctionResult { context .evaluator .context .search .justfile .parent() .unwrap() .join(context.name.token.path) .parent() .unwrap() .to_str() .map(str::to_owned) .ok_or_else(|| { format!( "Source file path not valid unicode: {}", context.name.token.path.display(), ) }) } fn source_file(context: Context) -> FunctionResult { context .evaluator .context .search .justfile .parent() .unwrap() .join(context.name.token.path) .to_str() .map(str::to_owned) .ok_or_else(|| { format!( "Source file path not valid unicode: {}", context.name.token.path.display(), ) }) } fn style(context: Context, s: &str) -> FunctionResult { match s { "command" => Ok( Color::always() .command(context.evaluator.context.config.command_color) .prefix() .to_string(), ), "error" => Ok(Color::always().error().prefix().to_string()), "warning" => Ok(Color::always().warning().prefix().to_string()), _ => Err(format!("unknown style: `{s}`")), } } fn titlecase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_title_case()) } fn trim(_context: Context, s: &str) -> FunctionResult { Ok(s.trim().to_owned()) } fn trim_end(_context: Context, s: &str) -> FunctionResult { Ok(s.trim_end().to_owned()) } fn trim_end_match(_context: Context, s: &str, pat: &str) -> FunctionResult { Ok(s.strip_suffix(pat).unwrap_or(s).to_owned()) } fn trim_end_matches(_context: Context, s: &str, pat: &str) -> FunctionResult { Ok(s.trim_end_matches(pat).to_owned()) } fn trim_start(_context: Context, s: &str) -> FunctionResult { Ok(s.trim_start().to_owned()) } fn trim_start_match(_context: Context, s: &str, pat: &str) -> FunctionResult { Ok(s.strip_prefix(pat).unwrap_or(s).to_owned()) } fn trim_start_matches(_context: Context, s: &str, pat: &str) -> FunctionResult { Ok(s.trim_start_matches(pat).to_owned()) } fn uppercamelcase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_upper_camel_case()) } fn uppercase(_context: Context, s: &str) -> FunctionResult { Ok(s.to_uppercase()) } fn uuid(_context: Context) -> FunctionResult { Ok(uuid::Uuid::new_v4().to_string()) } fn which(context: Context, name: &str) -> FunctionResult { Ok(crate::which(context, name)?.unwrap_or_default()) } fn without_extension(_context: Context, path: &str) -> FunctionResult { let parent = Utf8Path::new(path) .parent() .ok_or_else(|| format!("Could not extract parent from `{path}`"))?; let file_stem = Utf8Path::new(path) .file_stem() .ok_or_else(|| format!("Could not extract file stem from `{path}`"))?; Ok(parent.join(file_stem).to_string()) } /// Check whether a string processes properly as semver (e.x. "0.1.0") /// and matches a given semver requirement (e.x. ">=0.1.0") fn semver_matches(_context: Context, version: &str, requirement: &str) -> FunctionResult { Ok( requirement .parse::() .map_err(|err| format!("invalid semver requirement: {err}"))? .matches( &version .parse::() .map_err(|err| format!("invalid semver version: {err}"))?, ) .to_string(), ) } #[cfg(test)] mod tests { use super::*; #[test] fn dir_not_found() { assert_eq!(dir("foo", || None).unwrap_err(), "foo directory not found"); } #[cfg(unix)] #[test] fn dir_not_unicode() { use std::os::unix::ffi::OsStrExt; assert_eq!( dir("foo", || Some( std::ffi::OsStr::from_bytes(b"\xe0\x80\x80").into() )) .unwrap_err(), "unable to convert foo directory path to string: ���", ); } } just-1.40.0/src/fuzzing.rs000064400000000000000000000001201046102023000135150ustar 00000000000000use super::*; pub fn compile(text: &str) { let _ = testing::compile(text); } just-1.40.0/src/interpreter.rs000064400000000000000000000013521046102023000143740ustar 00000000000000use super::*; #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)] pub(crate) struct Interpreter<'src> { pub(crate) arguments: Vec>, pub(crate) command: StringLiteral<'src>, } impl Interpreter<'_> { pub(crate) fn default_script_interpreter() -> &'static Interpreter<'static> { static INSTANCE: Lazy> = Lazy::new(|| Interpreter { arguments: vec![StringLiteral::from_raw("-eu")], command: StringLiteral::from_raw("sh"), }); &INSTANCE } } impl Display for Interpreter<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.command)?; for argument in &self.arguments { write!(f, ", {argument}")?; } Ok(()) } } just-1.40.0/src/interrupt_guard.rs000064400000000000000000000004121046102023000152430ustar 00000000000000use super::*; pub(crate) struct InterruptGuard; impl InterruptGuard { pub(crate) fn new() -> Self { InterruptHandler::instance().block(); Self } } impl Drop for InterruptGuard { fn drop(&mut self) { InterruptHandler::instance().unblock(); } } just-1.40.0/src/interrupt_handler.rs000064400000000000000000000034321046102023000155630ustar 00000000000000use super::*; pub(crate) struct InterruptHandler { blocks: u32, interrupted: bool, verbosity: Verbosity, } impl InterruptHandler { pub(crate) fn install(verbosity: Verbosity) -> Result<(), ctrlc::Error> { let mut instance = Self::instance(); instance.verbosity = verbosity; ctrlc::set_handler(|| Self::instance().interrupt()) } pub(crate) fn instance() -> MutexGuard<'static, Self> { static INSTANCE: Mutex = Mutex::new(InterruptHandler::new()); match INSTANCE.lock() { Ok(guard) => guard, Err(poison_error) => { eprintln!( "{}", Error::Internal { message: format!("interrupt handler mutex poisoned: {poison_error}"), } .color_display(Color::auto().stderr()) ); process::exit(EXIT_FAILURE); } } } const fn new() -> Self { Self { blocks: 0, interrupted: false, verbosity: Verbosity::default(), } } fn interrupt(&mut self) { self.interrupted = true; if self.blocks > 0 { return; } Self::exit(); } fn exit() { process::exit(130); } pub(crate) fn block(&mut self) { self.blocks += 1; } pub(crate) fn unblock(&mut self) { if self.blocks == 0 { if self.verbosity.loud() { eprintln!( "{}", Error::Internal { message: "attempted to unblock interrupt handler, but handler was not blocked" .to_owned(), } .color_display(Color::auto().stderr()) ); } process::exit(EXIT_FAILURE); } self.blocks -= 1; if self.interrupted { Self::exit(); } } pub(crate) fn guard T>(function: F) -> T { let _guard = InterruptGuard::new(); function() } } just-1.40.0/src/item.rs000064400000000000000000000030561046102023000127720ustar 00000000000000use super::*; /// A single top-level item #[derive(Debug, Clone)] pub(crate) enum Item<'src> { Alias(Alias<'src, Namepath<'src>>), Assignment(Assignment<'src>), Comment(&'src str), Import { absolute: Option, optional: bool, path: Token<'src>, relative: StringLiteral<'src>, }, Module { absolute: Option, doc: Option, groups: Vec, name: Name<'src>, optional: bool, relative: Option>, }, Recipe(UnresolvedRecipe<'src>), Set(Set<'src>), Unexport { name: Name<'src>, }, } impl Display for Item<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::Alias(alias) => write!(f, "{alias}"), Self::Assignment(assignment) => write!(f, "{assignment}"), Self::Comment(comment) => write!(f, "{comment}"), Self::Import { relative, optional, .. } => { write!(f, "import")?; if *optional { write!(f, "?")?; } write!(f, " {relative}") } Self::Module { name, relative, optional, .. } => { write!(f, "mod")?; if *optional { write!(f, "?")?; } write!(f, " {name}")?; if let Some(path) = relative { write!(f, " {path}")?; } Ok(()) } Self::Recipe(recipe) => write!(f, "{}", recipe.color_display(Color::never())), Self::Set(set) => write!(f, "{set}"), Self::Unexport { name } => write!(f, "unexport {name}"), } } } just-1.40.0/src/justfile.rs000064400000000000000000000536511046102023000136670ustar 00000000000000use {super::*, serde::Serialize}; #[derive(Debug)] struct Invocation<'src: 'run, 'run> { arguments: Vec<&'run str>, module: &'run Justfile<'src>, recipe: &'run Recipe<'src>, scope: &'run Scope<'src, 'run>, } #[derive(Debug, PartialEq, Serialize)] pub(crate) struct Justfile<'src> { pub(crate) aliases: Table<'src, Alias<'src>>, pub(crate) assignments: Table<'src, Assignment<'src>>, #[serde(rename = "first", serialize_with = "keyed::serialize_option")] pub(crate) default: Option>>, pub(crate) doc: Option, pub(crate) groups: Vec, #[serde(skip)] pub(crate) loaded: Vec, pub(crate) modules: Table<'src, Justfile<'src>>, #[serde(skip)] pub(crate) name: Option>, pub(crate) recipes: Table<'src, Rc>>, pub(crate) settings: Settings<'src>, pub(crate) source: PathBuf, pub(crate) unexports: HashSet, #[serde(skip)] pub(crate) unstable_features: BTreeSet, pub(crate) warnings: Vec, #[serde(skip)] pub(crate) working_directory: PathBuf, } impl<'src> Justfile<'src> { fn find_suggestion( input: &str, candidates: impl Iterator>, ) -> Option> { candidates .map(|suggestion| (edit_distance(input, suggestion.name), suggestion)) .filter(|(distance, _suggestion)| *distance < 3) .min_by_key(|(distance, _suggestion)| *distance) .map(|(_distance, suggestion)| suggestion) } pub(crate) fn suggest_recipe(&self, input: &str) -> Option> { Self::find_suggestion( input, self .recipes .keys() .map(|name| Suggestion { name, target: None }) .chain(self.aliases.iter().map(|(name, alias)| Suggestion { name, target: Some(alias.target.name.lexeme()), })), ) } pub(crate) fn suggest_variable(&self, input: &str) -> Option> { Self::find_suggestion( input, self .assignments .keys() .map(|name| Suggestion { name, target: None }), ) } pub(crate) fn run( &self, config: &Config, search: &Search, overrides: &BTreeMap, arguments: &[String], ) -> RunResult<'src> { let unknown_overrides = overrides .keys() .filter(|name| !self.assignments.contains_key(name.as_str())) .cloned() .collect::>(); if !unknown_overrides.is_empty() { return Err(Error::UnknownOverrides { overrides: unknown_overrides, }); } let dotenv = if config.load_dotenv { load_dotenv(config, &self.settings, &search.working_directory)? } else { BTreeMap::new() }; let root = Scope::root(); let scope = Evaluator::evaluate_assignments(config, &dotenv, self, overrides, &root, search)?; match &config.subcommand { Subcommand::Command { binary, arguments, .. } => { let mut command = if config.shell_command { let mut command = self.settings.shell_command(config); command.arg(binary); command } else { Command::new(binary) }; command.args(arguments); command.current_dir(&search.working_directory); let scope = scope.child(); command.export(&self.settings, &dotenv, &scope, &self.unexports); let status = InterruptHandler::guard(|| command.status()).map_err(|io_error| { Error::CommandInvoke { binary: binary.clone(), arguments: arguments.clone(), io_error, } })?; if !status.success() { return Err(Error::CommandStatus { binary: binary.clone(), arguments: arguments.clone(), status, }); }; return Ok(()); } Subcommand::Evaluate { variable, .. } => { if let Some(variable) = variable { if let Some(value) = scope.value(variable) { print!("{value}"); } else { return Err(Error::EvalUnknownVariable { suggestion: self.suggest_variable(variable), variable: variable.clone(), }); } } else { let width = scope.names().fold(0, |max, name| name.len().max(max)); for binding in scope.bindings() { if !binding.private { println!( "{0:1$} := \"{2}\"", binding.name.lexeme(), width, binding.value ); } } } return Ok(()); } _ => {} } let arguments = arguments.iter().map(String::as_str).collect::>(); let groups = ArgumentParser::parse_arguments(self, &arguments)?; let arena: Arena = Arena::new(); let mut invocations = Vec::::new(); let mut scopes = BTreeMap::new(); for group in &groups { invocations.push(self.invocation( &arena, &group.arguments, config, &dotenv, &scope, &group.path, 0, &mut scopes, search, )?); } if config.one && invocations.len() > 1 { return Err(Error::ExcessInvocations { invocations: invocations.len(), }); } let mut ran = Ran::default(); for invocation in invocations { let context = ExecutionContext { config, dotenv: &dotenv, module: invocation.module, scope: invocation.scope, search, }; Self::run_recipe( &invocation .arguments .iter() .copied() .map(str::to_string) .collect::>(), &context, &mut ran, invocation.recipe, false, )?; } Ok(()) } pub(crate) fn check_unstable(&self, config: &Config) -> RunResult<'src> { if let Some(&unstable_feature) = self.unstable_features.iter().next() { config.require_unstable(self, unstable_feature)?; } for module in self.modules.values() { module.check_unstable(config)?; } Ok(()) } pub(crate) fn get_alias(&self, name: &str) -> Option<&Alias<'src>> { self.aliases.get(name) } pub(crate) fn get_recipe(&self, name: &str) -> Option<&Recipe<'src>> { self .recipes .get(name) .map(Rc::as_ref) .or_else(|| self.aliases.get(name).map(|alias| alias.target.as_ref())) } fn invocation<'run>( &'run self, arena: &'run Arena>, arguments: &[&'run str], config: &'run Config, dotenv: &'run BTreeMap, parent: &'run Scope<'src, 'run>, path: &'run [String], position: usize, scopes: &mut BTreeMap<&'run [String], &'run Scope<'src, 'run>>, search: &'run Search, ) -> RunResult<'src, Invocation<'src, 'run>> { if position + 1 == path.len() { let recipe = self.get_recipe(&path[position]).unwrap(); Ok(Invocation { arguments: arguments.into(), module: self, recipe, scope: parent, }) } else { let module = self.modules.get(&path[position]).unwrap(); let scope = if let Some(scope) = scopes.get(&path[..position]) { scope } else { let scope = Evaluator::evaluate_assignments( config, dotenv, module, &BTreeMap::new(), parent, search, )?; let scope = arena.alloc(scope); scopes.insert(path, scope); scopes.get(path).unwrap() }; module.invocation( arena, arguments, config, dotenv, scope, path, position + 1, scopes, search, ) } } pub(crate) fn is_submodule(&self) -> bool { self.name.is_some() } pub(crate) fn name(&self) -> &'src str { self.name.map(|name| name.lexeme()).unwrap_or_default() } fn run_recipe( arguments: &[String], context: &ExecutionContext<'src, '_>, ran: &mut Ran<'src>, recipe: &Recipe<'src>, is_dependency: bool, ) -> RunResult<'src> { if ran.has_run(&recipe.namepath, arguments) { return Ok(()); } if !context.config.yes && !recipe.confirm()? { return Err(Error::NotConfirmed { recipe: recipe.name(), }); } let (outer, positional) = Evaluator::evaluate_parameters(context, is_dependency, arguments, &recipe.parameters)?; let scope = outer.child(); let mut evaluator = Evaluator::new(context, true, &scope); if !context.config.no_dependencies { for Dependency { recipe, arguments } in recipe.dependencies.iter().take(recipe.priors) { let arguments = arguments .iter() .map(|argument| evaluator.evaluate_expression(argument)) .collect::>>()?; Self::run_recipe(&arguments, context, ran, recipe, true)?; } } recipe.run(context, &scope, &positional, is_dependency)?; if !context.config.no_dependencies { let mut ran = Ran::default(); for Dependency { recipe, arguments } in recipe.subsequents() { let mut evaluated = Vec::new(); for argument in arguments { evaluated.push(evaluator.evaluate_expression(argument)?); } Self::run_recipe(&evaluated, context, &mut ran, recipe, true)?; } } ran.ran(&recipe.namepath, arguments.to_vec()); Ok(()) } pub(crate) fn modules(&self, config: &Config) -> Vec<&Justfile> { let mut modules = self.modules.values().collect::>(); if config.unsorted { modules.sort_by_key(|module| { module .name .map(|name| name.token.offset) .unwrap_or_default() }); } modules } pub(crate) fn public_recipes(&self, config: &Config) -> Vec<&Recipe> { let mut recipes = self .recipes .values() .map(AsRef::as_ref) .filter(|recipe| recipe.is_public()) .collect::>(); if config.unsorted { recipes.sort_by_key(|recipe| (&recipe.import_offsets, recipe.name.offset)); } recipes } pub(crate) fn groups(&self) -> &[String] { &self.groups } pub(crate) fn public_groups(&self, config: &Config) -> Vec { let mut groups = Vec::new(); for recipe in self.recipes.values() { if recipe.is_public() { for group in recipe.groups() { groups.push((recipe.import_offsets.as_slice(), recipe.name.offset, group)); } } } for submodule in self.modules.values() { for group in submodule.groups() { groups.push((&[], submodule.name.unwrap().offset, group.to_string())); } } if config.unsorted { groups.sort(); } else { groups.sort_by(|(_, _, a), (_, _, b)| a.cmp(b)); } let mut seen = HashSet::new(); groups.retain(|(_, _, group)| seen.insert(group.clone())); groups.into_iter().map(|(_, _, group)| group).collect() } } impl ColorDisplay for Justfile<'_> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { let mut items = self.recipes.len() + self.assignments.len() + self.aliases.len(); for (name, assignment) in &self.assignments { if assignment.export { write!(f, "export ")?; } write!(f, "{name} := {}", assignment.value)?; items -= 1; if items != 0 { write!(f, "\n\n")?; } } for alias in self.aliases.values() { write!(f, "{alias}")?; items -= 1; if items != 0 { write!(f, "\n\n")?; } } for recipe in self.recipes.values() { write!(f, "{}", recipe.color_display(color))?; items -= 1; if items != 0 { write!(f, "\n\n")?; } } Ok(()) } } impl<'src> Keyed<'src> for Justfile<'src> { fn key(&self) -> &'src str { self.name() } } #[cfg(test)] mod tests { use super::*; use testing::compile; use Error::*; run_error! { name: unknown_recipe_no_suggestion, src: "a:\nb:\nc:", args: ["a", "xyz", "y", "z"], error: UnknownRecipe { recipe, suggestion, }, check: { assert_eq!(recipe, "xyz"); assert_eq!(suggestion, None); } } run_error! { name: unknown_recipe_with_suggestion, src: "a:\nb:\nc:", args: ["a", "x", "y", "z"], error: UnknownRecipe { recipe, suggestion, }, check: { assert_eq!(recipe, "x"); assert_eq!(suggestion, Some(Suggestion { name: "a", target: None, })); } } run_error! { name: unknown_recipe_show_alias_suggestion, src: " foo: echo foo alias z := foo ", args: ["zz"], error: UnknownRecipe { recipe, suggestion, }, check: { assert_eq!(recipe, "zz"); assert_eq!(suggestion, Some(Suggestion { name: "z", target: Some("foo"), } )); } } run_error! { name: code_error, src: " fail: @exit 100 ", args: ["fail"], error: Code { recipe, line_number, code, print_message, }, check: { assert_eq!(recipe, "fail"); assert_eq!(code, 100); assert_eq!(line_number, Some(2)); assert!(print_message); } } run_error! { name: run_args, src: r#" a return code: @x() { {{return}} {{code + "0"}}; }; x "#, args: ["a", "return", "15"], error: Code { recipe, line_number, code, print_message, }, check: { assert_eq!(recipe, "a"); assert_eq!(code, 150); assert_eq!(line_number, Some(2)); assert!(print_message); } } run_error! { name: missing_some_arguments, src: "a b c d:", args: ["a", "b", "c"], error: ArgumentCountMismatch { recipe, parameters, found, min, max, }, check: { let param_names = parameters .iter() .map(|p| p.name.lexeme()) .collect::>(); assert_eq!(recipe, "a"); assert_eq!(param_names, ["b", "c", "d"]); assert_eq!(found, 2); assert_eq!(min, 3); assert_eq!(max, 3); } } run_error! { name: missing_some_arguments_variadic, src: "a b c +d:", args: ["a", "B", "C"], error: ArgumentCountMismatch { recipe, parameters, found, min, max, }, check: { let param_names = parameters .iter() .map(|p| p.name.lexeme()) .collect::>(); assert_eq!(recipe, "a"); assert_eq!(param_names, ["b", "c", "d"]); assert_eq!(found, 2); assert_eq!(min, 3); assert_eq!(max, usize::MAX - 1); } } run_error! { name: missing_all_arguments, src: "a b c d:\n echo {{b}}{{c}}{{d}}", args: ["a"], error: ArgumentCountMismatch { recipe, parameters, found, min, max, }, check: { let param_names = parameters .iter() .map(|p| p.name.lexeme()) .collect::>(); assert_eq!(recipe, "a"); assert_eq!(param_names, ["b", "c", "d"]); assert_eq!(found, 0); assert_eq!(min, 3); assert_eq!(max, 3); } } run_error! { name: missing_some_defaults, src: "a b c d='hello':", args: ["a", "b"], error: ArgumentCountMismatch { recipe, parameters, found, min, max, }, check: { let param_names = parameters .iter() .map(|p| p.name.lexeme()) .collect::>(); assert_eq!(recipe, "a"); assert_eq!(param_names, ["b", "c", "d"]); assert_eq!(found, 1); assert_eq!(min, 2); assert_eq!(max, 3); } } run_error! { name: missing_all_defaults, src: "a b c='r' d='h':", args: ["a"], error: ArgumentCountMismatch { recipe, parameters, found, min, max, }, check: { let param_names = parameters .iter() .map(|p| p.name.lexeme()) .collect::>(); assert_eq!(recipe, "a"); assert_eq!(param_names, ["b", "c", "d"]); assert_eq!(found, 0); assert_eq!(min, 1); assert_eq!(max, 3); } } run_error! { name: unknown_overrides, src: " a: echo {{`f() { return 100; }; f`}} ", args: ["foo=bar", "baz=bob", "a"], error: UnknownOverrides { overrides }, check: { assert_eq!(overrides, &["baz", "foo"]); } } run_error! { name: export_failure, src: r#" export foo := "a" baz := "c" export bar := "b" export abc := foo + bar + baz wut: echo $foo $bar $baz "#, args: ["--quiet", "wut"], error: Code { recipe, line_number, print_message, .. }, check: { assert_eq!(recipe, "wut"); assert_eq!(line_number, Some(7)); assert!(print_message); } } fn case(input: &str, expected: &str) { let justfile = compile(input); let actual = format!("{}", justfile.color_display(Color::never())); assert_eq!(actual, expected); println!("Re-parsing..."); let reparsed = compile(&actual); let redumped = format!("{}", reparsed.color_display(Color::never())); assert_eq!(redumped, actual); } #[test] fn parse_empty() { case( " # hello ", "", ); } #[test] fn parse_string_default() { case( r#" foo a="b\t": "#, r#"foo a="b\t":"#, ); } #[test] fn parse_multiple() { case( r" a: b: ", r"a: b:", ); } #[test] fn parse_variadic() { case( r" foo +a: ", r"foo +a:", ); } #[test] fn parse_variadic_string_default() { case( r#" foo +a="Hello": "#, r#"foo +a="Hello":"#, ); } #[test] fn parse_raw_string_default() { case( r" foo a='b\t': ", r"foo a='b\t':", ); } #[test] fn parse_export() { case( r#" export a := "hello" "#, r#"export a := "hello""#, ); } #[test] fn parse_alias_after_target() { case( r" foo: echo a alias f := foo ", r"alias f := foo foo: echo a", ); } #[test] fn parse_alias_before_target() { case( r" alias f := foo foo: echo a ", r"alias f := foo foo: echo a", ); } #[test] fn parse_alias_with_comment() { case( r" alias f := foo #comment foo: echo a ", r"alias f := foo foo: echo a", ); } #[test] fn parse_complex() { case( " x: y: z: foo := \"xx\" bar := foo goodbye := \"y\" hello a b c : x y z #hello #! blah #blarg {{ foo + bar}}abc{{ goodbye\t + \"x\" }}xyz 1 2 3 ", "bar := foo foo := \"xx\" goodbye := \"y\" hello a b c: x y z #! blah #blarg {{ foo + bar }}abc{{ goodbye + \"x\" }}xyz 1 2 3 x: y: z:", ); } #[test] fn parse_shebang() { case( " practicum := 'hello' install: \t#!/bin/sh \tif [[ -f {{practicum}} ]]; then \t\treturn \tfi ", "practicum := 'hello' install: #!/bin/sh if [[ -f {{ practicum }} ]]; then \treturn fi", ); } #[test] fn parse_simple_shebang() { case("a:\n #!\n print(1)", "a:\n #!\n print(1)"); } #[test] fn parse_assignments() { case( r#"a := "0" c := a + b + a + b b := "1" "#, r#"a := "0" b := "1" c := a + b + a + b"#, ); } #[test] fn parse_assignment_backticks() { case( "a := `echo hello` c := a + b + a + b b := `echo goodbye`", "a := `echo hello` b := `echo goodbye` c := a + b + a + b", ); } #[test] fn parse_interpolation_backticks() { case( r#"a: echo {{ `echo hello` + "blarg" }} {{ `echo bob` }}"#, r#"a: echo {{ `echo hello` + "blarg" }} {{ `echo bob` }}"#, ); } #[test] fn eof_test() { case("x:\ny:\nz:\na b c: x y z", "a b c: x y z\n\nx:\n\ny:\n\nz:"); } #[test] fn string_quote_escape() { case(r#"a := "hello\"""#, r#"a := "hello\"""#); } #[test] fn string_escapes() { case(r#"a := "\n\t\r\"\\""#, r#"a := "\n\t\r\"\\""#); } #[test] fn parameters() { case( "a b c: {{b}} {{c}}", "a b c: {{ b }} {{ c }}", ); } #[test] fn unary_functions() { case( " x := arch() a: {{os()}} {{os_family()}} {{num_cpus()}}", "x := arch() a: {{ os() }} {{ os_family() }} {{ num_cpus() }}", ); } #[test] fn env_functions() { case( r#" x := env_var('foo',) a: {{env_var_or_default('foo' + 'bar', 'baz',)}} {{env_var(env_var("baz"))}}"#, r#"x := env_var('foo') a: {{ env_var_or_default('foo' + 'bar', 'baz') }} {{ env_var(env_var("baz")) }}"#, ); } #[test] fn parameter_default_string() { case( r#" f x="abc": "#, r#"f x="abc":"#, ); } #[test] fn parameter_default_raw_string() { case( r" f x='abc': ", r"f x='abc':", ); } #[test] fn parameter_default_backtick() { case( r" f x=`echo hello`: ", r"f x=`echo hello`:", ); } #[test] fn parameter_default_concatenation_string() { case( r#" f x=(`echo hello` + "foo"): "#, r#"f x=(`echo hello` + "foo"):"#, ); } #[test] fn parameter_default_concatenation_variable() { case( r#" x := "10" f y=(`echo hello` + x) +z="foo": "#, r#"x := "10" f y=(`echo hello` + x) +z="foo":"#, ); } #[test] fn parameter_default_multiple() { case( r#" x := "10" f y=(`echo hello` + x) +z=("foo" + "bar"): "#, r#"x := "10" f y=(`echo hello` + x) +z=("foo" + "bar"):"#, ); } #[test] fn concatenation_in_group() { case("x := ('0' + '1')", "x := ('0' + '1')"); } #[test] fn string_in_group() { case("x := ('0' )", "x := ('0')"); } #[rustfmt::skip] #[test] fn escaped_dos_newlines() { case("@spam:\r \t{ \\\r \t\tfiglet test; \\\r \t\tcargo build --color always 2>&1; \\\r \t\tcargo test --color always -- --color always 2>&1; \\\r \t} | less\r ", "@spam: { \\ \tfiglet test; \\ \tcargo build --color always 2>&1; \\ \tcargo test --color always -- --color always 2>&1; \\ } | less"); } } just-1.40.0/src/keyed.rs000064400000000000000000000012701046102023000131310ustar 00000000000000use super::*; pub(crate) trait Keyed<'key> { fn key(&self) -> &'key str; } impl<'key, T: Keyed<'key>> Keyed<'key> for Rc { fn key(&self) -> &'key str { self.as_ref().key() } } pub(crate) fn serialize<'src, S, K>(keyed: &K, serializer: S) -> Result where S: Serializer, K: Keyed<'src>, { serializer.serialize_str(keyed.key()) } #[rustversion::attr(since(1.83), allow(clippy::ref_option))] pub(crate) fn serialize_option<'src, S, K>( recipe: &Option, serializer: S, ) -> Result where S: Serializer, K: Keyed<'src>, { match recipe { None => serializer.serialize_none(), Some(keyed) => serialize(keyed, serializer), } } just-1.40.0/src/keyword.rs000064400000000000000000000020411046102023000135110ustar 00000000000000use super::*; #[derive(Debug, Eq, PartialEq, IntoStaticStr, Display, Copy, Clone, EnumString)] #[strum(serialize_all = "kebab_case")] pub(crate) enum Keyword { Alias, AllowDuplicateRecipes, AllowDuplicateVariables, Assert, DotenvFilename, DotenvLoad, DotenvPath, DotenvRequired, Else, Export, Fallback, False, If, IgnoreComments, Import, Mod, NoExitMessage, PositionalArguments, Quiet, ScriptInterpreter, Set, Shell, Tempdir, True, Unexport, Unstable, WindowsPowershell, WindowsShell, WorkingDirectory, X, } impl Keyword { pub(crate) fn from_lexeme(lexeme: &str) -> Option { lexeme.parse().ok() } pub(crate) fn lexeme(self) -> &'static str { self.into() } } impl<'a> PartialEq<&'a str> for Keyword { fn eq(&self, other: &&'a str) -> bool { self.lexeme() == *other } } #[cfg(test)] mod tests { use super::*; #[test] fn keyword_case() { assert_eq!(Keyword::X.lexeme(), "x"); assert_eq!(Keyword::IgnoreComments.lexeme(), "ignore-comments"); } } just-1.40.0/src/lexer.rs000064400000000000000000001360721046102023000131600ustar 00000000000000use {super::*, CompileErrorKind::*, TokenKind::*}; /// Just language lexer /// /// The lexer proceeds character-by-character, as opposed to using regular /// expressions to lex tokens or semi-tokens at a time. As a result, it is /// verbose and straightforward. Just used to have a regex-based lexer, which /// was slower and generally godawful. However, this should not be taken as a /// slight against regular expressions, the lexer was just idiosyncratically /// bad. pub(crate) struct Lexer<'src> { /// Char iterator chars: Chars<'src>, /// Indentation stack indentation: Vec<&'src str>, /// Interpolation token start stack interpolation_stack: Vec>, /// Next character to be lexed next: Option, /// Current open delimiters open_delimiters: Vec<(Delimiter, usize)>, /// Path to source file path: &'src Path, /// Inside recipe body recipe_body: bool, /// Next indent will start a recipe body recipe_body_pending: bool, /// Source text src: &'src str, /// Current token end token_end: Position, /// Current token start token_start: Position, /// Tokens tokens: Vec>, } impl<'src> Lexer<'src> { /// Lex `src` pub(crate) fn lex(path: &'src Path, src: &'src str) -> CompileResult<'src, Vec>> { Self::new(path, src).tokenize() } #[cfg(test)] pub(crate) fn test_lex(src: &'src str) -> CompileResult<'src, Vec>> { Self::new("justfile".as_ref(), src).tokenize() } /// Create a new Lexer to lex `src` fn new(path: &'src Path, src: &'src str) -> Self { let mut chars = src.chars(); let next = chars.next(); let start = Position { offset: 0, column: 0, line: 0, }; Self { indentation: vec![""], tokens: Vec::new(), token_start: start, token_end: start, recipe_body_pending: false, recipe_body: false, interpolation_stack: Vec::new(), open_delimiters: Vec::new(), chars, next, src, path, } } /// Advance over the character in `self.next`, updating `self.token_end` /// accordingly. fn advance(&mut self) -> CompileResult<'src> { match self.next { Some(c) => { let len_utf8 = c.len_utf8(); self.token_end.offset += len_utf8; self.token_end.column += len_utf8; if c == '\n' { self.token_end.column = 0; self.token_end.line += 1; } self.next = self.chars.next(); Ok(()) } None => Err(self.internal_error("Lexer advanced past end of text")), } } /// Advance over N characters. fn skip(&mut self, n: usize) -> CompileResult<'src> { for _ in 0..n { self.advance()?; } Ok(()) } /// Lexeme of in-progress token fn lexeme(&self) -> &'src str { &self.src[self.token_start.offset..self.token_end.offset] } /// Length of current token fn current_token_length(&self) -> usize { self.token_end.offset - self.token_start.offset } fn accepted(&mut self, c: char) -> CompileResult<'src, bool> { if self.next_is(c) { self.advance()?; Ok(true) } else { Ok(false) } } fn presume(&mut self, c: char) -> CompileResult<'src> { if !self.next_is(c) { return Err(self.internal_error(format!("Lexer presumed character `{c}`"))); } self.advance()?; Ok(()) } fn presume_str(&mut self, s: &str) -> CompileResult<'src> { for c in s.chars() { self.presume(c)?; } Ok(()) } /// Is next character c? fn next_is(&self, c: char) -> bool { self.next == Some(c) } /// Is next character ' ' or '\t'? fn next_is_whitespace(&self) -> bool { self.next_is(' ') || self.next_is('\t') } /// Un-lexed text fn rest(&self) -> &'src str { &self.src[self.token_end.offset..] } /// Check if unlexed text begins with prefix fn rest_starts_with(&self, prefix: &str) -> bool { self.rest().starts_with(prefix) } /// Does rest start with "\n" or "\r\n"? fn at_eol(&self) -> bool { self.next_is('\n') || self.rest_starts_with("\r\n") } /// Are we at end-of-file? fn at_eof(&self) -> bool { self.rest().is_empty() } /// Are we at end-of-line or end-of-file? fn at_eol_or_eof(&self) -> bool { self.at_eol() || self.at_eof() } /// Get current indentation fn indentation(&self) -> &'src str { self.indentation.last().unwrap() } /// Are we currently indented fn indented(&self) -> bool { !self.indentation().is_empty() } /// Create a new token with `kind` whose lexeme is between `self.token_start` /// and `self.token_end` fn token(&mut self, kind: TokenKind) { self.tokens.push(Token { offset: self.token_start.offset, column: self.token_start.column, line: self.token_start.line, src: self.src, length: self.token_end.offset - self.token_start.offset, kind, path: self.path, }); // Set `token_start` to point after the lexed token self.token_start = self.token_end; } /// Create an internal error with `message` fn internal_error(&self, message: impl Into) -> CompileError<'src> { // Use `self.token_end` as the location of the error let token = Token { src: self.src, offset: self.token_end.offset, line: self.token_end.line, column: self.token_end.column, length: 0, kind: Unspecified, path: self.path, }; CompileError::new( token, Internal { message: message.into(), }, ) } /// Create a compilation error with `kind` fn error(&self, kind: CompileErrorKind<'src>) -> CompileError<'src> { // Use the in-progress token span as the location of the error. // The width of the error site to highlight depends on the kind of error: let length = match kind { UnterminatedString | UnterminatedBacktick => { let Some(kind) = StringKind::from_token_start(self.lexeme()) else { return self.internal_error("Lexer::error: expected string or backtick token start"); }; kind.delimiter().len() } // highlight the full token _ => self.lexeme().len(), }; let token = Token { kind: Unspecified, src: self.src, offset: self.token_start.offset, line: self.token_start.line, column: self.token_start.column, length, path: self.path, }; CompileError::new(token, kind) } fn unterminated_interpolation_error(interpolation_start: Token<'src>) -> CompileError<'src> { CompileError::new(interpolation_start, UnterminatedInterpolation) } /// True if `text` could be an identifier pub(crate) fn is_identifier(text: &str) -> bool { if !text.chars().next().is_some_and(Self::is_identifier_start) { return false; } for c in text.chars().skip(1) { if !Self::is_identifier_continue(c) { return false; } } true } /// True if `c` can be the first character of an identifier pub(crate) fn is_identifier_start(c: char) -> bool { matches!(c, 'a'..='z' | 'A'..='Z' | '_') } /// True if `c` can be a continuation character of an identifier pub(crate) fn is_identifier_continue(c: char) -> bool { Self::is_identifier_start(c) || matches!(c, '0'..='9' | '-') } /// Consume the text and produce a series of tokens fn tokenize(mut self) -> CompileResult<'src, Vec>> { loop { if self.token_start.column == 0 { self.lex_line_start()?; } match self.next { Some(first) => { if let Some(&interpolation_start) = self.interpolation_stack.last() { self.lex_interpolation(interpolation_start, first)?; } else if self.recipe_body { self.lex_body()?; } else { self.lex_normal(first)?; }; } None => break, } } if let Some(&interpolation_start) = self.interpolation_stack.last() { return Err(Self::unterminated_interpolation_error(interpolation_start)); } while self.indented() { self.lex_dedent(); } self.token(Eof); assert_eq!(self.token_start.offset, self.token_end.offset); assert_eq!(self.token_start.offset, self.src.len()); assert_eq!(self.indentation.len(), 1); Ok(self.tokens) } /// Handle blank lines and indentation fn lex_line_start(&mut self) -> CompileResult<'src> { enum Indentation<'src> { // Line only contains whitespace Blank, // Indentation continues Continue, // Indentation decreases Decrease, // Indentation isn't consistent Inconsistent, // Indentation increases Increase, // Indentation mixes spaces and tabs Mixed { whitespace: &'src str }, } use Indentation::*; let nonblank_index = self .rest() .char_indices() .skip_while(|&(_, c)| c == ' ' || c == '\t') .map(|(i, _)| i) .next() .unwrap_or_else(|| self.rest().len()); let rest = &self.rest()[nonblank_index..]; let whitespace = &self.rest()[..nonblank_index]; let body_whitespace = &whitespace[..whitespace .char_indices() .take(self.indentation().chars().count()) .map(|(i, _c)| i) .next() .unwrap_or(0)]; let spaces = whitespace.chars().any(|c| c == ' '); let tabs = whitespace.chars().any(|c| c == '\t'); let body_spaces = body_whitespace.chars().any(|c| c == ' '); let body_tabs = body_whitespace.chars().any(|c| c == '\t'); #[allow(clippy::if_same_then_else)] let indentation = if rest.starts_with('\n') || rest.starts_with("\r\n") || rest.is_empty() { Blank } else if whitespace == self.indentation() { Continue } else if self.indentation.contains(&whitespace) { Decrease } else if self.recipe_body && whitespace.starts_with(self.indentation()) { Continue } else if self.recipe_body && body_spaces && body_tabs { Mixed { whitespace: body_whitespace, } } else if !self.recipe_body && spaces && tabs { Mixed { whitespace } } else if whitespace.len() < self.indentation().len() { Inconsistent } else if self.recipe_body && body_whitespace.len() >= self.indentation().len() && !body_whitespace.starts_with(self.indentation()) { Inconsistent } else if whitespace.len() >= self.indentation().len() && !whitespace.starts_with(self.indentation()) { Inconsistent } else { Increase }; match indentation { Blank => { if !whitespace.is_empty() { while self.next_is_whitespace() { self.advance()?; } self.token(Whitespace); }; Ok(()) } Continue => { if !self.indentation().is_empty() { for _ in self.indentation().chars() { self.advance()?; } self.token(Whitespace); } Ok(()) } Decrease => { while self.indentation() != whitespace { self.lex_dedent(); } if !whitespace.is_empty() { while self.next_is_whitespace() { self.advance()?; } self.token(Whitespace); } Ok(()) } Mixed { whitespace } => { for _ in whitespace.chars() { self.advance()?; } Err(self.error(MixedLeadingWhitespace { whitespace })) } Inconsistent => { for _ in whitespace.chars() { self.advance()?; } Err(self.error(InconsistentLeadingWhitespace { expected: self.indentation(), found: whitespace, })) } Increase => { while self.next_is_whitespace() { self.advance()?; } if self.open_delimiters() { self.token(Whitespace); } else { let indentation = self.lexeme(); self.indentation.push(indentation); self.token(Indent); if self.recipe_body_pending { self.recipe_body = true; } } Ok(()) } } } /// Lex token beginning with `start` outside of a recipe body fn lex_normal(&mut self, start: char) -> CompileResult<'src> { match start { ' ' | '\t' => self.lex_whitespace(), '!' if self.rest().starts_with("!include") => Err(self.error(Include)), '!' => self.lex_choices('!', &[('=', BangEquals), ('~', BangTilde)], None), '#' => self.lex_comment(), '$' => self.lex_single(Dollar), '&' => self.lex_digraph('&', '&', AmpersandAmpersand), '(' => self.lex_delimiter(ParenL), ')' => self.lex_delimiter(ParenR), '*' => self.lex_single(Asterisk), '+' => self.lex_single(Plus), ',' => self.lex_single(Comma), '/' => self.lex_single(Slash), ':' => self.lex_colon(), '=' => self.lex_choices( '=', &[('=', EqualsEquals), ('~', EqualsTilde)], Some(Equals), ), '?' => self.lex_single(QuestionMark), '@' => self.lex_single(At), '[' => self.lex_delimiter(BracketL), '\\' => self.lex_escape(), '\n' | '\r' => self.lex_eol(), '\u{feff}' => self.lex_single(ByteOrderMark), ']' => self.lex_delimiter(BracketR), '`' | '"' | '\'' => self.lex_string(), '{' => self.lex_delimiter(BraceL), '|' => self.lex_digraph('|', '|', BarBar), '}' => self.lex_delimiter(BraceR), _ if Self::is_identifier_start(start) => self.lex_identifier(), _ => { self.advance()?; Err(self.error(UnknownStartOfToken { start })) } } } /// Lex token beginning with `start` inside an interpolation fn lex_interpolation( &mut self, interpolation_start: Token<'src>, start: char, ) -> CompileResult<'src> { if self.rest_starts_with("}}") { // end current interpolation if self.interpolation_stack.pop().is_none() { self.advance()?; self.advance()?; return Err(self.internal_error( "Lexer::lex_interpolation found `}}` but was called with empty interpolation stack.", )); } // Emit interpolation end token self.lex_double(InterpolationEnd) } else if self.at_eol_or_eof() { // Return unterminated interpolation error that highlights the opening // {{ Err(Self::unterminated_interpolation_error(interpolation_start)) } else { // Otherwise lex as per normal self.lex_normal(start) } } /// Lex token while in recipe body fn lex_body(&mut self) -> CompileResult<'src> { enum Terminator { EndOfFile, Interpolation, Newline, NewlineCarriageReturn, } use Terminator::*; let terminator = loop { if self.rest_starts_with("{{{{") { self.skip(4)?; continue; } if self.rest_starts_with("\n") { break Newline; } if self.rest_starts_with("\r\n") { break NewlineCarriageReturn; } if self.rest_starts_with("{{") { break Interpolation; } if self.at_eof() { break EndOfFile; } self.advance()?; }; // emit text token containing text so far if self.current_token_length() > 0 { self.token(Text); } match terminator { Newline => self.lex_single(Eol), NewlineCarriageReturn => self.lex_double(Eol), Interpolation => { self.lex_double(InterpolationStart)?; self .interpolation_stack .push(self.tokens[self.tokens.len() - 1]); Ok(()) } EndOfFile => Ok(()), } } fn lex_dedent(&mut self) { assert_eq!(self.current_token_length(), 0); self.token(Dedent); self.indentation.pop(); self.recipe_body_pending = false; self.recipe_body = false; } /// Lex a single-character token fn lex_single(&mut self, kind: TokenKind) -> CompileResult<'src> { self.advance()?; self.token(kind); Ok(()) } /// Lex a double-character token fn lex_double(&mut self, kind: TokenKind) -> CompileResult<'src> { self.advance()?; self.advance()?; self.token(kind); Ok(()) } /// Lex a double-character token of kind `then` if the second character of /// that token would be `second`, otherwise lex a single-character token of /// kind `otherwise` fn lex_choices( &mut self, first: char, choices: &[(char, TokenKind)], otherwise: Option, ) -> CompileResult<'src> { self.presume(first)?; for (second, then) in choices { if self.accepted(*second)? { self.token(*then); return Ok(()); } } if let Some(token) = otherwise { self.token(token); } else { // Emit an unspecified token to consume the current character, self.token(Unspecified); let expected = choices.iter().map(|choice| choice.0).collect(); if self.at_eof() { return Err(self.error(UnexpectedEndOfToken { expected })); } // …and advance past another character, self.advance()?; // …so that the error we produce highlights the unexpected character. return Err(self.error(UnexpectedCharacter { expected })); } Ok(()) } /// Lex an opening or closing delimiter fn lex_delimiter(&mut self, kind: TokenKind) -> CompileResult<'src> { use Delimiter::*; match kind { BraceL => self.open_delimiter(Brace), BraceR => self.close_delimiter(Brace)?, BracketL => self.open_delimiter(Bracket), BracketR => self.close_delimiter(Bracket)?, ParenL => self.open_delimiter(Paren), ParenR => self.close_delimiter(Paren)?, _ => { return Err(self.internal_error(format!( "Lexer::lex_delimiter called with non-delimiter token: `{kind}`", ))) } } // Emit the delimiter token self.lex_single(kind) } /// Push a delimiter onto the open delimiter stack fn open_delimiter(&mut self, delimiter: Delimiter) { self .open_delimiters .push((delimiter, self.token_start.line)); } /// Pop a delimiter from the open delimiter stack and error if incorrect type fn close_delimiter(&mut self, close: Delimiter) -> CompileResult<'src> { match self.open_delimiters.pop() { Some((open, _)) if open == close => Ok(()), Some((open, open_line)) => Err(self.error(MismatchedClosingDelimiter { open, close, open_line, })), None => Err(self.error(UnexpectedClosingDelimiter { close })), } } /// Return true if there are any unclosed delimiters fn open_delimiters(&self) -> bool { !self.open_delimiters.is_empty() } /// Lex a two-character digraph fn lex_digraph(&mut self, left: char, right: char, token: TokenKind) -> CompileResult<'src> { self.presume(left)?; if self.accepted(right)? { self.token(token); Ok(()) } else { // Emit an unspecified token to consume the current character, self.token(Unspecified); if self.at_eof() { return Err(self.error(UnexpectedEndOfToken { expected: vec![right], })); } // …and advance past another character, self.advance()?; // …so that the error we produce highlights the unexpected character. Err(self.error(UnexpectedCharacter { expected: vec![right], })) } } /// Lex a token starting with ':' fn lex_colon(&mut self) -> CompileResult<'src> { self.presume(':')?; if self.accepted('=')? { self.token(ColonEquals); } else if self.accepted(':')? { self.token(ColonColon); } else { self.token(Colon); self.recipe_body_pending = true; } Ok(()) } /// Lex an token starting with '\' escape fn lex_escape(&mut self) -> CompileResult<'src> { self.presume('\\')?; // Treat newline escaped with \ as whitespace if self.accepted('\n')? { while self.next_is_whitespace() { self.advance()?; } self.token(Whitespace); } else if self.accepted('\r')? { if !self.accepted('\n')? { return Err(self.error(UnpairedCarriageReturn)); } while self.next_is_whitespace() { self.advance()?; } self.token(Whitespace); } else if let Some(character) = self.next { return Err(self.error(InvalidEscapeSequence { character })); } Ok(()) } /// Lex a carriage return and line feed fn lex_eol(&mut self) -> CompileResult<'src> { if self.accepted('\r')? { if !self.accepted('\n')? { return Err(self.error(UnpairedCarriageReturn)); } } else { self.presume('\n')?; } // Emit an eol if there are no open delimiters, otherwise emit a whitespace // token. if self.open_delimiters() { self.token(Whitespace); } else { self.token(Eol); } Ok(()) } /// Lex name: [a-zA-Z_][a-zA-Z0-9_]* fn lex_identifier(&mut self) -> CompileResult<'src> { self.advance()?; while let Some(c) = self.next { if !Self::is_identifier_continue(c) { break; } self.advance()?; } self.token(Identifier); Ok(()) } /// Lex comment: #[^\r\n] fn lex_comment(&mut self) -> CompileResult<'src> { self.presume('#')?; while !self.at_eol_or_eof() { self.advance()?; } self.token(Comment); Ok(()) } /// Lex whitespace: [ \t]+ fn lex_whitespace(&mut self) -> CompileResult<'src> { while self.next_is_whitespace() { self.advance()?; } self.token(Whitespace); Ok(()) } /// Lex a backtick, cooked string, or raw string. /// /// Backtick: ``[^`]*`` /// Cooked string: "[^"]*" # also processes escape sequences /// Raw string: '[^']*' fn lex_string(&mut self) -> CompileResult<'src> { let Some(kind) = StringKind::from_token_start(self.rest()) else { self.advance()?; return Err(self.internal_error("Lexer::lex_string: invalid string start")); }; self.presume_str(kind.delimiter())?; let mut escape = false; loop { if self.next.is_none() { return Err(self.error(kind.unterminated_error_kind())); } else if kind.processes_escape_sequences() && self.next_is('\\') && !escape { escape = true; } else if self.rest_starts_with(kind.delimiter()) && !escape { break; } else { escape = false; } self.advance()?; } self.presume_str(kind.delimiter())?; self.token(kind.token_kind()); Ok(()) } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; macro_rules! test { { name: $name:ident, text: $text:expr, tokens: ($($kind:ident $(: $lexeme:literal)?),* $(,)?)$(,)? } => { #[test] fn $name() { let kinds: &[TokenKind] = &[$($kind,)* Eof]; let lexemes: &[&str] = &[$(lexeme!($kind $(, $lexeme)?),)* ""]; test($text, true, kinds, lexemes); } }; { name: $name:ident, text: $text:expr, tokens: ($($kind:ident $(: $lexeme:literal)?),* $(,)?)$(,)? unindent: $unindent:expr, } => { #[test] fn $name() { let kinds: &[TokenKind] = &[$($kind,)* Eof]; let lexemes: &[&str] = &[$(lexeme!($kind $(, $lexeme)?),)* ""]; test($text, $unindent, kinds, lexemes); } } } macro_rules! lexeme { { $kind:ident, $lexeme:literal } => { $lexeme }; { $kind:ident } => { default_lexeme($kind) } } fn test(text: &str, unindent_text: bool, want_kinds: &[TokenKind], want_lexemes: &[&str]) { let text = if unindent_text { unindent(text) } else { text.to_owned() }; let have = Lexer::test_lex(&text).unwrap(); let have_kinds = have .iter() .map(|token| token.kind) .collect::>(); let have_lexemes = have.iter().map(Token::lexeme).collect::>(); assert_eq!(have_kinds, want_kinds, "Token kind mismatch"); assert_eq!(have_lexemes, want_lexemes, "Token lexeme mismatch"); let mut roundtrip = String::new(); for lexeme in have_lexemes { roundtrip.push_str(lexeme); } assert_eq!(roundtrip, text, "Roundtrip mismatch"); let mut offset = 0; let mut line = 0; let mut column = 0; for token in have { assert_eq!(token.offset, offset); assert_eq!(token.line, line); assert_eq!(token.lexeme().len(), token.length); assert_eq!(token.column, column); for c in token.lexeme().chars() { if c == '\n' { line += 1; column = 0; } else { column += c.len_utf8(); } } offset += token.length; } } fn default_lexeme(kind: TokenKind) -> &'static str { match kind { // Fixed lexemes AmpersandAmpersand => "&&", Asterisk => "*", At => "@", BangEquals => "!=", BangTilde => "!~", BarBar => "||", BraceL => "{", BraceR => "}", BracketL => "[", BracketR => "]", ByteOrderMark => "\u{feff}", Colon => ":", ColonColon => "::", ColonEquals => ":=", Comma => ",", Dollar => "$", Eol => "\n", Equals => "=", EqualsEquals => "==", EqualsTilde => "=~", Indent => " ", InterpolationEnd => "}}", InterpolationStart => "{{", ParenL => "(", ParenR => ")", Plus => "+", QuestionMark => "?", Slash => "/", Whitespace => " ", // Empty lexemes Dedent | Eof => "", // Variable lexemes Text | StringToken | Backtick | Identifier | Comment | Unspecified => { panic!("Token {kind:?} has no default lexeme") } } } macro_rules! error { ( name: $name:ident, input: $input:expr, offset: $offset:expr, line: $line:expr, column: $column:expr, width: $width:expr, kind: $kind:expr, ) => { #[test] fn $name() { error($input, $offset, $line, $column, $width, $kind); } }; } fn error( src: &str, offset: usize, line: usize, column: usize, length: usize, kind: CompileErrorKind, ) { match Lexer::test_lex(src) { Ok(_) => panic!("Lexing succeeded but expected"), Err(have) => { let want = CompileError { token: Token { kind: have.token.kind, src, offset, line, column, length, path: "justfile".as_ref(), }, kind: kind.into(), }; assert_eq!(have, want); } } } test! { name: name_new, text: "foo", tokens: (Identifier:"foo"), } test! { name: comment, text: "# hello", tokens: (Comment:"# hello"), } test! { name: backtick, text: "`echo`", tokens: (Backtick:"`echo`"), } test! { name: backtick_multi_line, text: "`echo\necho`", tokens: (Backtick:"`echo\necho`"), } test! { name: raw_string, text: "'hello'", tokens: (StringToken:"'hello'"), } test! { name: raw_string_multi_line, text: "'hello\ngoodbye'", tokens: (StringToken:"'hello\ngoodbye'"), } test! { name: cooked_string, text: "\"hello\"", tokens: (StringToken:"\"hello\""), } test! { name: cooked_string_multi_line, text: "\"hello\ngoodbye\"", tokens: (StringToken:"\"hello\ngoodbye\""), } test! { name: cooked_multiline_string, text: "\"\"\"hello\ngoodbye\"\"\"", tokens: (StringToken:"\"\"\"hello\ngoodbye\"\"\""), } test! { name: ampersand_ampersand, text: "&&", tokens: (AmpersandAmpersand), } test! { name: equals, text: "=", tokens: (Equals), } test! { name: equals_equals, text: "==", tokens: (EqualsEquals), } test! { name: bang_equals, text: "!=", tokens: (BangEquals), } test! { name: brace_l, text: "{", tokens: (BraceL), } test! { name: brace_r, text: "{}", tokens: (BraceL, BraceR), } test! { name: brace_lll, text: "{{{", tokens: (BraceL, BraceL, BraceL), } test! { name: brace_rrr, text: "{{{}}}", tokens: (BraceL, BraceL, BraceL, BraceR, BraceR, BraceR), } test! { name: dollar, text: "$", tokens: (Dollar), } test! { name: export_concatenation, text: "export foo = 'foo' + 'bar'", tokens: ( Identifier:"export", Whitespace, Identifier:"foo", Whitespace, Equals, Whitespace, StringToken:"'foo'", Whitespace, Plus, Whitespace, StringToken:"'bar'", ) } test! { name: export_complex, text: "export foo = ('foo' + 'bar') + `baz`", tokens: ( Identifier:"export", Whitespace, Identifier:"foo", Whitespace, Equals, Whitespace, ParenL, StringToken:"'foo'", Whitespace, Plus, Whitespace, StringToken:"'bar'", ParenR, Whitespace, Plus, Whitespace, Backtick:"`baz`", ), } test! { name: eol_linefeed, text: "\n", tokens: (Eol), unindent: false, } test! { name: eol_carriage_return_linefeed, text: "\r\n", tokens: (Eol:"\r\n"), unindent: false, } test! { name: indented_line, text: "foo:\n a", tokens: (Identifier:"foo", Colon, Eol, Indent:" ", Text:"a", Dedent), } test! { name: indented_normal, text: " a b c ", tokens: ( Identifier:"a", Eol, Indent:" ", Identifier:"b", Eol, Whitespace:" ", Identifier:"c", Eol, Dedent, ), } test! { name: indented_normal_nonempty_blank, text: "a\n b\n\t\t\n c\n", tokens: ( Identifier:"a", Eol, Indent:" ", Identifier:"b", Eol, Whitespace:"\t\t", Eol, Whitespace:" ", Identifier:"c", Eol, Dedent, ), unindent: false, } test! { name: indented_normal_multiple, text: " a b c ", tokens: ( Identifier:"a", Eol, Indent:" ", Identifier:"b", Eol, Indent:" ", Identifier:"c", Eol, Dedent, Dedent, ), } test! { name: indent_indent_dedent_indent, text: " a b c d e ", tokens: ( Identifier:"a", Eol, Indent:" ", Identifier:"b", Eol, Indent:" ", Identifier:"c", Eol, Dedent, Whitespace:" ", Identifier:"d", Eol, Indent:" ", Identifier:"e", Eol, Dedent, Dedent, ), } test! { name: indent_recipe_dedent_indent, text: " a b: c d e ", tokens: ( Identifier:"a", Eol, Indent:" ", Identifier:"b", Colon, Eol, Indent:" ", Text:"c", Eol, Dedent, Whitespace:" ", Identifier:"d", Eol, Indent:" ", Identifier:"e", Eol, Dedent, Dedent, ), } test! { name: indented_block, text: " foo: a b c ", tokens: ( Identifier:"foo", Colon, Eol, Indent, Text:"a", Eol, Whitespace:" ", Text:"b", Eol, Whitespace:" ", Text:"c", Eol, Dedent, ) } test! { name: brace_escape, text: " foo: {{{{ ", tokens: ( Identifier:"foo", Colon, Eol, Indent, Text:"{{{{", Eol, Dedent, ) } test! { name: indented_block_followed_by_item, text: " foo: a b: ", tokens: ( Identifier:"foo", Colon, Eol, Indent, Text:"a", Eol, Dedent, Identifier:"b", Colon, Eol, ) } test! { name: indented_block_followed_by_blank, text: " foo: a b: ", tokens: ( Identifier:"foo", Colon, Eol, Indent:" ", Text:"a", Eol, Eol, Dedent, Identifier:"b", Colon, Eol, ), } test! { name: indented_line_containing_unpaired_carriage_return, text: "foo:\n \r \n", tokens: ( Identifier:"foo", Colon, Eol, Indent:" ", Text:"\r ", Eol, Dedent, ), unindent: false, } test! { name: indented_blocks, text: " b: a @mv a b a: @touch F @touch a d: c @rm c c: b @mv b c ", tokens: ( Identifier:"b", Colon, Whitespace, Identifier:"a", Eol, Indent, Text:"@mv a b", Eol, Eol, Dedent, Identifier:"a", Colon, Eol, Indent, Text:"@touch F", Eol, Whitespace:" ", Text:"@touch a", Eol, Eol, Dedent, Identifier:"d", Colon, Whitespace, Identifier:"c", Eol, Indent, Text:"@rm c", Eol, Eol, Dedent, Identifier:"c", Colon, Whitespace, Identifier:"b", Eol, Indent, Text:"@mv b c", Eol, Dedent ), } test! { name: interpolation_empty, text: "hello:\n echo {{}}", tokens: ( Identifier:"hello", Colon, Eol, Indent:" ", Text:"echo ", InterpolationStart, InterpolationEnd, Dedent, ), } test! { name: interpolation_expression, text: "hello:\n echo {{`echo hello` + `echo goodbye`}}", tokens: ( Identifier:"hello", Colon, Eol, Indent:" ", Text:"echo ", InterpolationStart, Backtick:"`echo hello`", Whitespace, Plus, Whitespace, Backtick:"`echo goodbye`", InterpolationEnd, Dedent, ), } test! { name: interpolation_raw_multiline_string, text: "hello:\n echo {{'\n'}}", tokens: ( Identifier:"hello", Colon, Eol, Indent:" ", Text:"echo ", InterpolationStart, StringToken:"'\n'", InterpolationEnd, Dedent, ), } test! { name: tokenize_names, text: " foo bar-bob b-bob_asdfAAAA test123 ", tokens: ( Identifier:"foo", Eol, Identifier:"bar-bob", Eol, Identifier:"b-bob_asdfAAAA", Eol, Identifier:"test123", Eol, ), } test! { name: tokenize_indented_line, text: "foo:\n a", tokens: ( Identifier:"foo", Colon, Eol, Indent:" ", Text:"a", Dedent, ), } test! { name: tokenize_indented_block, text: " foo: a b c ", tokens: ( Identifier:"foo", Colon, Eol, Indent, Text:"a", Eol, Whitespace:" ", Text:"b", Eol, Whitespace:" ", Text:"c", Eol, Dedent, ), } test! { name: tokenize_strings, text: r#"a = "'a'" + '"b"' + "'c'" + '"d"'#echo hello"#, tokens: ( Identifier:"a", Whitespace, Equals, Whitespace, StringToken:"\"'a'\"", Whitespace, Plus, Whitespace, StringToken:"'\"b\"'", Whitespace, Plus, Whitespace, StringToken:"\"'c'\"", Whitespace, Plus, Whitespace, StringToken:"'\"d\"'", Comment:"#echo hello", ) } test! { name: tokenize_recipe_interpolation_eol, text: " foo: # some comment {{hello}} ", tokens: ( Identifier:"foo", Colon, Whitespace, Comment:"# some comment", Eol, Indent:" ", InterpolationStart, Identifier:"hello", InterpolationEnd, Eol, Dedent ), } test! { name: tokenize_recipe_interpolation_eof, text: "foo: # more comments {{hello}} # another comment ", tokens: ( Identifier:"foo", Colon, Whitespace, Comment:"# more comments", Eol, Indent:" ", InterpolationStart, Identifier:"hello", InterpolationEnd, Eol, Dedent, Comment:"# another comment", Eol, ), } test! { name: tokenize_recipe_complex_interpolation_expression, text: "foo: #lol\n {{a + b + \"z\" + blarg}}", tokens: ( Identifier:"foo", Colon, Whitespace:" ", Comment:"#lol", Eol, Indent:" ", InterpolationStart, Identifier:"a", Whitespace, Plus, Whitespace, Identifier:"b", Whitespace, Plus, Whitespace, StringToken:"\"z\"", Whitespace, Plus, Whitespace, Identifier:"blarg", InterpolationEnd, Dedent, ), } test! { name: tokenize_recipe_multiple_interpolations, text: "foo:,#ok\n {{a}}0{{b}}1{{c}}", tokens: ( Identifier:"foo", Colon, Comma, Comment:"#ok", Eol, Indent:" ", InterpolationStart, Identifier:"a", InterpolationEnd, Text:"0", InterpolationStart, Identifier:"b", InterpolationEnd, Text:"1", InterpolationStart, Identifier:"c", InterpolationEnd, Dedent, ), } test! { name: tokenize_junk, text: " bob hello blah blah blah : a b c #whatever ", tokens: ( Identifier:"bob", Eol, Eol, Identifier:"hello", Whitespace, Identifier:"blah", Whitespace, Identifier:"blah", Whitespace, Identifier:"blah", Whitespace, Colon, Whitespace, Identifier:"a", Whitespace, Identifier:"b", Whitespace, Identifier:"c", Whitespace, Comment:"#whatever", Eol, ) } test! { name: tokenize_empty_lines, text: " # this does something hello: asdf bsdf csdf dsdf # whatever # yolo ", tokens: ( Eol, Comment:"# this does something", Eol, Identifier:"hello", Colon, Eol, Indent, Text:"asdf", Eol, Whitespace:" ", Text:"bsdf", Eol, Eol, Whitespace:" ", Text:"csdf", Eol, Eol, Whitespace:" ", Text:"dsdf # whatever", Eol, Eol, Dedent, Comment:"# yolo", Eol, ), } test! { name: tokenize_comment_before_variable, text: " # A='1' echo: echo {{A}} ", tokens: ( Comment:"#", Eol, Identifier:"A", Equals, StringToken:"'1'", Eol, Identifier:"echo", Colon, Eol, Indent, Text:"echo ", InterpolationStart, Identifier:"A", InterpolationEnd, Eol, Dedent, ), } test! { name: tokenize_interpolation_backticks, text: "hello:\n echo {{`echo hello` + `echo goodbye`}}", tokens: ( Identifier:"hello", Colon, Eol, Indent:" ", Text:"echo ", InterpolationStart, Backtick:"`echo hello`", Whitespace, Plus, Whitespace, Backtick:"`echo goodbye`", InterpolationEnd, Dedent ), } test! { name: tokenize_empty_interpolation, text: "hello:\n echo {{}}", tokens: ( Identifier:"hello", Colon, Eol, Indent:" ", Text:"echo ", InterpolationStart, InterpolationEnd, Dedent, ), } test! { name: tokenize_assignment_backticks, text: "a = `echo hello` + `echo goodbye`", tokens: ( Identifier:"a", Whitespace, Equals, Whitespace, Backtick:"`echo hello`", Whitespace, Plus, Whitespace, Backtick:"`echo goodbye`", ), } test! { name: tokenize_multiple, text: " hello: a b c d # hello bob: frank \t ", tokens: ( Eol, Identifier:"hello", Colon, Eol, Indent, Text:"a", Eol, Whitespace:" ", Text:"b", Eol, Eol, Whitespace:" ", Text:"c", Eol, Eol, Whitespace:" ", Text:"d", Eol, Eol, Dedent, Comment:"# hello", Eol, Identifier:"bob", Colon, Eol, Indent:" ", Text:"frank", Eol, Eol, Dedent, ), } test! { name: tokenize_comment, text: "a:=#", tokens: ( Identifier:"a", ColonEquals, Comment:"#", ), } test! { name: tokenize_comment_with_bang, text: "a:=#foo!", tokens: ( Identifier:"a", ColonEquals, Comment:"#foo!", ), } test! { name: tokenize_order, text: " b: a @mv a b a: @touch F @touch a d: c @rm c c: b @mv b c ", tokens: ( Identifier:"b", Colon, Whitespace, Identifier:"a", Eol, Indent, Text:"@mv a b", Eol, Eol, Dedent, Identifier:"a", Colon, Eol, Indent, Text:"@touch F", Eol, Whitespace:" ", Text:"@touch a", Eol, Eol, Dedent, Identifier:"d", Colon, Whitespace, Identifier:"c", Eol, Indent, Text:"@rm c", Eol, Eol, Dedent, Identifier:"c", Colon, Whitespace, Identifier:"b", Eol, Indent, Text:"@mv b c", Eol, Dedent, ), } test! { name: tokenize_parens, text: "((())) ()abc(+", tokens: ( ParenL, ParenL, ParenL, ParenR, ParenR, ParenR, Whitespace, ParenL, ParenR, Identifier:"abc", ParenL, Plus, ), } test! { name: crlf_newline, text: "#\r\n#asdf\r\n", tokens: ( Comment:"#", Eol:"\r\n", Comment:"#asdf", Eol:"\r\n", ), } test! { name: multiple_recipes, text: "a:\n foo\nb:", tokens: ( Identifier:"a", Colon, Eol, Indent:" ", Text:"foo", Eol, Dedent, Identifier:"b", Colon, ), } test! { name: brackets, text: "[][]", tokens: (BracketL, BracketR, BracketL, BracketR), } test! { name: open_delimiter_eol, text: "[\n](\n){\n}", tokens: ( BracketL, Whitespace:"\n", BracketR, ParenL, Whitespace:"\n", ParenR, BraceL, Whitespace:"\n", BraceR ), } error! { name: tokenize_space_then_tab, input: "a: 0 1 \t2 ", offset: 9, line: 3, column: 0, width: 1, kind: InconsistentLeadingWhitespace{expected: " ", found: "\t"}, } error! { name: tokenize_tabs_then_tab_space, input: "a: \t\t0 \t\t 1 \t 2 ", offset: 12, line: 3, column: 0, width: 3, kind: InconsistentLeadingWhitespace{expected: "\t\t", found: "\t "}, } error! { name: tokenize_unknown, input: "%", offset: 0, line: 0, column: 0, width: 1, kind: UnknownStartOfToken { start: '%'}, } error! { name: unterminated_string_with_escapes, input: r#"a = "\n\t\r\"\\"#, offset: 4, line: 0, column: 4, width: 1, kind: UnterminatedString, } error! { name: unterminated_raw_string, input: "r a='asdf", offset: 4, line: 0, column: 4, width: 1, kind: UnterminatedString, } error! { name: unterminated_interpolation, input: "foo:\n echo {{ ", offset: 11, line: 1, column: 6, width: 2, kind: UnterminatedInterpolation, } error! { name: unterminated_backtick, input: "`echo", offset: 0, line: 0, column: 0, width: 1, kind: UnterminatedBacktick, } error! { name: unpaired_carriage_return, input: "foo\rbar", offset: 3, line: 0, column: 3, width: 1, kind: UnpairedCarriageReturn, } error! { name: invalid_name_start_dash, input: "-foo", offset: 0, line: 0, column: 0, width: 1, kind: UnknownStartOfToken{ start: '-'}, } error! { name: invalid_name_start_digit, input: "0foo", offset: 0, line: 0, column: 0, width: 1, kind: UnknownStartOfToken { start: '0' }, } error! { name: unterminated_string, input: r#"a = ""#, offset: 4, line: 0, column: 4, width: 1, kind: UnterminatedString, } error! { name: mixed_leading_whitespace_recipe, input: "a:\n\t echo hello", offset: 3, line: 1, column: 0, width: 2, kind: MixedLeadingWhitespace{whitespace: "\t "}, } error! { name: mixed_leading_whitespace_normal, input: "a\n\t echo hello", offset: 2, line: 1, column: 0, width: 2, kind: MixedLeadingWhitespace{whitespace: "\t "}, } error! { name: mixed_leading_whitespace_indent, input: "a\n foo\n \tbar", offset: 7, line: 2, column: 0, width: 2, kind: MixedLeadingWhitespace{whitespace: " \t"}, } error! { name: bad_dedent, input: "a\n foo\n bar\n baz", offset: 14, line: 3, column: 0, width: 2, kind: InconsistentLeadingWhitespace{expected: " ", found: " "}, } error! { name: unclosed_interpolation_delimiter, input: "a:\n echo {{ foo", offset: 9, line: 1, column: 6, width: 2, kind: UnterminatedInterpolation, } error! { name: unexpected_character_after_at, input: "@%", offset: 1, line: 0, column: 1, width: 1, kind: UnknownStartOfToken { start: '%'}, } error! { name: mismatched_closing_brace, input: "(]", offset: 1, line: 0, column: 1, width: 0, kind: MismatchedClosingDelimiter { open: Delimiter::Paren, close: Delimiter::Bracket, open_line: 0, }, } error! { name: ampersand_eof, input: "&", offset: 1, line: 0, column: 1, width: 0, kind: UnexpectedEndOfToken { expected: vec!['&'], }, } error! { name: ampersand_unexpected, input: "&%", offset: 1, line: 0, column: 1, width: 1, kind: UnexpectedCharacter { expected: vec!['&'], }, } error! { name: bang_eof, input: "!", offset: 1, line: 0, column: 1, width: 0, kind: UnexpectedEndOfToken { expected: vec!['=', '~'], }, } #[test] fn presume_error() { let compile_error = Lexer::new("justfile".as_ref(), "!") .presume('-') .unwrap_err(); assert_matches!( compile_error.token, Token { offset: 0, line: 0, column: 0, length: 0, src: "!", kind: Unspecified, path: _, } ); assert_matches!(&*compile_error.kind, Internal { message } if message == "Lexer presumed character `-`" ); assert_eq!( Error::Compile { compile_error } .color_display(Color::never()) .to_string(), "error: Internal error, this may indicate a bug in just: Lexer presumed character `-` consider filing an issue: https://github.com/casey/just/issues/new ——▶ justfile:1:1 │ 1 │ ! │ ^" ); } } just-1.40.0/src/lib.rs000064400000000000000000000140001046102023000125710ustar 00000000000000//! `just` is primarily used as a command-line binary, but does provide a //! limited public library interface. //! //! Please keep in mind that there are no semantic version guarantees for the //! library interface. It may break or change at any time. pub(crate) use { crate::{ alias::Alias, alias_style::AliasStyle, analyzer::Analyzer, argument_parser::ArgumentParser, assignment::Assignment, assignment_resolver::AssignmentResolver, ast::Ast, attribute::{Attribute, AttributeDiscriminant}, attribute_set::AttributeSet, binding::Binding, color::Color, color_display::ColorDisplay, command_color::CommandColor, command_ext::CommandExt, compilation::Compilation, compile_error::CompileError, compile_error_kind::CompileErrorKind, compiler::Compiler, condition::Condition, conditional_operator::ConditionalOperator, config::Config, config_error::ConfigError, constants::constants, count::Count, delimiter::Delimiter, dependency::Dependency, dump_format::DumpFormat, enclosure::Enclosure, error::Error, evaluator::Evaluator, execution_context::ExecutionContext, executor::Executor, expression::Expression, fragment::Fragment, function::Function, interpreter::Interpreter, interrupt_guard::InterruptGuard, interrupt_handler::InterruptHandler, item::Item, justfile::Justfile, keyed::Keyed, keyword::Keyword, lexer::Lexer, line::Line, list::List, load_dotenv::load_dotenv, loader::Loader, module_path::ModulePath, name::Name, namepath::Namepath, ordinal::Ordinal, output::output, output_error::OutputError, parameter::Parameter, parameter_kind::ParameterKind, parser::Parser, platform::Platform, platform_interface::PlatformInterface, position::Position, positional::Positional, ran::Ran, range_ext::RangeExt, recipe::Recipe, recipe_resolver::RecipeResolver, recipe_signature::RecipeSignature, scope::Scope, search::Search, search_config::SearchConfig, search_error::SearchError, set::Set, setting::Setting, settings::Settings, shebang::Shebang, show_whitespace::ShowWhitespace, source::Source, string_delimiter::StringDelimiter, string_kind::StringKind, string_literal::StringLiteral, subcommand::Subcommand, suggestion::Suggestion, table::Table, thunk::Thunk, token::Token, token_kind::TokenKind, unresolved_dependency::UnresolvedDependency, unresolved_recipe::UnresolvedRecipe, unstable_feature::UnstableFeature, use_color::UseColor, variables::Variables, verbosity::Verbosity, warning::Warning, which::which, }, camino::Utf8Path, clap::ValueEnum, derive_where::derive_where, edit_distance::edit_distance, lexiclean::Lexiclean, libc::EXIT_FAILURE, once_cell::sync::Lazy, rand::seq::IndexedRandom, regex::Regex, serde::{ ser::{SerializeMap, SerializeSeq}, Deserialize, Serialize, Serializer, }, snafu::{ResultExt, Snafu}, std::{ borrow::Cow, cmp, collections::{BTreeMap, BTreeSet, HashMap, HashSet}, env, ffi::OsString, fmt::{self, Debug, Display, Formatter}, fs, io::{self, Read, Seek, Write}, iter::{self, FromIterator}, mem, ops::Deref, ops::{Index, Range, RangeInclusive}, path::{self, Path, PathBuf}, process::{self, Command, ExitStatus, Stdio}, rc::Rc, str::{self, Chars}, sync::{Mutex, MutexGuard, OnceLock}, vec, }, strum::{Display, EnumDiscriminants, EnumString, IntoStaticStr}, tempfile::tempfile, typed_arena::Arena, unicode_width::{UnicodeWidthChar, UnicodeWidthStr}, }; #[cfg(test)] pub(crate) use { crate::{node::Node, tree::Tree}, std::slice, }; pub use crate::run::run; #[doc(hidden)] use request::Request; // Used in integration tests. #[doc(hidden)] pub use {request::Response, unindent::unindent}; type CompileResult<'a, T = ()> = Result>; type ConfigResult = Result; type FunctionResult = Result; type RunResult<'a, T = ()> = Result>; type SearchResult = Result; #[cfg(test)] #[macro_use] pub mod testing; #[cfg(test)] #[macro_use] pub mod tree; #[cfg(test)] pub mod node; #[cfg(fuzzing)] pub mod fuzzing; // Used by Janus, https://github.com/casey/janus, a tool // that analyses all public justfiles on GitHub to avoid // breaking changes. #[doc(hidden)] pub mod summary; // Used for testing with the `--request` subcommand. #[doc(hidden)] pub mod request; mod alias; mod alias_style; mod analyzer; mod argument_parser; mod assignment; mod assignment_resolver; mod ast; mod attribute; mod attribute_set; mod binding; mod color; mod color_display; mod command_color; mod command_ext; mod compilation; mod compile_error; mod compile_error_kind; mod compiler; mod completions; mod condition; mod conditional_operator; mod config; mod config_error; mod constants; mod count; mod delimiter; mod dependency; mod dump_format; mod enclosure; mod error; mod evaluator; mod execution_context; mod executor; mod expression; mod fragment; mod function; mod interpreter; mod interrupt_guard; mod interrupt_handler; mod item; mod justfile; mod keyed; mod keyword; mod lexer; mod line; mod list; mod load_dotenv; mod loader; mod module_path; mod name; mod namepath; mod ordinal; mod output; mod output_error; mod parameter; mod parameter_kind; mod parser; mod platform; mod platform_interface; mod position; mod positional; mod ran; mod range_ext; mod recipe; mod recipe_resolver; mod recipe_signature; mod run; mod scope; mod search; mod search_config; mod search_error; mod set; mod setting; mod settings; mod shebang; mod show_whitespace; mod source; mod string_delimiter; mod string_kind; mod string_literal; mod subcommand; mod suggestion; mod table; mod thunk; mod token; mod token_kind; mod unindent; mod unresolved_dependency; mod unresolved_recipe; mod unstable_feature; mod use_color; mod variables; mod verbosity; mod warning; mod which; just-1.40.0/src/line.rs000064400000000000000000000023151046102023000127600ustar 00000000000000use super::*; /// A single line in a recipe body, consisting of any number of `Fragment`s. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(transparent)] pub(crate) struct Line<'src> { pub(crate) fragments: Vec>, #[serde(skip)] pub(crate) number: usize, } impl Line<'_> { fn first(&self) -> Option<&str> { if let Fragment::Text { token } = self.fragments.first()? { Some(token.lexeme()) } else { None } } pub(crate) fn is_comment(&self) -> bool { self.first().is_some_and(|text| text.starts_with('#')) } pub(crate) fn is_continuation(&self) -> bool { matches!( self.fragments.last(), Some(Fragment::Text { token }) if token.lexeme().ends_with('\\'), ) } pub(crate) fn is_empty(&self) -> bool { self.fragments.is_empty() } pub(crate) fn is_infallible(&self) -> bool { self .first() .is_some_and(|text| text.starts_with('-') || text.starts_with("@-")) } pub(crate) fn is_quiet(&self) -> bool { self .first() .is_some_and(|text| text.starts_with('@') || text.starts_with("-@")) } pub(crate) fn is_shebang(&self) -> bool { self.first().is_some_and(|text| text.starts_with("#!")) } } just-1.40.0/src/list.rs000064400000000000000000000062161046102023000130100ustar 00000000000000use super::*; pub struct List + Clone> { conjunction: &'static str, values: I, } impl + Clone> List { pub fn or>(values: II) -> Self { Self { conjunction: "or", values: values.into_iter(), } } pub fn and>(values: II) -> Self { Self { conjunction: "and", values: values.into_iter(), } } pub fn or_ticked>( values: II, ) -> List, impl Iterator> + Clone> { List::or(values.into_iter().map(Enclosure::tick)) } pub fn and_ticked>( values: II, ) -> List, impl Iterator> + Clone> { List::and(values.into_iter().map(Enclosure::tick)) } } impl + Clone> Display for List { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut values = self.values.clone().fuse(); if let Some(first) = values.next() { write!(f, "{first}")?; } else { return Ok(()); } let second = values.next(); if second.is_none() { return Ok(()); } let third = values.next(); if let (Some(second), None) = (second.as_ref(), third.as_ref()) { write!(f, " {} {second}", self.conjunction)?; return Ok(()); } let mut current = second; let mut next = third; loop { match (current, next) { (Some(c), Some(n)) => { write!(f, ", {c}")?; current = Some(n); next = values.next(); } (Some(c), None) => { write!(f, ", {} {c}", self.conjunction)?; return Ok(()); } _ => unreachable!("Iterator was fused, but returned Some after None"), } } } } #[cfg(test)] mod tests { use super::*; #[test] fn or() { assert_eq!("1", List::or(&[1]).to_string()); assert_eq!("1 or 2", List::or(&[1, 2]).to_string()); assert_eq!("1, 2, or 3", List::or(&[1, 2, 3]).to_string()); assert_eq!("1, 2, 3, or 4", List::or(&[1, 2, 3, 4]).to_string()); } #[test] fn and() { assert_eq!("1", List::and(&[1]).to_string()); assert_eq!("1 and 2", List::and(&[1, 2]).to_string()); assert_eq!("1, 2, and 3", List::and(&[1, 2, 3]).to_string()); assert_eq!("1, 2, 3, and 4", List::and(&[1, 2, 3, 4]).to_string()); } #[test] fn or_ticked() { assert_eq!("`1`", List::or_ticked(&[1]).to_string()); assert_eq!("`1` or `2`", List::or_ticked(&[1, 2]).to_string()); assert_eq!("`1`, `2`, or `3`", List::or_ticked(&[1, 2, 3]).to_string()); assert_eq!( "`1`, `2`, `3`, or `4`", List::or_ticked(&[1, 2, 3, 4]).to_string() ); } #[test] fn and_ticked() { assert_eq!("`1`", List::and_ticked(&[1]).to_string()); assert_eq!("`1` and `2`", List::and_ticked(&[1, 2]).to_string()); assert_eq!( "`1`, `2`, and `3`", List::and_ticked(&[1, 2, 3]).to_string() ); assert_eq!( "`1`, `2`, `3`, and `4`", List::and_ticked(&[1, 2, 3, 4]).to_string() ); } } just-1.40.0/src/load_dotenv.rs000064400000000000000000000024671046102023000143370ustar 00000000000000use super::*; pub(crate) fn load_dotenv( config: &Config, settings: &Settings, working_directory: &Path, ) -> RunResult<'static, BTreeMap> { let dotenv_filename = config .dotenv_filename .as_ref() .or(settings.dotenv_filename.as_ref()); let dotenv_path = config .dotenv_path .as_ref() .or(settings.dotenv_path.as_ref()); if !settings.dotenv_load && dotenv_filename.is_none() && dotenv_path.is_none() && !settings.dotenv_required { return Ok(BTreeMap::new()); } if let Some(path) = dotenv_path { let path = working_directory.join(path); if path.is_file() { return load_from_file(&path); } } let filename = dotenv_filename.map_or(".env", |s| s.as_str()); for directory in working_directory.ancestors() { let path = directory.join(filename); if path.is_file() { return load_from_file(&path); } } if settings.dotenv_required { Err(Error::DotenvRequired) } else { Ok(BTreeMap::new()) } } fn load_from_file(path: &Path) -> RunResult<'static, BTreeMap> { let iter = dotenvy::from_path_iter(path)?; let mut dotenv = BTreeMap::new(); for result in iter { let (key, value) = result?; if env::var_os(&key).is_none() { dotenv.insert(key, value); } } Ok(dotenv) } just-1.40.0/src/loader.rs000064400000000000000000000011501046102023000132730ustar 00000000000000use super::*; pub(crate) struct Loader { paths: Arena, srcs: Arena, } impl Loader { pub(crate) fn new() -> Self { Self { srcs: Arena::new(), paths: Arena::new(), } } pub(crate) fn load<'src>( &'src self, root: &Path, path: &Path, ) -> RunResult<'src, (&'src Path, &'src str)> { let src = fs::read_to_string(path).map_err(|io_error| Error::Load { path: path.into(), io_error, })?; let relative = path.strip_prefix(root.parent().unwrap()).unwrap_or(path); Ok((self.paths.alloc(relative.into()), self.srcs.alloc(src))) } } just-1.40.0/src/main.rs000064400000000000000000000001461046102023000127550ustar 00000000000000fn main() { if let Err(code) = just::run(std::env::args_os()) { std::process::exit(code); } } just-1.40.0/src/module_path.rs000064400000000000000000000041331046102023000143320ustar 00000000000000use super::*; #[derive(Debug, PartialEq, Clone)] pub(crate) struct ModulePath { pub(crate) path: Vec, pub(crate) spaced: bool, } impl TryFrom<&[&str]> for ModulePath { type Error = (); fn try_from(path: &[&str]) -> Result { let spaced = path.len() > 1; let path = if path.len() == 1 { let first = path[0]; if first.starts_with(':') || first.ends_with(':') || first.contains(":::") { return Err(()); } first .split("::") .map(str::to_string) .collect::>() } else { path.iter().map(|s| (*s).to_string()).collect() }; for name in &path { if name.is_empty() { return Err(()); } for (i, c) in name.chars().enumerate() { if i == 0 { if !Lexer::is_identifier_start(c) { return Err(()); } } else if !Lexer::is_identifier_continue(c) { return Err(()); } } } Ok(Self { path, spaced }) } } impl Display for ModulePath { fn fmt(&self, f: &mut Formatter) -> fmt::Result { for (i, name) in self.path.iter().enumerate() { if i > 0 { if self.spaced { write!(f, " ")?; } else { write!(f, "::")?; } } write!(f, "{name}")?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn try_from_ok() { #[track_caller] fn case(path: &[&str], expected: &[&str], display: &str) { let actual = ModulePath::try_from(path).unwrap(); assert_eq!(actual.path, expected); assert_eq!(actual.to_string(), display); } case(&[], &[], ""); case(&["foo"], &["foo"], "foo"); case(&["foo0"], &["foo0"], "foo0"); case(&["foo", "bar"], &["foo", "bar"], "foo bar"); case(&["foo::bar"], &["foo", "bar"], "foo::bar"); } #[test] fn try_from_err() { #[track_caller] fn case(path: &[&str]) { assert!(ModulePath::try_from(path).is_err()); } case(&[":foo"]); case(&["foo:"]); case(&["foo:::bar"]); case(&["0foo"]); case(&["f$oo"]); case(&[""]); } } just-1.40.0/src/name.rs000064400000000000000000000015011046102023000127450ustar 00000000000000use super::*; /// A name. This is just a `Token` of kind `Identifier`, but we give it its own /// type for clarity. #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub(crate) struct Name<'src> { pub(crate) token: Token<'src>, } impl<'src> Name<'src> { pub(crate) fn from_identifier(token: Token<'src>) -> Self { assert_eq!(token.kind, TokenKind::Identifier); Self { token } } } impl<'src> Deref for Name<'src> { type Target = Token<'src>; fn deref(&self) -> &Self::Target { &self.token } } impl Display for Name<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.lexeme()) } } impl Serialize for Name<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(self.lexeme()) } } just-1.40.0/src/namepath.rs000064400000000000000000000026141046102023000136300ustar 00000000000000use super::*; #[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] pub(crate) struct Namepath<'src>(Vec>); impl<'src> Namepath<'src> { pub(crate) fn join(&self, name: Name<'src>) -> Self { Self(self.0.iter().copied().chain(iter::once(name)).collect()) } pub(crate) fn spaced(&self) -> ModulePath { ModulePath { path: self.0.iter().map(|name| name.lexeme().into()).collect(), spaced: true, } } pub(crate) fn push(&mut self, name: Name<'src>) { self.0.push(name); } pub(crate) fn last(&self) -> &Name<'src> { self.0.last().unwrap() } pub(crate) fn split_last(&self) -> (&Name<'src>, &[Name<'src>]) { self.0.split_last().unwrap() } #[cfg(test)] pub(crate) fn iter(&self) -> slice::Iter<'_, Name<'src>> { self.0.iter() } #[cfg(test)] pub(crate) fn len(&self) -> usize { self.0.len() } } impl Display for Namepath<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { for (i, name) in self.0.iter().enumerate() { if i > 0 { write!(f, "::")?; } write!(f, "{name}")?; } Ok(()) } } impl<'src> From> for Namepath<'src> { fn from(name: Name<'src>) -> Self { Self(vec![name]) } } impl Serialize for Namepath<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&format!("{self}")) } } just-1.40.0/src/node.rs000064400000000000000000000220501046102023000127540ustar 00000000000000use super::*; /// Methods common to all AST nodes. Currently only used in parser unit tests. pub(crate) trait Node<'src> { /// Construct an untyped tree of atoms representing this Node. This function, /// and `Tree` type, are only used in parser unit tests. fn tree(&self) -> Tree<'src>; } impl<'src> Node<'src> for Ast<'src> { fn tree(&self) -> Tree<'src> { Tree::atom("justfile") .extend(self.items.iter().map(Node::tree)) .extend(self.warnings.iter().map(Node::tree)) } } impl<'src> Node<'src> for Item<'src> { fn tree(&self) -> Tree<'src> { match self { Self::Alias(alias) => alias.tree(), Self::Assignment(assignment) => assignment.tree(), Self::Comment(comment) => comment.tree(), Self::Import { relative, optional, .. } => { let mut tree = Tree::atom("import"); if *optional { tree = tree.push("?"); } tree.push(format!("{relative}")) } Self::Module { name, optional, relative, .. } => { let mut tree = Tree::atom("mod"); if *optional { tree = tree.push("?"); } tree = tree.push(name.lexeme()); if let Some(relative) = relative { tree = tree.push(format!("{relative}")); } tree } Self::Recipe(recipe) => recipe.tree(), Self::Set(set) => set.tree(), Self::Unexport { name } => { let mut unexport = Tree::atom(Keyword::Unexport.lexeme()); unexport.push_mut(name.lexeme().replace('-', "_")); unexport } } } } impl<'src> Node<'src> for Namepath<'src> { fn tree(&self) -> Tree<'src> { match self.len() { 1 => Tree::atom(self.last().lexeme()), _ => Tree::list( self .iter() .map(|name| Tree::atom(Cow::Borrowed(name.lexeme()))), ), } } } impl<'src> Node<'src> for Alias<'src, Namepath<'src>> { fn tree(&self) -> Tree<'src> { let target = self.target.tree(); Tree::atom(Keyword::Alias.lexeme()) .push(self.name.lexeme()) .push(target) } } impl<'src> Node<'src> for Assignment<'src> { fn tree(&self) -> Tree<'src> { if self.export { Tree::atom("assignment") .push("#") .push(Keyword::Export.lexeme()) } else { Tree::atom("assignment") } .push(self.name.lexeme()) .push(self.value.tree()) } } impl<'src> Node<'src> for Expression<'src> { fn tree(&self) -> Tree<'src> { match self { Self::And { lhs, rhs } => Tree::atom("&&").push(lhs.tree()).push(rhs.tree()), Self::Assert { condition: Condition { lhs, rhs, operator }, error, } => Tree::atom(Keyword::Assert.lexeme()) .push(lhs.tree()) .push(operator.to_string()) .push(rhs.tree()) .push(error.tree()), Self::Backtick { contents, .. } => Tree::atom("backtick").push(Tree::string(contents)), Self::Call { thunk } => { use Thunk::*; let mut tree = Tree::atom("call"); match thunk { Nullary { name, .. } => tree.push_mut(name.lexeme()), Unary { name, arg, .. } => { tree.push_mut(name.lexeme()); tree.push_mut(arg.tree()); } UnaryOpt { name, args: (a, b), .. } => { tree.push_mut(name.lexeme()); tree.push_mut(a.tree()); if let Some(b) = b.as_ref() { tree.push_mut(b.tree()); } } UnaryPlus { name, args: (a, rest), .. } => { tree.push_mut(name.lexeme()); tree.push_mut(a.tree()); for arg in rest { tree.push_mut(arg.tree()); } } Binary { name, args: [a, b], .. } => { tree.push_mut(name.lexeme()); tree.push_mut(a.tree()); tree.push_mut(b.tree()); } BinaryPlus { name, args: ([a, b], rest), .. } => { tree.push_mut(name.lexeme()); tree.push_mut(a.tree()); tree.push_mut(b.tree()); for arg in rest { tree.push_mut(arg.tree()); } } Ternary { name, args: [a, b, c], .. } => { tree.push_mut(name.lexeme()); tree.push_mut(a.tree()); tree.push_mut(b.tree()); tree.push_mut(c.tree()); } } tree } Self::Concatenation { lhs, rhs } => Tree::atom("+").push(lhs.tree()).push(rhs.tree()), Self::Conditional { condition: Condition { lhs, rhs, operator }, then, otherwise, } => { let mut tree = Tree::atom(Keyword::If.lexeme()); tree.push_mut(lhs.tree()); tree.push_mut(operator.to_string()); tree.push_mut(rhs.tree()); tree.push_mut(then.tree()); tree.push_mut(otherwise.tree()); tree } Self::Group { contents } => Tree::List(vec![contents.tree()]), Self::Join { lhs: None, rhs } => Tree::atom("/").push(rhs.tree()), Self::Join { lhs: Some(lhs), rhs, } => Tree::atom("/").push(lhs.tree()).push(rhs.tree()), Self::Or { lhs, rhs } => Tree::atom("||").push(lhs.tree()).push(rhs.tree()), Self::StringLiteral { string_literal: StringLiteral { cooked, .. }, } => Tree::string(cooked), Self::Variable { name } => Tree::atom(name.lexeme()), } } } impl<'src> Node<'src> for UnresolvedRecipe<'src> { fn tree(&self) -> Tree<'src> { let mut t = Tree::atom("recipe"); if self.quiet { t.push_mut("#"); t.push_mut("quiet"); } if let Some(doc) = &self.doc { t.push_mut(Tree::string(doc)); } t.push_mut(self.name.lexeme()); if !self.parameters.is_empty() { let mut params = Tree::atom("params"); for parameter in &self.parameters { if let Some(prefix) = parameter.kind.prefix() { params.push_mut(prefix); } params.push_mut(parameter.tree()); } t.push_mut(params); } if !self.dependencies.is_empty() { let mut dependencies = Tree::atom("deps"); let mut subsequents = Tree::atom("sups"); for (i, dependency) in self.dependencies.iter().enumerate() { let mut d = Tree::atom(dependency.recipe.lexeme()); for argument in &dependency.arguments { d.push_mut(argument.tree()); } if i < self.priors { dependencies.push_mut(d); } else { subsequents.push_mut(d); } } if let Tree::List(_) = dependencies { t.push_mut(dependencies); } if let Tree::List(_) = subsequents { t.push_mut(subsequents); } } if !self.body.is_empty() { t.push_mut(Tree::atom("body").extend(self.body.iter().map(Node::tree))); } t } } impl<'src> Node<'src> for Parameter<'src> { fn tree(&self) -> Tree<'src> { let mut children = vec![Tree::atom(self.name.lexeme())]; if let Some(default) = &self.default { children.push(default.tree()); } Tree::List(children) } } impl<'src> Node<'src> for Line<'src> { fn tree(&self) -> Tree<'src> { Tree::list(self.fragments.iter().map(Node::tree)) } } impl<'src> Node<'src> for Fragment<'src> { fn tree(&self) -> Tree<'src> { match self { Self::Text { token } => Tree::string(token.lexeme()), Self::Interpolation { expression } => Tree::List(vec![expression.tree()]), } } } impl<'src> Node<'src> for Set<'src> { fn tree(&self) -> Tree<'src> { let mut set = Tree::atom(Keyword::Set.lexeme()); set.push_mut(self.name.lexeme().replace('-', "_")); match &self.value { Setting::AllowDuplicateRecipes(value) | Setting::AllowDuplicateVariables(value) | Setting::DotenvLoad(value) | Setting::DotenvRequired(value) | Setting::Export(value) | Setting::Fallback(value) | Setting::NoExitMessage(value) | Setting::PositionalArguments(value) | Setting::Quiet(value) | Setting::Unstable(value) | Setting::WindowsPowerShell(value) | Setting::IgnoreComments(value) => { set.push_mut(value.to_string()); } Setting::ScriptInterpreter(Interpreter { command, arguments }) | Setting::Shell(Interpreter { command, arguments }) | Setting::WindowsShell(Interpreter { command, arguments }) => { set.push_mut(Tree::string(&command.cooked)); for argument in arguments { set.push_mut(Tree::string(&argument.cooked)); } } Setting::DotenvFilename(value) | Setting::DotenvPath(value) | Setting::Tempdir(value) | Setting::WorkingDirectory(value) => { set.push_mut(Tree::string(&value.cooked)); } } set } } impl<'src> Node<'src> for Warning { fn tree(&self) -> Tree<'src> { unreachable!() } } impl<'src> Node<'src> for str { fn tree(&self) -> Tree<'src> { Tree::atom("comment").push(["\"", self, "\""].concat()) } } just-1.40.0/src/ordinal.rs000064400000000000000000000003041046102023000134550ustar 00000000000000pub(crate) trait Ordinal { /// Convert an index starting at 0 to an ordinal starting at 1 fn ordinal(self) -> Self; } impl Ordinal for usize { fn ordinal(self) -> Self { self + 1 } } just-1.40.0/src/output.rs000064400000000000000000000017731046102023000134000ustar 00000000000000use super::*; /// Run a command and return the data it wrote to stdout as a string pub(crate) fn output(mut command: Command) -> Result { match command.output() { Ok(output) => { if let Some(code) = output.status.code() { if code != 0 { return Err(OutputError::Code(code)); } } else { let signal = Platform::signal_from_exit_status(output.status); return Err(match signal { Some(signal) => OutputError::Signal(signal), None => OutputError::Unknown, }); } match str::from_utf8(&output.stdout) { Err(error) => Err(OutputError::Utf8(error)), Ok(output) => Ok( if output.ends_with("\r\n") { &output[0..output.len() - 2] } else if output.ends_with('\n') { &output[0..output.len() - 1] } else { output } .to_owned(), ), } } Err(io_error) => Err(OutputError::Io(io_error)), } } just-1.40.0/src/output_error.rs000064400000000000000000000014151046102023000146020ustar 00000000000000use super::*; #[derive(Debug)] pub(crate) enum OutputError { /// Non-zero exit code Code(i32), /// IO error Io(io::Error), /// Terminated by signal Signal(i32), /// Unknown failure Unknown, /// Stdout not UTF-8 Utf8(str::Utf8Error), } impl Display for OutputError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { Self::Code(code) => write!(f, "Process exited with status code {code}"), Self::Io(ref io_error) => write!(f, "Error executing process: {io_error}"), Self::Signal(signal) => write!(f, "Process terminated by signal {signal}"), Self::Unknown => write!(f, "Process experienced an unknown failure"), Self::Utf8(ref err) => write!(f, "Could not convert process stdout to UTF-8: {err}"), } } } just-1.40.0/src/parameter.rs000064400000000000000000000017671046102023000140230ustar 00000000000000use super::*; /// A single function parameter #[derive(PartialEq, Debug, Clone, Serialize)] pub(crate) struct Parameter<'src> { /// An optional default expression pub(crate) default: Option>, /// Export parameter as environment variable pub(crate) export: bool, /// The kind of parameter pub(crate) kind: ParameterKind, /// The parameter name pub(crate) name: Name<'src>, } impl Parameter<'_> { pub(crate) fn is_required(&self) -> bool { self.default.is_none() && self.kind != ParameterKind::Star } } impl ColorDisplay for Parameter<'_> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { if let Some(prefix) = self.kind.prefix() { write!(f, "{}", color.annotation().paint(prefix))?; } if self.export { write!(f, "$")?; } write!(f, "{}", color.parameter().paint(self.name.lexeme()))?; if let Some(ref default) = self.default { write!(f, "={}", color.string().paint(&default.to_string()))?; } Ok(()) } } just-1.40.0/src/parameter_kind.rs000064400000000000000000000011611046102023000150140ustar 00000000000000use super::*; /// Parameters can either be… #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub(crate) enum ParameterKind { /// …variadic, accepting one or more arguments Plus, /// …singular, accepting a single argument Singular, /// …variadic, accepting zero or more arguments Star, } impl ParameterKind { pub(crate) fn prefix(self) -> Option<&'static str> { match self { Self::Singular => None, Self::Plus => Some("+"), Self::Star => Some("*"), } } pub(crate) fn is_variadic(self) -> bool { self != Self::Singular } } just-1.40.0/src/parser.rs000064400000000000000000002076471046102023000133440ustar 00000000000000use {super::*, TokenKind::*}; /// Just language parser /// /// The parser is a (hopefully) straightforward recursive descent parser. /// /// It uses a few tokens of lookahead to disambiguate different constructs. /// /// The `expect_*` and `presume_`* methods are similar in that they assert the /// type of unparsed tokens and consume them. However, upon encountering an /// unexpected token, the `expect_*` methods return an unexpected token error, /// whereas the `presume_*` tokens return an internal error. /// /// The `presume_*` methods are used when the token stream has been inspected in /// some other way, and thus encountering an unexpected token is a bug in Just, /// and not a syntax error. /// /// All methods starting with `parse_*` parse and return a language construct. /// /// The parser tracks an expected set of tokens as it parses. This set contains /// all tokens which would have been accepted at the current point in the /// parse. Whenever the parser tests for a token that would be accepted, but /// does not find it, it adds that token to the set. When the parser accepts a /// token, the set is cleared. If the parser finds a token which is unexpected, /// the elements of the set are printed in the resultant error message. pub(crate) struct Parser<'run, 'src> { expected_tokens: BTreeSet, file_depth: u32, import_offsets: Vec, module_namepath: Option<&'run Namepath<'src>>, next_token: usize, recursion_depth: usize, tokens: &'run [Token<'src>], unstable_features: BTreeSet, working_directory: &'run Path, } impl<'run, 'src> Parser<'run, 'src> { /// Parse `tokens` into an `Ast` pub(crate) fn parse( file_depth: u32, import_offsets: &[usize], module_namepath: Option<&'run Namepath<'src>>, tokens: &'run [Token<'src>], working_directory: &'run Path, ) -> CompileResult<'src, Ast<'src>> { Self { expected_tokens: BTreeSet::new(), file_depth, import_offsets: import_offsets.to_vec(), module_namepath, next_token: 0, recursion_depth: 0, tokens, unstable_features: BTreeSet::new(), working_directory, } .parse_ast() } fn error(&self, kind: CompileErrorKind<'src>) -> CompileResult<'src, CompileError<'src>> { Ok(self.next()?.error(kind)) } /// Construct an unexpected token error with the token returned by /// `Parser::next` fn unexpected_token(&self) -> CompileResult<'src, CompileError<'src>> { self.error(CompileErrorKind::UnexpectedToken { expected: self .expected_tokens .iter() .copied() .filter(|kind| *kind != ByteOrderMark) .collect::>(), found: self.next()?.kind, }) } fn internal_error(&self, message: impl Into) -> CompileResult<'src, CompileError<'src>> { self.error(CompileErrorKind::Internal { message: message.into(), }) } /// An iterator over the remaining significant tokens fn rest(&self) -> impl Iterator> + 'run { self.tokens[self.next_token..] .iter() .copied() .filter(|token| token.kind != Whitespace) } /// The next significant token fn next(&self) -> CompileResult<'src, Token<'src>> { if let Some(token) = self.rest().next() { Ok(token) } else { Err(self.internal_error("`Parser::next()` called after end of token stream")?) } } /// Check if the next significant token is of kind `kind` fn next_is(&mut self, kind: TokenKind) -> bool { self.next_are(&[kind]) } /// Check if the next significant tokens are of kinds `kinds` /// /// The first token in `kinds` will be added to the expected token set. fn next_are(&mut self, kinds: &[TokenKind]) -> bool { if let Some(&kind) = kinds.first() { self.expected_tokens.insert(kind); } let mut rest = self.rest(); for kind in kinds { match rest.next() { Some(token) => { if token.kind != *kind { return false; } } None => return false, } } true } /// Advance past one significant token, clearing the expected token set. fn advance(&mut self) -> CompileResult<'src, Token<'src>> { self.expected_tokens.clear(); for skipped in &self.tokens[self.next_token..] { self.next_token += 1; if skipped.kind != Whitespace { return Ok(*skipped); } } Err(self.internal_error("`Parser::advance()` advanced past end of token stream")?) } /// Return the next token if it is of kind `expected`, otherwise, return an /// unexpected token error fn expect(&mut self, expected: TokenKind) -> CompileResult<'src, Token<'src>> { if let Some(token) = self.accept(expected)? { Ok(token) } else { Err(self.unexpected_token()?) } } /// Return an unexpected token error if the next token is not an EOL fn expect_eol(&mut self) -> CompileResult<'src> { self.accept(Comment)?; if self.next_is(Eof) { return Ok(()); } self.expect(Eol).map(|_| ()) } fn expect_keyword(&mut self, expected: Keyword) -> CompileResult<'src> { let found = self.advance()?; if found.kind == Identifier && expected == found.lexeme() { Ok(()) } else { Err(found.error(CompileErrorKind::ExpectedKeyword { expected: vec![expected], found, })) } } /// Return an internal error if the next token is not of kind `Identifier` /// with lexeme `lexeme`. fn presume_keyword(&mut self, keyword: Keyword) -> CompileResult<'src> { let next = self.advance()?; if next.kind != Identifier { Err(self.internal_error(format!( "Presumed next token would have kind {Identifier}, but found {}", next.kind ))?) } else if keyword == next.lexeme() { Ok(()) } else { Err(self.internal_error(format!( "Presumed next token would have lexeme \"{keyword}\", but found \"{}\"", next.lexeme(), ))?) } } /// Return an internal error if the next token is not of kind `kind`. fn presume(&mut self, kind: TokenKind) -> CompileResult<'src, Token<'src>> { let next = self.advance()?; if next.kind == kind { Ok(next) } else { Err(self.internal_error(format!( "Presumed next token would have kind {kind:?}, but found {:?}", next.kind ))?) } } /// Return an internal error if the next token is not one of kinds `kinds`. fn presume_any(&mut self, kinds: &[TokenKind]) -> CompileResult<'src, Token<'src>> { let next = self.advance()?; if kinds.contains(&next.kind) { Ok(next) } else { Err(self.internal_error(format!( "Presumed next token would be {}, but found {}", List::or(kinds), next.kind ))?) } } /// Accept and return a token of kind `kind` fn accept(&mut self, kind: TokenKind) -> CompileResult<'src, Option>> { if self.next_is(kind) { Ok(Some(self.advance()?)) } else { Ok(None) } } /// Return an error if the next token is of kind `forbidden` fn forbid(&self, forbidden: TokenKind, error: F) -> CompileResult<'src> where F: FnOnce(Token) -> CompileError, { let next = self.next()?; if next.kind == forbidden { Err(error(next)) } else { Ok(()) } } /// Accept a token of kind `Identifier` and parse into a `Name` fn accept_name(&mut self) -> CompileResult<'src, Option>> { if self.next_is(Identifier) { Ok(Some(self.parse_name()?)) } else { Ok(None) } } fn accepted_keyword(&mut self, keyword: Keyword) -> CompileResult<'src, bool> { let next = self.next()?; if next.kind == Identifier && next.lexeme() == keyword.lexeme() { self.advance()?; Ok(true) } else { Ok(false) } } /// Accept a dependency fn accept_dependency(&mut self) -> CompileResult<'src, Option>> { if let Some(recipe) = self.accept_name()? { Ok(Some(UnresolvedDependency { arguments: Vec::new(), recipe, })) } else if self.accepted(ParenL)? { let recipe = self.parse_name()?; let mut arguments = Vec::new(); while !self.accepted(ParenR)? { arguments.push(self.parse_expression()?); } Ok(Some(UnresolvedDependency { arguments, recipe })) } else { Ok(None) } } /// Accept and return `true` if next token is of kind `kind` fn accepted(&mut self, kind: TokenKind) -> CompileResult<'src, bool> { Ok(self.accept(kind)?.is_some()) } /// Parse a justfile, consumes self fn parse_ast(mut self) -> CompileResult<'src, Ast<'src>> { fn pop_doc_comment<'src>( items: &mut Vec>, eol_since_last_comment: bool, ) -> Option<&'src str> { if !eol_since_last_comment { if let Some(Item::Comment(contents)) = items.last() { let doc = Some(contents[1..].trim_start()); items.pop(); return doc; } } None } let mut items = Vec::new(); let mut eol_since_last_comment = false; self.accept(ByteOrderMark)?; loop { let mut attributes = self.parse_attributes()?; let mut take_attributes = || { attributes .take() .map(|(_token, attributes)| attributes) .unwrap_or_default() }; let next = self.next()?; if let Some(comment) = self.accept(Comment)? { items.push(Item::Comment(comment.lexeme().trim_end())); self.expect_eol()?; eol_since_last_comment = false; } else if self.accepted(Eol)? { eol_since_last_comment = true; } else if self.accepted(Eof)? { break; } else if self.next_is(Identifier) { match Keyword::from_lexeme(next.lexeme()) { Some(Keyword::Alias) if self.next_are(&[Identifier, Identifier, ColonEquals]) => { items.push(Item::Alias(self.parse_alias(take_attributes())?)); } Some(Keyword::Export) if self.next_are(&[Identifier, Identifier, ColonEquals]) => { self.presume_keyword(Keyword::Export)?; items.push(Item::Assignment( self.parse_assignment(true, take_attributes())?, )); } Some(Keyword::Unexport) if self.next_are(&[Identifier, Identifier, Eof]) || self.next_are(&[Identifier, Identifier, Eol]) => { self.presume_keyword(Keyword::Unexport)?; let name = self.parse_name()?; self.expect_eol()?; items.push(Item::Unexport { name }); } Some(Keyword::Import) if self.next_are(&[Identifier, StringToken]) || self.next_are(&[Identifier, Identifier, StringToken]) || self.next_are(&[Identifier, QuestionMark]) => { self.presume_keyword(Keyword::Import)?; let optional = self.accepted(QuestionMark)?; let (path, relative) = self.parse_string_literal_token()?; items.push(Item::Import { absolute: None, optional, path, relative, }); } Some(Keyword::Mod) if self.next_are(&[Identifier, Identifier, Comment]) || self.next_are(&[Identifier, Identifier, Eof]) || self.next_are(&[Identifier, Identifier, Eol]) || self.next_are(&[Identifier, Identifier, Identifier, StringToken]) || self.next_are(&[Identifier, Identifier, StringToken]) || self.next_are(&[Identifier, QuestionMark]) => { let doc = pop_doc_comment(&mut items, eol_since_last_comment); self.presume_keyword(Keyword::Mod)?; let optional = self.accepted(QuestionMark)?; let name = self.parse_name()?; let relative = if self.next_is(StringToken) || self.next_are(&[Identifier, StringToken]) { Some(self.parse_string_literal()?) } else { None }; let attributes = take_attributes(); attributes.ensure_valid_attributes( "Module", *name, &[AttributeDiscriminant::Doc, AttributeDiscriminant::Group], )?; let doc = match attributes.get(AttributeDiscriminant::Doc) { Some(Attribute::Doc(Some(doc))) => Some(doc.cooked.clone()), Some(Attribute::Doc(None)) => None, None => doc.map(ToOwned::to_owned), _ => unreachable!(), }; let mut groups = Vec::new(); for attribute in attributes { if let Attribute::Group(group) = attribute { groups.push(group.cooked); } } items.push(Item::Module { groups, absolute: None, doc, name, optional, relative, }); } Some(Keyword::Set) if self.next_are(&[Identifier, Identifier, ColonEquals]) || self.next_are(&[Identifier, Identifier, Comment, Eof]) || self.next_are(&[Identifier, Identifier, Comment, Eol]) || self.next_are(&[Identifier, Identifier, Eof]) || self.next_are(&[Identifier, Identifier, Eol]) => { items.push(Item::Set(self.parse_set()?)); } _ => { if self.next_are(&[Identifier, ColonEquals]) { items.push(Item::Assignment( self.parse_assignment(false, take_attributes())?, )); } else { let doc = pop_doc_comment(&mut items, eol_since_last_comment); items.push(Item::Recipe(self.parse_recipe( doc, false, take_attributes(), )?)); } } } } else if self.accepted(At)? { let doc = pop_doc_comment(&mut items, eol_since_last_comment); items.push(Item::Recipe(self.parse_recipe( doc, true, take_attributes(), )?)); } else { return Err(self.unexpected_token()?); } if let Some((token, attributes)) = attributes { return Err(token.error(CompileErrorKind::ExtraneousAttributes { count: attributes.len(), })); } } if self.next_token != self.tokens.len() { return Err(self.internal_error(format!( "Parse completed with {} unparsed tokens", self.tokens.len() - self.next_token, ))?); } Ok(Ast { items, unstable_features: self.unstable_features, warnings: Vec::new(), working_directory: self.working_directory.into(), }) } /// Parse an alias, e.g `alias name := target` fn parse_alias( &mut self, attributes: AttributeSet<'src>, ) -> CompileResult<'src, Alias<'src, Namepath<'src>>> { self.presume_keyword(Keyword::Alias)?; let name = self.parse_name()?; self.presume_any(&[Equals, ColonEquals])?; let target = self.parse_namepath()?; self.expect_eol()?; attributes.ensure_valid_attributes("Alias", *name, &[AttributeDiscriminant::Private])?; Ok(Alias { attributes, name, target, }) } /// Parse an assignment, e.g. `foo := bar` fn parse_assignment( &mut self, export: bool, attributes: AttributeSet<'src>, ) -> CompileResult<'src, Assignment<'src>> { let name = self.parse_name()?; self.presume(ColonEquals)?; let value = self.parse_expression()?; self.expect_eol()?; let private = attributes.contains(AttributeDiscriminant::Private); attributes.ensure_valid_attributes("Assignment", *name, &[AttributeDiscriminant::Private])?; Ok(Assignment { constant: false, export, file_depth: self.file_depth, name, private: private || name.lexeme().starts_with('_'), value, }) } /// Parse an expression, e.g. `1 + 2` fn parse_expression(&mut self) -> CompileResult<'src, Expression<'src>> { if self.recursion_depth == if cfg!(windows) { 48 } else { 256 } { let token = self.next()?; return Err(CompileError::new( token, CompileErrorKind::ParsingRecursionDepthExceeded, )); } self.recursion_depth += 1; let disjunct = self.parse_disjunct()?; let expression = if self.accepted(BarBar)? { self .unstable_features .insert(UnstableFeature::LogicalOperators); let lhs = disjunct.into(); let rhs = self.parse_expression()?.into(); Expression::Or { lhs, rhs } } else { disjunct }; self.recursion_depth -= 1; Ok(expression) } fn parse_disjunct(&mut self) -> CompileResult<'src, Expression<'src>> { let conjunct = self.parse_conjunct()?; let disjunct = if self.accepted(AmpersandAmpersand)? { self .unstable_features .insert(UnstableFeature::LogicalOperators); let lhs = conjunct.into(); let rhs = self.parse_disjunct()?.into(); Expression::And { lhs, rhs } } else { conjunct }; Ok(disjunct) } fn parse_conjunct(&mut self) -> CompileResult<'src, Expression<'src>> { if self.accepted_keyword(Keyword::If)? { self.parse_conditional() } else if self.accepted(Slash)? { let lhs = None; let rhs = self.parse_conjunct()?.into(); Ok(Expression::Join { lhs, rhs }) } else { let value = self.parse_value()?; if self.accepted(Slash)? { let lhs = Some(Box::new(value)); let rhs = self.parse_conjunct()?.into(); Ok(Expression::Join { lhs, rhs }) } else if self.accepted(Plus)? { let lhs = value.into(); let rhs = self.parse_conjunct()?.into(); Ok(Expression::Concatenation { lhs, rhs }) } else { Ok(value) } } } /// Parse a conditional, e.g. `if a == b { "foo" } else { "bar" }` fn parse_conditional(&mut self) -> CompileResult<'src, Expression<'src>> { let condition = self.parse_condition()?; self.expect(BraceL)?; let then = self.parse_expression()?; self.expect(BraceR)?; self.expect_keyword(Keyword::Else)?; let otherwise = if self.accepted_keyword(Keyword::If)? { self.parse_conditional()? } else { self.expect(BraceL)?; let otherwise = self.parse_expression()?; self.expect(BraceR)?; otherwise }; Ok(Expression::Conditional { condition, then: then.into(), otherwise: otherwise.into(), }) } fn parse_condition(&mut self) -> CompileResult<'src, Condition<'src>> { let lhs = self.parse_expression()?; let operator = if self.accepted(BangEquals)? { ConditionalOperator::Inequality } else if self.accepted(EqualsTilde)? { ConditionalOperator::RegexMatch } else if self.accepted(BangTilde)? { ConditionalOperator::RegexMismatch } else { self.expect(EqualsEquals)?; ConditionalOperator::Equality }; let rhs = self.parse_expression()?; Ok(Condition { lhs: lhs.into(), rhs: rhs.into(), operator, }) } // Check if the next tokens are a shell-expanded string, i.e., `x"foo"`. // // This function skips initial whitespace tokens, but thereafter is // whitespace-sensitive, so `x"foo"` is a shell-expanded string, whereas `x // "foo"` is not. fn next_is_shell_expanded_string(&self) -> bool { let mut tokens = self .tokens .iter() .skip(self.next_token) .skip_while(|token| token.kind == Whitespace); tokens .next() .is_some_and(|token| token.kind == Identifier && token.lexeme() == "x") && tokens.next().is_some_and(|token| token.kind == StringToken) } /// Parse a value, e.g. `(bar)` fn parse_value(&mut self) -> CompileResult<'src, Expression<'src>> { if self.next_is(StringToken) || self.next_is_shell_expanded_string() { Ok(Expression::StringLiteral { string_literal: self.parse_string_literal()?, }) } else if self.next_is(Backtick) { let next = self.next()?; let kind = StringKind::from_string_or_backtick(next)?; let contents = &next.lexeme()[kind.delimiter_len()..next.lexeme().len() - kind.delimiter_len()]; let token = self.advance()?; let contents = if kind.indented() { unindent(contents) } else { contents.to_owned() }; if contents.starts_with("#!") { return Err(next.error(CompileErrorKind::BacktickShebang)); } Ok(Expression::Backtick { contents, token }) } else if self.next_is(Identifier) { if self.accepted_keyword(Keyword::Assert)? { self.expect(ParenL)?; let condition = self.parse_condition()?; self.expect(Comma)?; let error = Box::new(self.parse_expression()?); self.expect(ParenR)?; Ok(Expression::Assert { condition, error }) } else { let name = self.parse_name()?; if self.next_is(ParenL) { let arguments = self.parse_sequence()?; if name.lexeme() == "which" { self .unstable_features .insert(UnstableFeature::WhichFunction); } Ok(Expression::Call { thunk: Thunk::resolve(name, arguments)?, }) } else { Ok(Expression::Variable { name }) } } } else if self.next_is(ParenL) { self.presume(ParenL)?; let contents = self.parse_expression()?.into(); self.expect(ParenR)?; Ok(Expression::Group { contents }) } else { Err(self.unexpected_token()?) } } /// Parse a string literal, e.g. `"FOO"`, returning the string literal and the string token fn parse_string_literal_token( &mut self, ) -> CompileResult<'src, (Token<'src>, StringLiteral<'src>)> { let expand = if self.next_is(Identifier) { self.expect_keyword(Keyword::X)?; true } else { false }; let token = self.expect(StringToken)?; let kind = StringKind::from_string_or_backtick(token)?; let delimiter_len = kind.delimiter_len(); let raw = &token.lexeme()[delimiter_len..token.lexeme().len() - delimiter_len]; let unindented = if kind.indented() { unindent(raw) } else { raw.to_owned() }; let cooked = if kind.processes_escape_sequences() { Self::cook_string(token, &unindented)? } else { unindented }; let cooked = if expand { shellexpand::full(&cooked) .map_err(|err| token.error(CompileErrorKind::ShellExpansion { err }))? .into_owned() } else { cooked }; Ok(( token, StringLiteral { cooked, expand, kind, raw, }, )) } // Transform escape sequences in from string literal `token` with content `text` fn cook_string(token: Token<'src>, text: &str) -> CompileResult<'src, String> { #[derive(PartialEq, Eq)] enum State { Backslash, Initial, Unicode, UnicodeValue { hex: String }, } let mut cooked = String::new(); let mut state = State::Initial; for c in text.chars() { match state { State::Initial => { if c == '\\' { state = State::Backslash; } else { cooked.push(c); } } State::Backslash if c == 'u' => { state = State::Unicode; } State::Backslash => { match c { 'n' => cooked.push('\n'), 'r' => cooked.push('\r'), 't' => cooked.push('\t'), '\\' => cooked.push('\\'), '\n' => {} '"' => cooked.push('"'), character => { return Err(token.error(CompileErrorKind::InvalidEscapeSequence { character })) } } state = State::Initial; } State::Unicode => match c { '{' => { state = State::UnicodeValue { hex: String::new() }; } character => { return Err(token.error(CompileErrorKind::UnicodeEscapeDelimiter { character })); } }, State::UnicodeValue { ref mut hex } => match c { '}' => { if hex.is_empty() { return Err(token.error(CompileErrorKind::UnicodeEscapeEmpty)); } let codepoint = u32::from_str_radix(hex, 16).unwrap(); cooked.push(char::from_u32(codepoint).ok_or_else(|| { token.error(CompileErrorKind::UnicodeEscapeRange { hex: hex.clone() }) })?); state = State::Initial; } '0'..='9' | 'A'..='F' | 'a'..='f' => { hex.push(c); if hex.len() > 6 { return Err(token.error(CompileErrorKind::UnicodeEscapeLength { hex: hex.clone() })); } } _ => { return Err(token.error(CompileErrorKind::UnicodeEscapeCharacter { character: c })); } }, } } if state != State::Initial { return Err(token.error(CompileErrorKind::UnicodeEscapeUnterminated)); } Ok(cooked) } /// Parse a string literal, e.g. `"FOO"` fn parse_string_literal(&mut self) -> CompileResult<'src, StringLiteral<'src>> { let (_token, string_literal) = self.parse_string_literal_token()?; Ok(string_literal) } /// Parse a name from an identifier token fn parse_name(&mut self) -> CompileResult<'src, Name<'src>> { self.expect(Identifier).map(Name::from_identifier) } /// Parse a path of `::` separated names fn parse_namepath(&mut self) -> CompileResult<'src, Namepath<'src>> { let first = self.parse_name()?; let mut path = Namepath::from(first); while self.accepted(ColonColon)? { let name = self.parse_name()?; path.push(name); } Ok(path) } /// Parse sequence of comma-separated expressions fn parse_sequence(&mut self) -> CompileResult<'src, Vec>> { self.presume(ParenL)?; let mut elements = Vec::new(); while !self.next_is(ParenR) { elements.push(self.parse_expression()?); if !self.accepted(Comma)? { break; } } self.expect(ParenR)?; Ok(elements) } /// Parse a recipe fn parse_recipe( &mut self, doc: Option<&'src str>, quiet: bool, attributes: AttributeSet<'src>, ) -> CompileResult<'src, UnresolvedRecipe<'src>> { let name = self.parse_name()?; let mut positional = Vec::new(); while self.next_is(Identifier) || self.next_is(Dollar) { positional.push(self.parse_parameter(ParameterKind::Singular)?); } let kind = if self.accepted(Plus)? { ParameterKind::Plus } else if self.accepted(Asterisk)? { ParameterKind::Star } else { ParameterKind::Singular }; let variadic = if kind.is_variadic() { let variadic = self.parse_parameter(kind)?; self.forbid(Identifier, |token| { token.error(CompileErrorKind::ParameterFollowsVariadicParameter { parameter: token.lexeme(), }) })?; Some(variadic) } else { None }; self.expect(Colon)?; let mut dependencies = Vec::new(); while let Some(dependency) = self.accept_dependency()? { dependencies.push(dependency); } let priors = dependencies.len(); if self.accepted(AmpersandAmpersand)? { let mut subsequents = Vec::new(); while let Some(subsequent) = self.accept_dependency()? { subsequents.push(subsequent); } if subsequents.is_empty() { return Err(self.unexpected_token()?); } dependencies.append(&mut subsequents); } self.expect_eol()?; let body = self.parse_body()?; let shebang = body.first().is_some_and(Line::is_shebang); let script = attributes.contains(AttributeDiscriminant::Script); if shebang && script { return Err(name.error(CompileErrorKind::ShebangAndScriptAttribute { recipe: name.lexeme(), })); } if attributes.contains(AttributeDiscriminant::WorkingDirectory) && attributes.contains(AttributeDiscriminant::NoCd) { return Err( name.error(CompileErrorKind::NoCdAndWorkingDirectoryAttribute { recipe: name.lexeme(), }), ); } if attributes.contains(AttributeDiscriminant::ExitMessage) && attributes.contains(AttributeDiscriminant::NoExitMessage) { return Err( name.error(CompileErrorKind::ExitMessageAndNoExitMessageAttribute { recipe: name.lexeme(), }), ); } let private = name.lexeme().starts_with('_') || attributes.contains(AttributeDiscriminant::Private); let mut doc = doc.map(ToOwned::to_owned); for attribute in &attributes { if let Attribute::Doc(attribute_doc) = attribute { doc = attribute_doc.as_ref().map(|doc| doc.cooked.clone()); } } Ok(Recipe { shebang: shebang || script, attributes, body, dependencies, doc: doc.filter(|doc| !doc.is_empty()), file_depth: self.file_depth, import_offsets: self.import_offsets.clone(), name, namepath: self .module_namepath .map_or_else(|| name.into(), |module_namepath| module_namepath.join(name)), parameters: positional.into_iter().chain(variadic).collect(), priors, private, quiet, }) } /// Parse a recipe parameter fn parse_parameter(&mut self, kind: ParameterKind) -> CompileResult<'src, Parameter<'src>> { let export = self.accepted(Dollar)?; let name = self.parse_name()?; let default = if self.accepted(Equals)? { Some(self.parse_value()?) } else { None }; Ok(Parameter { default, export, kind, name, }) } /// Parse the body of a recipe fn parse_body(&mut self) -> CompileResult<'src, Vec>> { let mut lines = Vec::new(); if self.accepted(Indent)? { while !self.accepted(Dedent)? { let mut fragments = Vec::new(); let number = self .tokens .get(self.next_token) .map(|token| token.line) .unwrap_or_default(); if !self.accepted(Eol)? { while !(self.accepted(Eol)? || self.next_is(Dedent)) { if let Some(token) = self.accept(Text)? { fragments.push(Fragment::Text { token }); } else if self.accepted(InterpolationStart)? { fragments.push(Fragment::Interpolation { expression: self.parse_expression()?, }); self.expect(InterpolationEnd)?; } else { return Err(self.unexpected_token()?); } } }; lines.push(Line { fragments, number }); } } while lines.last().is_some_and(Line::is_empty) { lines.pop(); } Ok(lines) } /// Parse a boolean setting value fn parse_set_bool(&mut self) -> CompileResult<'src, bool> { if !self.accepted(ColonEquals)? { return Ok(true); } let identifier = self.expect(Identifier)?; let value = if Keyword::True == identifier.lexeme() { true } else if Keyword::False == identifier.lexeme() { false } else { return Err(identifier.error(CompileErrorKind::ExpectedKeyword { expected: vec![Keyword::True, Keyword::False], found: identifier, })); }; Ok(value) } /// Parse a setting fn parse_set(&mut self) -> CompileResult<'src, Set<'src>> { self.presume_keyword(Keyword::Set)?; let name = Name::from_identifier(self.presume(Identifier)?); let lexeme = name.lexeme(); let Some(keyword) = Keyword::from_lexeme(lexeme) else { return Err(name.error(CompileErrorKind::UnknownSetting { setting: name.lexeme(), })); }; let set_bool = match keyword { Keyword::AllowDuplicateRecipes => { Some(Setting::AllowDuplicateRecipes(self.parse_set_bool()?)) } Keyword::AllowDuplicateVariables => { Some(Setting::AllowDuplicateVariables(self.parse_set_bool()?)) } Keyword::DotenvLoad => Some(Setting::DotenvLoad(self.parse_set_bool()?)), Keyword::DotenvRequired => Some(Setting::DotenvRequired(self.parse_set_bool()?)), Keyword::Export => Some(Setting::Export(self.parse_set_bool()?)), Keyword::Fallback => Some(Setting::Fallback(self.parse_set_bool()?)), Keyword::IgnoreComments => Some(Setting::IgnoreComments(self.parse_set_bool()?)), Keyword::NoExitMessage => Some(Setting::NoExitMessage(self.parse_set_bool()?)), Keyword::PositionalArguments => Some(Setting::PositionalArguments(self.parse_set_bool()?)), Keyword::Quiet => Some(Setting::Quiet(self.parse_set_bool()?)), Keyword::Unstable => Some(Setting::Unstable(self.parse_set_bool()?)), Keyword::WindowsPowershell => Some(Setting::WindowsPowerShell(self.parse_set_bool()?)), _ => None, }; if let Some(value) = set_bool { return Ok(Set { name, value }); } self.expect(ColonEquals)?; let set_value = match keyword { Keyword::DotenvFilename => Some(Setting::DotenvFilename(self.parse_string_literal()?)), Keyword::DotenvPath => Some(Setting::DotenvPath(self.parse_string_literal()?)), Keyword::ScriptInterpreter => Some(Setting::ScriptInterpreter(self.parse_interpreter()?)), Keyword::Shell => Some(Setting::Shell(self.parse_interpreter()?)), Keyword::Tempdir => Some(Setting::Tempdir(self.parse_string_literal()?)), Keyword::WindowsShell => Some(Setting::WindowsShell(self.parse_interpreter()?)), Keyword::WorkingDirectory => Some(Setting::WorkingDirectory(self.parse_string_literal()?)), _ => None, }; if let Some(value) = set_value { return Ok(Set { name, value }); } Err(name.error(CompileErrorKind::UnknownSetting { setting: name.lexeme(), })) } /// Parse interpreter setting value, i.e., `['sh', '-eu']` fn parse_interpreter(&mut self) -> CompileResult<'src, Interpreter<'src>> { self.expect(BracketL)?; let command = self.parse_string_literal()?; let mut arguments = Vec::new(); if self.accepted(Comma)? { while !self.next_is(BracketR) { arguments.push(self.parse_string_literal()?); if !self.accepted(Comma)? { break; } } } self.expect(BracketR)?; Ok(Interpreter { arguments, command }) } /// Item attributes, i.e., `[macos]` or `[confirm: "warning!"]` fn parse_attributes(&mut self) -> CompileResult<'src, Option<(Token<'src>, AttributeSet<'src>)>> { let mut attributes = BTreeMap::new(); let mut discriminants = BTreeMap::new(); let mut token = None; while let Some(bracket) = self.accept(BracketL)? { token.get_or_insert(bracket); loop { let name = self.parse_name()?; let mut arguments = Vec::new(); if self.accepted(Colon)? { arguments.push(self.parse_string_literal()?); } else if self.accepted(ParenL)? { loop { arguments.push(self.parse_string_literal()?); if !self.accepted(Comma)? { break; } } self.expect(ParenR)?; } let attribute = Attribute::new(name, arguments)?; let first = attributes.get(&attribute).or_else(|| { if attribute.repeatable() { None } else { discriminants.get(&attribute.discriminant()) } }); if let Some(&first) = first { return Err(name.error(CompileErrorKind::DuplicateAttribute { attribute: name.lexeme(), first, })); } discriminants.insert(attribute.discriminant(), name.line); attributes.insert(attribute, name.line); if !self.accepted(Comma)? { break; } } self.expect(BracketR)?; self.expect_eol()?; } if attributes.is_empty() { Ok(None) } else { Ok(Some((token.unwrap(), attributes.into_keys().collect()))) } } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use CompileErrorKind::*; macro_rules! test { { name: $name:ident, text: $text:expr, tree: $tree:tt, } => { #[test] fn $name() { let text: String = $text.into(); let want = tree!($tree); test(&text, want); } } } fn test(text: &str, want: Tree) { let unindented = unindent(text); let tokens = Lexer::test_lex(&unindented).expect("lexing failed"); let justfile = Parser::parse(0, &[], None, &tokens, &PathBuf::new()).expect("parsing failed"); let have = justfile.tree(); if have != want { println!("parsed text: {unindented}"); println!("expected: {want}"); println!("but got: {have}"); println!("tokens: {tokens:?}"); panic!(); } } macro_rules! error { ( name: $name:ident, input: $input:expr, offset: $offset:expr, line: $line:expr, column: $column:expr, width: $width:expr, kind: $kind:expr, ) => { #[test] fn $name() { error($input, $offset, $line, $column, $width, $kind); } }; } fn error( src: &str, offset: usize, line: usize, column: usize, length: usize, kind: CompileErrorKind, ) { let tokens = Lexer::test_lex(src).expect("Lexing failed in parse test..."); match Parser::parse(0, &[], None, &tokens, &PathBuf::new()) { Ok(_) => panic!("Parsing unexpectedly succeeded"), Err(have) => { let want = CompileError { token: Token { kind: have.token.kind, src, offset, line, column, length, path: "justfile".as_ref(), }, kind: kind.into(), }; assert_eq!(have, want); } } } test! { name: empty, text: "", tree: (justfile), } test! { name: empty_multiline, text: " ", tree: (justfile), } test! { name: whitespace, text: " ", tree: (justfile), } test! { name: alias_single, text: "alias t := test", tree: (justfile (alias t test)), } test! { name: alias_with_attribute, text: "[private]\nalias t := test", tree: (justfile (alias t test)), } test! { name: alias_module_path, text: "alias fbb := foo::bar::baz", tree: (justfile (alias fbb (foo bar baz))), } test! { name: single_argument_attribute_shorthand, text: "[group: 'foo']\nbar:", tree: (justfile (recipe bar)), } test! { name: single_argument_attribute_shorthand_multiple_same_line, text: "[group: 'foo', group: 'bar']\nbaz:", tree: (justfile (recipe baz)), } test! { name: aliases_multiple, text: "alias t := test\nalias b := build", tree: ( justfile (alias t test) (alias b build) ), } test! { name: alias_equals, text: "alias t := test", tree: (justfile (alias t test) ), } test! { name: recipe_named_alias, text: r" [private] alias: echo 'echoing alias' ", tree: (justfile (recipe alias (body ("echo 'echoing alias'"))) ), } test! { name: export, text: r#"export x := "hello""#, tree: (justfile (assignment #export x "hello")), } test! { name: private_export, text: " [private] export x := 'hello' ", tree: (justfile (assignment #export x "hello")), } test! { name: export_equals, text: r#"export x := "hello""#, tree: (justfile (assignment #export x "hello") ), } test! { name: assignment, text: r#"x := "hello""#, tree: (justfile (assignment x "hello")), } test! { name: private_assignment, text: " [private] x := 'hello' ", tree: (justfile (assignment x "hello")), } test! { name: assignment_equals, text: r#"x := "hello""#, tree: (justfile (assignment x "hello") ), } test! { name: backtick, text: "x := `hello`", tree: (justfile (assignment x (backtick "hello"))), } test! { name: variable, text: "x := y", tree: (justfile (assignment x y)), } test! { name: group, text: "x := (y)", tree: (justfile (assignment x (y))), } test! { name: addition_single, text: "x := a + b", tree: (justfile (assignment x (+ a b))), } test! { name: addition_chained, text: "x := a + b + c", tree: (justfile (assignment x (+ a (+ b c)))), } test! { name: call_one_arg, text: "x := env_var(y)", tree: (justfile (assignment x (call env_var y))), } test! { name: call_multiple_args, text: "x := env_var_or_default(y, z)", tree: (justfile (assignment x (call env_var_or_default y z))), } test! { name: call_trailing_comma, text: "x := env_var(y,)", tree: (justfile (assignment x (call env_var y))), } test! { name: recipe, text: "foo:", tree: (justfile (recipe foo)), } test! { name: recipe_multiple, text: " foo: bar: baz: ", tree: (justfile (recipe foo) (recipe bar) (recipe baz)), } test! { name: recipe_quiet, text: "@foo:", tree: (justfile (recipe #quiet foo)), } test! { name: recipe_parameter_single, text: "foo bar:", tree: (justfile (recipe foo (params (bar)))), } test! { name: recipe_parameter_multiple, text: "foo bar baz:", tree: (justfile (recipe foo (params (bar) (baz)))), } test! { name: recipe_default_single, text: r#"foo bar="baz":"#, tree: (justfile (recipe foo (params (bar "baz")))), } test! { name: recipe_default_multiple, text: r#"foo bar="baz" bob="biz":"#, tree: (justfile (recipe foo (params (bar "baz") (bob "biz")))), } test! { name: recipe_plus_variadic, text: r"foo +bar:", tree: (justfile (recipe foo (params +(bar)))), } test! { name: recipe_star_variadic, text: r"foo *bar:", tree: (justfile (recipe foo (params *(bar)))), } test! { name: recipe_variadic_string_default, text: r#"foo +bar="baz":"#, tree: (justfile (recipe foo (params +(bar "baz")))), } test! { name: recipe_variadic_variable_default, text: r"foo +bar=baz:", tree: (justfile (recipe foo (params +(bar baz)))), } test! { name: recipe_variadic_addition_group_default, text: r"foo +bar=(baz + bob):", tree: (justfile (recipe foo (params +(bar ((+ baz bob)))))), } test! { name: recipe_dependency_single, text: "foo: bar", tree: (justfile (recipe foo (deps bar))), } test! { name: recipe_dependency_multiple, text: "foo: bar baz", tree: (justfile (recipe foo (deps bar baz))), } test! { name: recipe_dependency_parenthesis, text: "foo: (bar)", tree: (justfile (recipe foo (deps bar))), } test! { name: recipe_dependency_argument_string, text: "foo: (bar 'baz')", tree: (justfile (recipe foo (deps (bar "baz")))), } test! { name: recipe_dependency_argument_identifier, text: "foo: (bar baz)", tree: (justfile (recipe foo (deps (bar baz)))), } test! { name: recipe_dependency_argument_concatenation, text: "foo: (bar 'a' + 'b' 'c' + 'd')", tree: (justfile (recipe foo (deps (bar (+ 'a' 'b') (+ 'c' 'd'))))), } test! { name: recipe_subsequent, text: "foo: && bar", tree: (justfile (recipe foo (sups bar))), } test! { name: recipe_line_single, text: "foo:\n bar", tree: (justfile (recipe foo (body ("bar")))), } test! { name: recipe_line_multiple, text: "foo:\n bar\n baz\n {{\"bob\"}}biz", tree: (justfile (recipe foo (body ("bar") ("baz") (("bob") "biz")))), } test! { name: recipe_line_interpolation, text: "foo:\n bar{{\"bob\"}}biz", tree: (justfile (recipe foo (body ("bar" ("bob") "biz")))), } test! { name: comment, text: "# foo", tree: (justfile (comment "# foo")), } test! { name: comment_before_alias, text: "# foo\nalias x := y", tree: (justfile (comment "# foo") (alias x y)), } test! { name: comment_after_alias, text: "alias x := y # foo", tree: (justfile (alias x y)), } test! { name: comment_assignment, text: "x := y # foo", tree: (justfile (assignment x y)), } test! { name: comment_export, text: "export x := y # foo", tree: (justfile (assignment #export x y)), } test! { name: comment_recipe, text: "foo: # bar", tree: (justfile (recipe foo)), } test! { name: comment_recipe_dependencies, text: "foo: bar # baz", tree: (justfile (recipe foo (deps bar))), } test! { name: doc_comment_single, text: " # foo bar: ", tree: (justfile (recipe "foo" bar)), } test! { name: doc_comment_recipe_clear, text: " # foo bar: baz: ", tree: (justfile (recipe "foo" bar) (recipe baz)), } test! { name: doc_comment_middle, text: " bar: # foo baz: ", tree: (justfile (recipe bar) (recipe "foo" baz)), } test! { name: doc_comment_assignment_clear, text: " # foo x := y bar: ", tree: (justfile (comment "# foo") (assignment x y) (recipe bar)), } test! { name: doc_comment_empty_line_clear, text: " # foo bar: ", tree: (justfile (comment "# foo") (recipe bar)), } test! { name: string_escape_tab, text: r#"x := "foo\tbar""#, tree: (justfile (assignment x "foo\tbar")), } test! { name: string_escape_newline, text: r#"x := "foo\nbar""#, tree: (justfile (assignment x "foo\nbar")), } test! { name: string_escape_suppress_newline, text: r#" x := "foo\ bar" "#, tree: (justfile (assignment x "foobar")), } test! { name: string_escape_carriage_return, text: r#"x := "foo\rbar""#, tree: (justfile (assignment x "foo\rbar")), } test! { name: string_escape_slash, text: r#"x := "foo\\bar""#, tree: (justfile (assignment x "foo\\bar")), } test! { name: string_escape_quote, text: r#"x := "foo\"bar""#, tree: (justfile (assignment x "foo\"bar")), } test! { name: indented_string_raw_with_dedent, text: " x := ''' foo\\t bar\\n ''' ", tree: (justfile (assignment x "foo\\t\nbar\\n\n")), } test! { name: indented_string_raw_no_dedent, text: " x := ''' foo\\t bar\\n ''' ", tree: (justfile (assignment x "foo\\t\n bar\\n\n")), } test! { name: indented_string_cooked, text: r#" x := """ \tfoo\t \tbar\n """ "#, tree: (justfile (assignment x "\tfoo\t\n\tbar\n\n")), } test! { name: indented_string_cooked_no_dedent, text: r#" x := """ \tfoo\t \tbar\n """ "#, tree: (justfile (assignment x "\tfoo\t\n \tbar\n\n")), } test! { name: indented_backtick, text: r" x := ``` \tfoo\t \tbar\n ``` ", tree: (justfile (assignment x (backtick "\\tfoo\\t\n\\tbar\\n\n"))), } test! { name: indented_backtick_no_dedent, text: r" x := ``` \tfoo\t \tbar\n ``` ", tree: (justfile (assignment x (backtick "\\tfoo\\t\n \\tbar\\n\n"))), } test! { name: recipe_variadic_with_default_after_default, text: r" f a=b +c=d: ", tree: (justfile (recipe f (params (a b) +(c d)))), } test! { name: parameter_default_concatenation_variable, text: r#" x := "10" f y=(`echo hello` + x) +z="foo": "#, tree: (justfile (assignment x "10") (recipe f (params (y ((+ (backtick "echo hello") x))) +(z "foo"))) ), } test! { name: parameter_default_multiple, text: r#" x := "10" f y=(`echo hello` + x) +z=("foo" + "bar"): "#, tree: (justfile (assignment x "10") (recipe f (params (y ((+ (backtick "echo hello") x))) +(z ((+ "foo" "bar"))))) ), } test! { name: parse_raw_string_default, text: r" foo a='b\t': ", tree: (justfile (recipe foo (params (a "b\\t")))), } test! { name: parse_alias_after_target, text: r" foo: echo a alias f := foo ", tree: (justfile (recipe foo (body ("echo a"))) (alias f foo) ), } test! { name: parse_alias_before_target, text: " alias f := foo foo: echo a ", tree: (justfile (alias f foo) (recipe foo (body ("echo a"))) ), } test! { name: parse_alias_with_comment, text: " alias f := foo #comment foo: echo a ", tree: (justfile (alias f foo) (recipe foo (body ("echo a"))) ), } test! { name: parse_assignment_with_comment, text: " f := foo #comment foo: echo a ", tree: (justfile (assignment f foo) (recipe foo (body ("echo a"))) ), } test! { name: parse_complex, text: " x: y: z: foo := \"xx\" bar := foo goodbye := \"y\" hello a b c : x y z #hello #! blah #blarg {{ foo + bar}}abc{{ goodbye\t + \"x\" }}xyz 1 2 3 ", tree: (justfile (recipe x) (recipe y) (recipe z) (assignment foo "xx") (assignment bar foo) (assignment goodbye "y") (recipe hello (params (a) (b) (c)) (deps x y z) (body ("#! blah") ("#blarg") (((+ foo bar)) "abc" ((+ goodbye "x")) "xyz") ("1") ("2") ("3") ) ) ), } test! { name: parse_shebang, text: " practicum := 'hello' install: \t#!/bin/sh \tif [[ -f {{practicum}} ]]; then \t\treturn \tfi ", tree: (justfile (assignment practicum "hello") (recipe install (body ("#!/bin/sh") ("if [[ -f " (practicum) " ]]; then") ("\treturn") ("fi") ) ) ), } test! { name: parse_simple_shebang, text: "a:\n #!\n print(1)", tree: (justfile (recipe a (body ("#!") (" print(1)"))) ), } test! { name: parse_assignments, text: r#" a := "0" c := a + b + a + b b := "1" "#, tree: (justfile (assignment a "0") (assignment c (+ a (+ b (+ a b)))) (assignment b "1") ), } test! { name: parse_assignment_backticks, text: " a := `echo hello` c := a + b + a + b b := `echo goodbye` ", tree: (justfile (assignment a (backtick "echo hello")) (assignment c (+ a (+ b (+ a b)))) (assignment b (backtick "echo goodbye")) ), } test! { name: parse_interpolation_backticks, text: r#" a: echo {{ `echo hello` + "blarg" }} {{ `echo bob` }} "#, tree: (justfile (recipe a (body ("echo " ((+ (backtick "echo hello") "blarg")) " " ((backtick "echo bob")))) ) ), } test! { name: eof_test, text: "x:\ny:\nz:\na b c: x y z", tree: (justfile (recipe x) (recipe y) (recipe z) (recipe a (params (b) (c)) (deps x y z)) ), } test! { name: string_quote_escape, text: r#"a := "hello\"""#, tree: (justfile (assignment a "hello\"") ), } test! { name: string_escapes, text: r#"a := "\n\t\r\"\\""#, tree: (justfile (assignment a "\n\t\r\"\\")), } test! { name: parameters, text: " a b c: {{b}} {{c}} ", tree: (justfile (recipe a (params (b) (c)) (body ((b) " " (c))))), } test! { name: unary_functions, text: " x := arch() a: {{os()}} {{os_family()}} ", tree: (justfile (assignment x (call arch)) (recipe a (body (((call os)) " " ((call os_family))))) ), } test! { name: env_functions, text: r#" x := env_var('foo',) a: {{env_var_or_default('foo' + 'bar', 'baz',)}} {{env_var(env_var("baz"))}} "#, tree: (justfile (assignment x (call env_var "foo")) (recipe a (body ( ((call env_var_or_default (+ "foo" "bar") "baz")) " " ((call env_var (call env_var "baz"))) ) ) ) ), } test! { name: parameter_default_string, text: r#" f x="abc": "#, tree: (justfile (recipe f (params (x "abc")))), } test! { name: parameter_default_raw_string, text: r" f x='abc': ", tree: (justfile (recipe f (params (x "abc")))), } test! { name: parameter_default_backtick, text: " f x=`echo hello`: ", tree: (justfile (recipe f (params (x (backtick "echo hello")))) ), } test! { name: parameter_default_concatenation_string, text: r#" f x=(`echo hello` + "foo"): "#, tree: (justfile (recipe f (params (x ((+ (backtick "echo hello") "foo")))))), } test! { name: concatenation_in_group, text: "x := ('0' + '1')", tree: (justfile (assignment x ((+ "0" "1")))), } test! { name: string_in_group, text: "x := ('0' )", tree: (justfile (assignment x ("0"))), } test! { name: escaped_dos_newlines, text: " @spam:\r \t{ \\\r \t\tfiglet test; \\\r \t\tcargo build --color always 2>&1; \\\r \t\tcargo test --color always -- --color always 2>&1; \\\r \t} | less\r ", tree: (justfile (recipe #quiet spam (body ("{ \\") ("\tfiglet test; \\") ("\tcargo build --color always 2>&1; \\") ("\tcargo test --color always -- --color always 2>&1; \\") ("} | less") ) ) ), } test! { name: empty_body, text: "a:", tree: (justfile (recipe a)), } test! { name: single_line_body, text: "a:\n foo", tree: (justfile (recipe a (body ("foo")))), } test! { name: trimmed_body, text: "a:\n foo\n \n \n \nb:\n ", tree: (justfile (recipe a (body ("foo"))) (recipe b)), } test! { name: set_export_implicit, text: "set export", tree: (justfile (set export true)), } test! { name: set_export_true, text: "set export := true", tree: (justfile (set export true)), } test! { name: set_export_false, text: "set export := false", tree: (justfile (set export false)), } test! { name: set_dotenv_load_implicit, text: "set dotenv-load", tree: (justfile (set dotenv_load true)), } test! { name: set_allow_duplicate_recipes_implicit, text: "set allow-duplicate-recipes", tree: (justfile (set allow_duplicate_recipes true)), } test! { name: set_allow_duplicate_variables_implicit, text: "set allow-duplicate-variables", tree: (justfile (set allow_duplicate_variables true)), } test! { name: set_dotenv_load_true, text: "set dotenv-load := true", tree: (justfile (set dotenv_load true)), } test! { name: set_dotenv_load_false, text: "set dotenv-load := false", tree: (justfile (set dotenv_load false)), } test! { name: set_positional_arguments_implicit, text: "set positional-arguments", tree: (justfile (set positional_arguments true)), } test! { name: set_positional_arguments_true, text: "set positional-arguments := true", tree: (justfile (set positional_arguments true)), } test! { name: set_quiet_implicit, text: "set quiet", tree: (justfile (set quiet true)), } test! { name: set_quiet_true, text: "set quiet := true", tree: (justfile (set quiet true)), } test! { name: set_quiet_false, text: "set quiet := false", tree: (justfile (set quiet false)), } test! { name: set_positional_arguments_false, text: "set positional-arguments := false", tree: (justfile (set positional_arguments false)), } test! { name: set_shell_no_arguments, text: "set shell := ['tclsh']", tree: (justfile (set shell "tclsh")), } test! { name: set_shell_no_arguments_cooked, text: "set shell := [\"tclsh\"]", tree: (justfile (set shell "tclsh")), } test! { name: set_shell_no_arguments_trailing_comma, text: "set shell := ['tclsh',]", tree: (justfile (set shell "tclsh")), } test! { name: set_shell_with_one_argument, text: "set shell := ['bash', '-cu']", tree: (justfile (set shell "bash" "-cu")), } test! { name: set_shell_with_one_argument_trailing_comma, text: "set shell := ['bash', '-cu',]", tree: (justfile (set shell "bash" "-cu")), } test! { name: set_shell_with_two_arguments, text: "set shell := ['bash', '-cu', '-l']", tree: (justfile (set shell "bash" "-cu" "-l")), } test! { name: set_windows_powershell_implicit, text: "set windows-powershell", tree: (justfile (set windows_powershell true)), } test! { name: set_windows_powershell_true, text: "set windows-powershell := true", tree: (justfile (set windows_powershell true)), } test! { name: set_windows_powershell_false, text: "set windows-powershell := false", tree: (justfile (set windows_powershell false)), } test! { name: set_working_directory, text: "set working-directory := 'foo'", tree: (justfile (set working_directory "foo")), } test! { name: conditional, text: "a := if b == c { d } else { e }", tree: (justfile (assignment a (if b == c d e))), } test! { name: conditional_inverted, text: "a := if b != c { d } else { e }", tree: (justfile (assignment a (if b != c d e))), } test! { name: conditional_concatenations, text: "a := if b0 + b1 == c0 + c1 { d0 + d1 } else { e0 + e1 }", tree: (justfile (assignment a (if (+ b0 b1) == (+ c0 c1) (+ d0 d1) (+ e0 e1)))), } test! { name: conditional_nested_lhs, text: "a := if if b == c { d } else { e } == c { d } else { e }", tree: (justfile (assignment a (if (if b == c d e) == c d e))), } test! { name: conditional_nested_rhs, text: "a := if c == if b == c { d } else { e } { d } else { e }", tree: (justfile (assignment a (if c == (if b == c d e) d e))), } test! { name: conditional_nested_then, text: "a := if b == c { if b == c { d } else { e } } else { e }", tree: (justfile (assignment a (if b == c (if b == c d e) e))), } test! { name: conditional_nested_otherwise, text: "a := if b == c { d } else { if b == c { d } else { e } }", tree: (justfile (assignment a (if b == c d (if b == c d e)))), } test! { name: import, text: "import \"some/file/path.txt\" \n", tree: (justfile (import "some/file/path.txt")), } test! { name: optional_import, text: "import? \"some/file/path.txt\" \n", tree: (justfile (import ? "some/file/path.txt")), } test! { name: module_with, text: "mod foo", tree: (justfile (mod foo )), } test! { name: optional_module, text: "mod? foo", tree: (justfile (mod ? foo)), } test! { name: module_with_path, text: "mod foo \"some/file/path.txt\" \n", tree: (justfile (mod foo "some/file/path.txt")), } test! { name: optional_module_with_path, text: "mod? foo \"some/file/path.txt\" \n", tree: (justfile (mod ? foo "some/file/path.txt")), } test! { name: assert, text: "a := assert(foo == \"bar\", \"error\")", tree: (justfile (assignment a (assert foo == "bar" "error"))), } test! { name: assert_conditional_condition, text: "foo := assert(if a != b { c } else { d } == \"abc\", \"error\")", tree: (justfile (assignment foo (assert (if a != b c d) == "abc" "error"))), } error! { name: alias_syntax_multiple_rhs, input: "alias foo := bar baz", offset: 17, line: 0, column: 17, width: 3, kind: UnexpectedToken { expected: vec![ColonColon, Comment, Eof, Eol], found: Identifier }, } error! { name: alias_syntax_no_rhs, input: "alias foo := \n", offset: 13, line: 0, column: 13, width: 1, kind: UnexpectedToken {expected: vec![Identifier], found:Eol}, } error! { name: alias_syntax_colon_end, input: "alias foo := bar::\n", offset: 18, line: 0, column: 18, width: 1, kind: UnexpectedToken {expected: vec![Identifier], found:Eol}, } error! { name: alias_syntax_single_colon, input: "alias foo := bar:baz", offset: 16, line: 0, column: 16, width: 1, kind: UnexpectedToken {expected: vec![ColonColon, Comment, Eof, Eol], found:Colon}, } error! { name: missing_colon, input: "a b c\nd e f", offset: 5, line: 0, column: 5, width: 1, kind: UnexpectedToken{ expected: vec![Asterisk, Colon, Dollar, Equals, Identifier, Plus], found: Eol }, } error! { name: missing_default_eol, input: "hello arg=\n", offset: 10, line: 0, column: 10, width: 1, kind: UnexpectedToken { expected: vec![ Backtick, Identifier, ParenL, StringToken, ], found: Eol }, } error! { name: missing_default_eof, input: "hello arg=", offset: 10, line: 0, column: 10, width: 0, kind: UnexpectedToken { expected: vec![ Backtick, Identifier, ParenL, StringToken, ], found: Eof, }, } error! { name: missing_eol, input: "a b c: z =", offset: 9, line: 0, column: 9, width: 1, kind: UnexpectedToken{ expected: vec![AmpersandAmpersand, Comment, Eof, Eol, Identifier, ParenL], found: Equals }, } error! { name: unexpected_brace, input: "{{", offset: 0, line: 0, column: 0, width: 1, kind: UnexpectedToken { expected: vec![At, BracketL, Comment, Eof, Eol, Identifier], found: BraceL, }, } error! { name: unclosed_parenthesis_in_expression, input: "x := foo(", offset: 9, line: 0, column: 9, width: 0, kind: UnexpectedToken{ expected: vec![ Backtick, Identifier, ParenL, ParenR, Slash, StringToken, ], found: Eof, }, } error! { name: unclosed_parenthesis_in_interpolation, input: "a:\n echo {{foo(}}", offset: 15, line: 1, column: 12, width: 2, kind: UnexpectedToken{ expected: vec![ Backtick, Identifier, ParenL, ParenR, Slash, StringToken, ], found: InterpolationEnd, }, } error! { name: plus_following_parameter, input: "a b c+:", offset: 6, line: 0, column: 6, width: 1, kind: UnexpectedToken{expected: vec![Dollar, Identifier], found: Colon}, } error! { name: invalid_escape_sequence, input: r#"foo := "\b""#, offset: 7, line: 0, column: 7, width: 4, kind: InvalidEscapeSequence{character: 'b'}, } error! { name: bad_export, input: "export a", offset: 8, line: 0, column: 8, width: 0, kind: UnexpectedToken { expected: vec![Asterisk, Colon, Dollar, Equals, Identifier, Plus], found: Eof }, } error! { name: parameter_follows_variadic_parameter, input: "foo +a b:", offset: 7, line: 0, column: 7, width: 1, kind: ParameterFollowsVariadicParameter{parameter: "b"}, } error! { name: parameter_after_variadic, input: "foo +a bbb:", offset: 7, line: 0, column: 7, width: 3, kind: ParameterFollowsVariadicParameter{parameter: "bbb"}, } error! { name: concatenation_in_default, input: "foo a=c+d e:", offset: 10, line: 0, column: 10, width: 1, kind: ParameterFollowsVariadicParameter{parameter: "e"}, } error! { name: set_shell_empty, input: "set shell := []", offset: 14, line: 0, column: 14, width: 1, kind: UnexpectedToken { expected: vec![ Identifier, StringToken, ], found: BracketR, }, } error! { name: set_shell_non_literal_first, input: "set shell := ['bar' + 'baz']", offset: 20, line: 0, column: 20, width: 1, kind: UnexpectedToken { expected: vec![BracketR, Comma], found: Plus, }, } error! { name: set_shell_non_literal_second, input: "set shell := ['biz', 'bar' + 'baz']", offset: 27, line: 0, column: 27, width: 1, kind: UnexpectedToken { expected: vec![BracketR, Comma], found: Plus, }, } error! { name: set_shell_bad_comma, input: "set shell := ['bash',", offset: 21, line: 0, column: 21, width: 0, kind: UnexpectedToken { expected: vec![ BracketR, Identifier, StringToken, ], found: Eof, }, } error! { name: set_shell_bad, input: "set shell := ['bash'", offset: 20, line: 0, column: 20, width: 0, kind: UnexpectedToken { expected: vec![BracketR, Comma], found: Eof, }, } error! { name: empty_attribute, input: "[]\nsome_recipe:\n @exit 3", offset: 1, line: 0, column: 1, width: 1, kind: UnexpectedToken { expected: vec![Identifier], found: BracketR, }, } error! { name: unknown_attribute, input: "[unknown]\nsome_recipe:\n @exit 3", offset: 1, line: 0, column: 1, width: 7, kind: UnknownAttribute { attribute: "unknown" }, } error! { name: set_unknown, input: "set shall := []", offset: 4, line: 0, column: 4, width: 5, kind: UnknownSetting { setting: "shall", }, } error! { name: set_shell_non_string, input: "set shall := []", offset: 4, line: 0, column: 4, width: 5, kind: UnknownSetting { setting: "shall", }, } error! { name: unknown_function, input: "a := foo()", offset: 5, line: 0, column: 5, width: 3, kind: UnknownFunction{function: "foo"}, } error! { name: unknown_function_in_interpolation, input: "a:\n echo {{bar()}}", offset: 11, line: 1, column: 8, width: 3, kind: UnknownFunction{function: "bar"}, } error! { name: unknown_function_in_default, input: "a f=baz():", offset: 4, line: 0, column: 4, width: 3, kind: UnknownFunction{function: "baz"}, } error! { name: function_argument_count_nullary, input: "x := arch('foo')", offset: 5, line: 0, column: 5, width: 4, kind: FunctionArgumentCountMismatch { function: "arch", found: 1, expected: 0..=0, }, } error! { name: function_argument_count_unary, input: "x := env_var()", offset: 5, line: 0, column: 5, width: 7, kind: FunctionArgumentCountMismatch { function: "env_var", found: 0, expected: 1..=1, }, } error! { name: function_argument_count_too_high_unary_opt, input: "x := env('foo', 'foo', 'foo')", offset: 5, line: 0, column: 5, width: 3, kind: FunctionArgumentCountMismatch { function: "env", found: 3, expected: 1..=2, }, } error! { name: function_argument_count_too_low_unary_opt, input: "x := env()", offset: 5, line: 0, column: 5, width: 3, kind: FunctionArgumentCountMismatch { function: "env", found: 0, expected: 1..=2, }, } error! { name: function_argument_count_binary, input: "x := env_var_or_default('foo')", offset: 5, line: 0, column: 5, width: 18, kind: FunctionArgumentCountMismatch { function: "env_var_or_default", found: 1, expected: 2..=2, }, } error! { name: function_argument_count_binary_plus, input: "x := join('foo')", offset: 5, line: 0, column: 5, width: 4, kind: FunctionArgumentCountMismatch { function: "join", found: 1, expected: 2..=usize::MAX, }, } error! { name: function_argument_count_ternary, input: "x := replace('foo')", offset: 5, line: 0, column: 5, width: 7, kind: FunctionArgumentCountMismatch { function: "replace", found: 1, expected: 3..=3, }, } } just-1.40.0/src/platform.rs000064400000000000000000000062441046102023000136620ustar 00000000000000use super::*; pub(crate) struct Platform; #[cfg(unix)] impl PlatformInterface for Platform { fn make_shebang_command( path: &Path, working_directory: Option<&Path>, _shebang: Shebang, ) -> Result { // shebang scripts can be executed directly on unix let mut command = Command::new(path); if let Some(working_directory) = working_directory { command.current_dir(working_directory); } Ok(command) } fn set_execute_permission(path: &Path) -> io::Result<()> { use std::os::unix::fs::PermissionsExt; // get current permissions let mut permissions = fs::metadata(path)?.permissions(); // set the execute bit let current_mode = permissions.mode(); permissions.set_mode(current_mode | 0o100); // set the new permissions fs::set_permissions(path, permissions) } fn signal_from_exit_status(exit_status: ExitStatus) -> Option { use std::os::unix::process::ExitStatusExt; exit_status.signal() } fn convert_native_path(_working_directory: &Path, path: &Path) -> FunctionResult { path .to_str() .map(str::to_string) .ok_or_else(|| String::from("Error getting current directory: unicode decode error")) } } #[cfg(windows)] impl PlatformInterface for Platform { fn make_shebang_command( path: &Path, working_directory: Option<&Path>, shebang: Shebang, ) -> Result { use std::borrow::Cow; // If the path contains forward slashes… let command = if shebang.interpreter.contains('/') { // …translate path to the interpreter from unix style to windows style. let mut cygpath = Command::new("cygpath"); if let Some(working_directory) = working_directory { cygpath.current_dir(working_directory); } cygpath.arg("--windows"); cygpath.arg(shebang.interpreter); Cow::Owned(output(cygpath)?) } else { // …otherwise use it as-is. Cow::Borrowed(shebang.interpreter) }; let mut cmd = Command::new(command.as_ref()); if let Some(working_directory) = working_directory { cmd.current_dir(working_directory); } if let Some(argument) = shebang.argument { cmd.arg(argument); } cmd.arg(path); Ok(cmd) } fn set_execute_permission(_path: &Path) -> io::Result<()> { // it is not necessary to set an execute permission on a script on windows, so // this is a nop Ok(()) } fn signal_from_exit_status(_exit_status: process::ExitStatus) -> Option { // The rust standard library does not expose a way to extract a signal from a // windows process exit status, so just return None None } fn convert_native_path(working_directory: &Path, path: &Path) -> FunctionResult { // Translate path from windows style to unix style let mut cygpath = Command::new("cygpath"); cygpath.current_dir(working_directory); cygpath.arg("--unix"); cygpath.arg(path); match output(cygpath) { Ok(shell_path) => Ok(shell_path), Err(_) => path .to_str() .map(str::to_string) .ok_or_else(|| String::from("Error getting current directory: unicode decode error")), } } } just-1.40.0/src/platform_interface.rs000064400000000000000000000013621046102023000156760ustar 00000000000000use super::*; pub(crate) trait PlatformInterface { /// Translate a path from a "native" path to a path the interpreter expects fn convert_native_path(working_directory: &Path, path: &Path) -> FunctionResult; /// Construct a command equivalent to running the script at `path` with the /// shebang line `shebang` fn make_shebang_command( path: &Path, working_directory: Option<&Path>, shebang: Shebang, ) -> Result; /// Set the execute permission on the file pointed to by `path` fn set_execute_permission(path: &Path) -> io::Result<()>; /// Extract the signal from a process exit status, if it was terminated by a /// signal fn signal_from_exit_status(exit_status: ExitStatus) -> Option; } just-1.40.0/src/position.rs000064400000000000000000000002561046102023000136770ustar 00000000000000/// Source position #[derive(Copy, Clone, PartialEq, Debug)] pub(crate) struct Position { pub(crate) column: usize, pub(crate) line: usize, pub(crate) offset: usize, } just-1.40.0/src/positional.rs000064400000000000000000000137741046102023000142250ustar 00000000000000use super::*; /// A struct containing the parsed representation of positional command-line /// arguments, i.e. arguments that are not flags, options, or the subcommand. /// /// The DSL of positional arguments is fairly complex and mostly accidental. /// There are three possible components: overrides, a search directory, and the /// rest: /// /// - Overrides are of the form `NAME=.*` /// /// - After overrides comes a single optional search directory argument. This is /// either '.', '..', or an argument that contains a `/`. /// /// If the argument contains a `/`, everything before and including the slash /// is the search directory, and everything after is added to the rest. /// /// - Everything else is an argument. /// /// Overrides set the values of top-level variables in the justfile being /// invoked and are a convenient way to override settings. /// /// For modes that do not take other arguments, the search directory argument /// determines where to begin searching for the justfile. This allows command /// lines like `just -l ..` and `just ../build` to find the same justfile. /// /// For modes that do take other arguments, the search argument is simply /// prepended to rest. #[cfg_attr(test, derive(PartialEq, Eq, Debug))] pub struct Positional { /// Everything else pub arguments: Vec, /// Overrides from values of the form `[a-zA-Z_][a-zA-Z0-9_-]*=.*` pub overrides: Vec<(String, String)>, /// An argument equal to '.', '..', or ending with `/` pub search_directory: Option, } impl Positional { pub fn from_values<'values>(values: Option>) -> Self { let mut overrides = Vec::new(); let mut search_directory = None; let mut arguments = Vec::new(); if let Some(values) = values { for value in values { if search_directory.is_none() && arguments.is_empty() { if let Some(o) = Self::override_from_value(value) { overrides.push(o); } else if value == "." || value == ".." { search_directory = Some(value.to_owned()); } else if let Some(i) = value.rfind('/') { let (dir, tail) = value.split_at(i + 1); search_directory = Some(dir.to_owned()); if !tail.is_empty() { arguments.push(tail.to_owned()); } } else { arguments.push(value.to_owned()); } } else { arguments.push(value.to_owned()); } } } Self { arguments, overrides, search_directory, } } /// Parse an override from a value of the form `NAME=.*`. fn override_from_value(value: &str) -> Option<(String, String)> { let equals = value.find('=')?; let (identifier, equals_value) = value.split_at(equals); // exclude `=` from value let value = &equals_value[1..]; if Lexer::is_identifier(identifier) { Some((identifier.to_owned(), value.to_owned())) } else { None } } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; macro_rules! test { { name: $name:ident, values: $vals:expr, overrides: $overrides:expr, search_directory: $search_directory:expr, arguments: $arguments:expr, } => { #[test] fn $name() { assert_eq! ( Positional::from_values(Some($vals.iter().cloned())), Positional { overrides: $overrides .iter() .cloned() .map(|(key, value): (&str, &str)| (key.to_owned(), value.to_owned())) .collect(), search_directory: $search_directory.map(str::to_owned), arguments: $arguments.iter().cloned().map(str::to_owned).collect(), }, ) } } } test! { name: no_values, values: [], overrides: [], search_directory: None, arguments: [], } test! { name: arguments_only, values: ["foo", "bar"], overrides: [], search_directory: None, arguments: ["foo", "bar"], } test! { name: all_overrides, values: ["foo=bar", "bar=foo"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: None, arguments: [], } test! { name: override_not_name, values: ["foo=bar", "bar.=foo"], overrides: [("foo", "bar")], search_directory: None, arguments: ["bar.=foo"], } test! { name: no_overrides, values: ["the-dir/", "baz", "bzzd"], overrides: [], search_directory: Some("the-dir/"), arguments: ["baz", "bzzd"], } test! { name: no_search_directory, values: ["foo=bar", "bar=foo", "baz", "bzzd"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: None, arguments: ["baz", "bzzd"], } test! { name: no_arguments, values: ["foo=bar", "bar=foo", "the-dir/"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: Some("the-dir/"), arguments: [], } test! { name: all_dot, values: ["foo=bar", "bar=foo", ".", "garnor"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: Some("."), arguments: ["garnor"], } test! { name: all_dot_dot, values: ["foo=bar", "bar=foo", "..", "garnor"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: Some(".."), arguments: ["garnor"], } test! { name: all_slash, values: ["foo=bar", "bar=foo", "/", "garnor"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: Some("/"), arguments: ["garnor"], } test! { name: search_directory_after_argument, values: ["foo=bar", "bar=foo", "baz", "bzzd", "bar/"], overrides: [("foo", "bar"), ("bar", "foo")], search_directory: None, arguments: ["baz", "bzzd", "bar/"], } test! { name: override_after_search_directory, values: ["..", "a=b"], overrides: [], search_directory: Some(".."), arguments: ["a=b"], } test! { name: override_after_argument, values: ["a", "a=b"], overrides: [], search_directory: None, arguments: ["a", "a=b"], } } just-1.40.0/src/ran.rs000064400000000000000000000007251046102023000126140ustar 00000000000000use super::*; #[derive(Default)] pub(crate) struct Ran<'src>(BTreeMap, BTreeSet>>); impl<'src> Ran<'src> { pub(crate) fn has_run(&self, recipe: &Namepath<'src>, arguments: &[String]) -> bool { self .0 .get(recipe) .is_some_and(|ran| ran.contains(arguments)) } pub(crate) fn ran(&mut self, recipe: &Namepath<'src>, arguments: Vec) { self.0.entry(recipe.clone()).or_default().insert(arguments); } } just-1.40.0/src/range_ext.rs000064400000000000000000000040501046102023000140030ustar 00000000000000use super::*; pub(crate) trait RangeExt { fn display(&self) -> DisplayRange<&Self> { DisplayRange(self) } fn range_contains(&self, i: &T) -> bool; } pub(crate) struct DisplayRange(T); impl Display for DisplayRange<&RangeInclusive> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.0.start() == self.0.end() { write!(f, "{}", self.0.start())?; } else if *self.0.end() == usize::MAX { write!(f, "{} or more", self.0.start())?; } else { write!(f, "{} to {}", self.0.start(), self.0.end())?; } Ok(()) } } impl RangeExt for Range where T: PartialOrd, { fn range_contains(&self, i: &T) -> bool { i >= &self.start && i < &self.end } } impl RangeExt for RangeInclusive where T: PartialOrd, { fn range_contains(&self, i: &T) -> bool { i >= self.start() && i <= self.end() } } #[cfg(test)] mod tests { use super::*; #[test] fn exclusive() { assert!(!(0..0).range_contains(&0)); assert!(!(1..10).range_contains(&0)); assert!(!(1..10).range_contains(&10)); assert!(!(1..10).range_contains(&0)); assert!((0..1).range_contains(&0)); assert!((10..20).range_contains(&15)); } #[test] fn inclusive() { assert!(!(0..=10).range_contains(&11)); assert!(!(1..=10).range_contains(&0)); assert!(!(5..=10).range_contains(&4)); assert!((0..=0).range_contains(&0)); assert!((0..=1).range_contains(&0)); assert!((0..=10).range_contains(&0)); assert!((0..=10).range_contains(&10)); assert!((0..=10).range_contains(&7)); assert!((1..=10).range_contains(&10)); assert!((10..=20).range_contains(&15)); } #[test] fn display() { assert!(!(1..1).contains(&1)); assert!((1..1).is_empty()); assert!((5..5).is_empty()); assert_eq!((0..=0).display().to_string(), "0"); assert_eq!((1..=1).display().to_string(), "1"); assert_eq!((5..=5).display().to_string(), "5"); assert_eq!((5..=9).display().to_string(), "5 to 9"); assert_eq!((1..=usize::MAX).display().to_string(), "1 or more"); } } just-1.40.0/src/recipe.rs000064400000000000000000000350651046102023000133100ustar 00000000000000use super::*; /// Return a `Error::Signal` if the process was terminated by a signal, /// otherwise return an `Error::UnknownFailure` fn error_from_signal(recipe: &str, line_number: Option, exit_status: ExitStatus) -> Error { match Platform::signal_from_exit_status(exit_status) { Some(signal) => Error::Signal { recipe, line_number, signal, }, None => Error::Unknown { recipe, line_number, }, } } /// A recipe, e.g. `foo: bar baz` #[derive(PartialEq, Debug, Clone, Serialize)] pub(crate) struct Recipe<'src, D = Dependency<'src>> { pub(crate) attributes: AttributeSet<'src>, pub(crate) body: Vec>, pub(crate) dependencies: Vec, pub(crate) doc: Option, #[serde(skip)] pub(crate) file_depth: u32, #[serde(skip)] pub(crate) import_offsets: Vec, pub(crate) name: Name<'src>, pub(crate) namepath: Namepath<'src>, pub(crate) parameters: Vec>, pub(crate) priors: usize, pub(crate) private: bool, pub(crate) quiet: bool, pub(crate) shebang: bool, } impl<'src, D> Recipe<'src, D> { pub(crate) fn argument_range(&self) -> RangeInclusive { self.min_arguments()..=self.max_arguments() } pub(crate) fn min_arguments(&self) -> usize { self .parameters .iter() .filter(|p| p.default.is_none() && p.kind != ParameterKind::Star) .count() } pub(crate) fn max_arguments(&self) -> usize { if self.parameters.iter().any(|p| p.kind.is_variadic()) { usize::MAX - 1 } else { self.parameters.len() } } pub(crate) fn name(&self) -> &'src str { self.name.lexeme() } pub(crate) fn line_number(&self) -> usize { self.name.line } pub(crate) fn confirm(&self) -> RunResult<'src, bool> { if let Some(Attribute::Confirm(prompt)) = self.attributes.get(AttributeDiscriminant::Confirm) { if let Some(prompt) = prompt { eprint!("{} ", prompt.cooked); } else { eprint!("Run recipe `{}`? ", self.name); } let mut line = String::new(); std::io::stdin() .read_line(&mut line) .map_err(|io_error| Error::GetConfirmation { io_error })?; let line = line.trim().to_lowercase(); return Ok(line == "y" || line == "yes"); } Ok(true) } pub(crate) fn check_can_be_default_recipe(&self) -> RunResult<'src, ()> { let min_arguments = self.min_arguments(); if min_arguments > 0 { return Err(Error::DefaultRecipeRequiresArguments { recipe: self.name.lexeme(), min_arguments, }); } Ok(()) } pub(crate) fn is_public(&self) -> bool { !self.private && !self.attributes.contains(AttributeDiscriminant::Private) } pub(crate) fn is_script(&self) -> bool { self.shebang } pub(crate) fn takes_positional_arguments(&self, settings: &Settings) -> bool { settings.positional_arguments || self .attributes .contains(AttributeDiscriminant::PositionalArguments) } pub(crate) fn change_directory(&self) -> bool { !self.attributes.contains(AttributeDiscriminant::NoCd) } pub(crate) fn enabled(&self) -> bool { let linux = self.attributes.contains(AttributeDiscriminant::Linux); let macos = self.attributes.contains(AttributeDiscriminant::Macos); let openbsd = self.attributes.contains(AttributeDiscriminant::Openbsd); let unix = self.attributes.contains(AttributeDiscriminant::Unix); let windows = self.attributes.contains(AttributeDiscriminant::Windows); (!windows && !linux && !macos && !openbsd && !unix) || (cfg!(target_os = "linux") && (linux || unix)) || (cfg!(target_os = "macos") && (macos || unix)) || (cfg!(target_os = "openbsd") && (openbsd || unix)) || (cfg!(target_os = "windows") && windows) || (cfg!(unix) && unix) || (cfg!(windows) && windows) } fn print_exit_message(&self, settings: &Settings) -> bool { if self.attributes.contains(AttributeDiscriminant::ExitMessage) { true } else if settings.no_exit_message { false } else { !self .attributes .contains(AttributeDiscriminant::NoExitMessage) } } fn working_directory<'a>(&'a self, context: &'a ExecutionContext) -> Option { if !self.change_directory() { return None; } let working_directory = context.working_directory(); for attribute in &self.attributes { if let Attribute::WorkingDirectory(dir) = attribute { return Some(working_directory.join(&dir.cooked)); } } Some(working_directory) } fn no_quiet(&self) -> bool { self.attributes.contains(AttributeDiscriminant::NoQuiet) } pub(crate) fn run<'run>( &self, context: &ExecutionContext<'src, 'run>, scope: &Scope<'src, 'run>, positional: &[String], is_dependency: bool, ) -> RunResult<'src, ()> { let color = context.config.color.stderr().banner(); let prefix = color.prefix(); let suffix = color.suffix(); if context.config.verbosity.loquacious() { eprintln!("{prefix}===> Running recipe `{}`...{suffix}", self.name); } if context.config.explain { if let Some(doc) = self.doc() { eprintln!("{prefix}#### {doc}{suffix}"); } } let evaluator = Evaluator::new(context, is_dependency, scope); if self.is_script() { self.run_script(context, scope, positional, evaluator) } else { self.run_linewise(context, scope, positional, evaluator) } } fn run_linewise<'run>( &self, context: &ExecutionContext<'src, 'run>, scope: &Scope<'src, 'run>, positional: &[String], mut evaluator: Evaluator<'src, 'run>, ) -> RunResult<'src, ()> { let config = &context.config; let mut lines = self.body.iter().peekable(); let mut line_number = self.line_number() + 1; loop { if lines.peek().is_none() { return Ok(()); } let mut evaluated = String::new(); let mut continued = false; let quiet_line = lines.peek().is_some_and(|line| line.is_quiet()); let infallible_line = lines.peek().is_some_and(|line| line.is_infallible()); let comment_line = context.module.settings.ignore_comments && lines.peek().is_some_and(|line| line.is_comment()); loop { if lines.peek().is_none() { break; } let line = lines.next().unwrap(); line_number += 1; if !comment_line { evaluated += &evaluator.evaluate_line(line, continued)?; } if line.is_continuation() && !comment_line { continued = true; evaluated.pop(); } else { break; } } if comment_line { continue; } let mut command = evaluated.as_str(); let sigils = usize::from(infallible_line) + usize::from(quiet_line); command = &command[sigils..]; if command.is_empty() { continue; } if config.dry_run || config.verbosity.loquacious() || !((quiet_line ^ self.quiet) || (context.module.settings.quiet && !self.no_quiet()) || config.verbosity.quiet()) { let color = config .highlight .then(|| config.color.command(config.command_color)) .unwrap_or(config.color) .stderr(); if config.timestamp { eprint!( "[{}] ", color.paint( &chrono::Local::now() .format(&config.timestamp_format) .to_string() ), ); } eprintln!("{}", color.paint(command)); } if config.dry_run { continue; } let mut cmd = context.module.settings.shell_command(config); if let Some(working_directory) = self.working_directory(context) { cmd.current_dir(working_directory); } cmd.arg(command); if self.takes_positional_arguments(&context.module.settings) { cmd.arg(self.name.lexeme()); cmd.args(positional); } if config.verbosity.quiet() { cmd.stderr(Stdio::null()); cmd.stdout(Stdio::null()); } cmd.export( &context.module.settings, context.dotenv, scope, &context.module.unexports, ); match InterruptHandler::guard(|| cmd.status()) { Ok(exit_status) => { if let Some(code) = exit_status.code() { if code != 0 && !infallible_line { return Err(Error::Code { recipe: self.name(), line_number: Some(line_number), code, print_message: self.print_exit_message(&context.module.settings), }); } } else { return Err(error_from_signal( self.name(), Some(line_number), exit_status, )); } } Err(io_error) => { return Err(Error::Io { recipe: self.name(), io_error, }); } }; } } pub(crate) fn run_script<'run>( &self, context: &ExecutionContext<'src, 'run>, scope: &Scope<'src, 'run>, positional: &[String], mut evaluator: Evaluator<'src, 'run>, ) -> RunResult<'src, ()> { let config = &context.config; let mut evaluated_lines = Vec::new(); for line in &self.body { evaluated_lines.push(evaluator.evaluate_line(line, false)?); } if config.verbosity.loud() && (config.dry_run || self.quiet) { for line in &evaluated_lines { eprintln!( "{}", config .color .command(config.command_color) .stderr() .paint(line) ); } } if config.dry_run { return Ok(()); } let executor = if let Some(Attribute::Script(interpreter)) = self.attributes.get(AttributeDiscriminant::Script) { Executor::Command( interpreter .as_ref() .or(context.module.settings.script_interpreter.as_ref()) .unwrap_or_else(|| Interpreter::default_script_interpreter()), ) } else { let line = evaluated_lines .first() .ok_or_else(|| Error::internal("evaluated_lines was empty"))?; let shebang = Shebang::new(line).ok_or_else(|| Error::internal(format!("bad shebang line: {line}")))?; Executor::Shebang(shebang) }; let mut tempdir_builder = tempfile::Builder::new(); tempdir_builder.prefix("just-"); let tempdir = match &context.module.settings.tempdir { Some(tempdir) => tempdir_builder.tempdir_in(context.search.working_directory.join(tempdir)), None => { if let Some(runtime_dir) = dirs::runtime_dir() { let path = runtime_dir.join("just"); fs::create_dir_all(&path).map_err(|io_error| Error::RuntimeDirIo { io_error, path: path.clone(), })?; tempdir_builder.tempdir_in(path) } else { tempdir_builder.tempdir() } } } .map_err(|error| Error::TempdirIo { recipe: self.name(), io_error: error, })?; let mut path = tempdir.path().to_path_buf(); let extension = self.attributes.iter().find_map(|attribute| { if let Attribute::Extension(extension) = attribute { Some(extension.cooked.as_str()) } else { None } }); path.push(executor.script_filename(self.name(), extension)); let script = executor.script(self, &evaluated_lines); if config.verbosity.grandiloquent() { eprintln!("{}", config.color.doc().stderr().paint(&script)); } fs::write(&path, script).map_err(|error| Error::TempdirIo { recipe: self.name(), io_error: error, })?; let mut command = executor.command( &path, self.name(), self.working_directory(context).as_deref(), )?; if self.takes_positional_arguments(&context.module.settings) { command.args(positional); } command.export( &context.module.settings, context.dotenv, scope, &context.module.unexports, ); // run it! match InterruptHandler::guard(|| command.status()) { Ok(exit_status) => exit_status.code().map_or_else( || Err(error_from_signal(self.name(), None, exit_status)), |code| { if code == 0 { Ok(()) } else { Err(Error::Code { recipe: self.name(), line_number: None, code, print_message: self.print_exit_message(&context.module.settings), }) } }, ), Err(io_error) => Err(executor.error(io_error, self.name())), } } pub(crate) fn groups(&self) -> BTreeSet { self .attributes .iter() .filter_map(|attribute| { if let Attribute::Group(group) = attribute { Some(group.cooked.clone()) } else { None } }) .collect() } pub(crate) fn doc(&self) -> Option<&str> { for attribute in &self.attributes { if let Attribute::Doc(doc) = attribute { return doc.as_ref().map(|s| s.cooked.as_ref()); } } self.doc.as_deref() } pub(crate) fn subsequents(&self) -> impl Iterator { self.dependencies.iter().skip(self.priors) } } impl ColorDisplay for Recipe<'_, D> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { if !self .attributes .iter() .any(|attribute| matches!(attribute, Attribute::Doc(_))) { if let Some(doc) = &self.doc { writeln!(f, "# {doc}")?; } } for attribute in &self.attributes { writeln!(f, "[{attribute}]")?; } if self.quiet { write!(f, "@{}", self.name)?; } else { write!(f, "{}", self.name)?; } for parameter in &self.parameters { write!(f, " {}", parameter.color_display(color))?; } write!(f, ":")?; for (i, dependency) in self.dependencies.iter().enumerate() { if i == self.priors { write!(f, " &&")?; } write!(f, " {dependency}")?; } for (i, line) in self.body.iter().enumerate() { if i == 0 { writeln!(f)?; } for (j, fragment) in line.fragments.iter().enumerate() { if j == 0 { write!(f, " ")?; } match fragment { Fragment::Text { token } => write!(f, "{}", token.lexeme())?, Fragment::Interpolation { expression, .. } => write!(f, "{{{{ {expression} }}}}")?, } } if i + 1 < self.body.len() { writeln!(f)?; } } Ok(()) } } impl<'src, D> Keyed<'src> for Recipe<'src, D> { fn key(&self) -> &'src str { self.name.lexeme() } } just-1.40.0/src/recipe_resolver.rs000064400000000000000000000123741046102023000152270ustar 00000000000000use {super::*, CompileErrorKind::*}; pub(crate) struct RecipeResolver<'src: 'run, 'run> { assignments: &'run Table<'src, Assignment<'src>>, resolved_recipes: Table<'src, Rc>>, unresolved_recipes: Table<'src, UnresolvedRecipe<'src>>, } impl<'src: 'run, 'run> RecipeResolver<'src, 'run> { pub(crate) fn resolve_recipes( assignments: &'run Table<'src, Assignment<'src>>, settings: &Settings, unresolved_recipes: Table<'src, UnresolvedRecipe<'src>>, ) -> CompileResult<'src, Table<'src, Rc>>> { let mut resolver = Self { resolved_recipes: Table::new(), unresolved_recipes, assignments, }; while let Some(unresolved) = resolver.unresolved_recipes.pop() { resolver.resolve_recipe(&mut Vec::new(), unresolved)?; } for recipe in resolver.resolved_recipes.values() { for (i, parameter) in recipe.parameters.iter().enumerate() { if let Some(expression) = ¶meter.default { for variable in expression.variables() { resolver.resolve_variable(&variable, &recipe.parameters[..i])?; } } } for dependency in &recipe.dependencies { for argument in &dependency.arguments { for variable in argument.variables() { resolver.resolve_variable(&variable, &recipe.parameters)?; } } } for line in &recipe.body { if line.is_comment() && settings.ignore_comments { continue; } for fragment in &line.fragments { if let Fragment::Interpolation { expression, .. } = fragment { for variable in expression.variables() { resolver.resolve_variable(&variable, &recipe.parameters)?; } } } } } Ok(resolver.resolved_recipes) } fn resolve_variable( &self, variable: &Token<'src>, parameters: &[Parameter], ) -> CompileResult<'src> { let name = variable.lexeme(); let defined = self.assignments.contains_key(name) || parameters.iter().any(|p| p.name.lexeme() == name) || constants().contains_key(name); if !defined { return Err(variable.error(UndefinedVariable { variable: name })); } Ok(()) } fn resolve_recipe( &mut self, stack: &mut Vec<&'src str>, recipe: UnresolvedRecipe<'src>, ) -> CompileResult<'src, Rc>> { if let Some(resolved) = self.resolved_recipes.get(recipe.name()) { return Ok(Rc::clone(resolved)); } stack.push(recipe.name()); let mut dependencies: Vec> = Vec::new(); for dependency in &recipe.dependencies { let name = dependency.recipe.lexeme(); if let Some(resolved) = self.resolved_recipes.get(name) { // dependency already resolved dependencies.push(Rc::clone(resolved)); } else if stack.contains(&name) { let first = stack[0]; stack.push(first); return Err( dependency.recipe.error(CircularRecipeDependency { recipe: recipe.name(), circle: stack .iter() .skip_while(|name| **name != dependency.recipe.lexeme()) .copied() .collect(), }), ); } else if let Some(unresolved) = self.unresolved_recipes.remove(name) { // resolve unresolved dependency dependencies.push(self.resolve_recipe(stack, unresolved)?); } else { // dependency is unknown return Err(dependency.recipe.error(UnknownDependency { recipe: recipe.name(), unknown: name, })); } } stack.pop(); let resolved = Rc::new(recipe.resolve(dependencies)?); self.resolved_recipes.insert(Rc::clone(&resolved)); Ok(resolved) } } #[cfg(test)] mod tests { use super::*; analysis_error! { name: circular_recipe_dependency, input: "a: b\nb: a", offset: 8, line: 1, column: 3, width: 1, kind: CircularRecipeDependency{recipe: "b", circle: vec!["a", "b", "a"]}, } analysis_error! { name: self_recipe_dependency, input: "a: a", offset: 3, line: 0, column: 3, width: 1, kind: CircularRecipeDependency{recipe: "a", circle: vec!["a", "a"]}, } analysis_error! { name: unknown_dependency, input: "a: b", offset: 3, line: 0, column: 3, width: 1, kind: UnknownDependency{recipe: "a", unknown: "b"}, } analysis_error! { name: unknown_interpolation_variable, input: "x:\n {{ hello}}", offset: 9, line: 1, column: 6, width: 5, kind: UndefinedVariable{variable: "hello"}, } analysis_error! { name: unknown_second_interpolation_variable, input: "wtf:=\"x\"\nx:\n echo\n foo {{wtf}} {{ lol }}", offset: 34, line: 3, column: 16, width: 3, kind: UndefinedVariable{variable: "lol"}, } analysis_error! { name: unknown_variable_in_default, input: "a f=foo:", offset: 4, line: 0, column: 4, width: 3, kind: UndefinedVariable{variable: "foo"}, } analysis_error! { name: unknown_variable_in_dependency_argument, input: "bar x:\nfoo: (bar baz)", offset: 17, line: 1, column: 10, width: 3, kind: UndefinedVariable{variable: "baz"}, } } just-1.40.0/src/recipe_signature.rs000064400000000000000000000006111046102023000153560ustar 00000000000000use super::*; pub(crate) struct RecipeSignature<'a> { pub(crate) name: &'a str, pub(crate) recipe: &'a Recipe<'a>, } impl ColorDisplay for RecipeSignature<'_> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { write!(f, "{}", self.name)?; for parameter in &self.recipe.parameters { write!(f, " {}", parameter.color_display(color))?; } Ok(()) } } just-1.40.0/src/request.rs000064400000000000000000000004571046102023000135260ustar 00000000000000use super::*; #[derive(Clone, Debug, Deserialize, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum Request { EnvironmentVariable(String), } #[derive(Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "kebab-case")] pub enum Response { EnvironmentVariable(Option), } just-1.40.0/src/run.rs000064400000000000000000000017331046102023000126400ustar 00000000000000use super::*; /// Main entry point into `just`. Parse arguments from `args` and run. #[allow(clippy::missing_errors_doc)] pub fn run(args: impl Iterator + Clone>) -> Result<(), i32> { #[cfg(windows)] ansi_term::enable_ansi_support().ok(); let app = Config::app(); let matches = app.try_get_matches_from(args).map_err(|err| { err.print().ok(); err.exit_code() })?; let config = Config::from_matches(&matches).map_err(Error::from); let (color, verbosity) = config .as_ref() .map(|config| (config.color, config.verbosity)) .unwrap_or_default(); let loader = Loader::new(); config .and_then(|config| { InterruptHandler::install(config.verbosity).ok(); config.subcommand.execute(&config, &loader) }) .map_err(|error| { if !verbosity.quiet() && error.print_message() { eprintln!("{}", error.color_display(color.stderr())); } error.code().unwrap_or(EXIT_FAILURE) }) } just-1.40.0/src/scope.rs000064400000000000000000000031021046102023000131350ustar 00000000000000use super::*; #[derive(Debug)] pub(crate) struct Scope<'src: 'run, 'run> { bindings: Table<'src, Binding<'src, String>>, parent: Option<&'run Self>, } impl<'src, 'run> Scope<'src, 'run> { pub(crate) fn child(&'run self) -> Self { Self { parent: Some(self), bindings: Table::new(), } } pub(crate) fn root() -> Self { let mut root = Self { parent: None, bindings: Table::new(), }; for (key, value) in constants() { root.bind(Binding { constant: true, export: false, file_depth: 0, name: Name { token: Token { column: 0, kind: TokenKind::Identifier, length: key.len(), line: 0, offset: 0, path: Path::new("PRELUDE"), src: key, }, }, private: false, value: (*value).into(), }); } root } pub(crate) fn bind(&mut self, binding: Binding<'src>) { self.bindings.insert(binding); } pub(crate) fn bound(&self, name: &str) -> bool { self.bindings.contains_key(name) } pub(crate) fn value(&self, name: &str) -> Option<&str> { if let Some(binding) = self.bindings.get(name) { Some(binding.value.as_ref()) } else { self.parent?.value(name) } } pub(crate) fn bindings(&self) -> impl Iterator> { self.bindings.values() } pub(crate) fn names(&self) -> impl Iterator { self.bindings.keys().copied() } pub(crate) fn parent(&self) -> Option<&'run Self> { self.parent } } just-1.40.0/src/search.rs000064400000000000000000000270461046102023000133060ustar 00000000000000use {super::*, std::path::Component}; const DEFAULT_JUSTFILE_NAME: &str = JUSTFILE_NAMES[0]; pub(crate) const JUSTFILE_NAMES: [&str; 2] = ["justfile", ".justfile"]; const PROJECT_ROOT_CHILDREN: &[&str] = &[".bzr", ".git", ".hg", ".svn", "_darcs"]; #[derive(Debug)] pub(crate) struct Search { pub(crate) justfile: PathBuf, pub(crate) working_directory: PathBuf, } impl Search { fn global_justfile_paths() -> Vec { let mut paths = Vec::new(); if let Some(config_dir) = dirs::config_dir() { paths.push(config_dir.join("just").join(DEFAULT_JUSTFILE_NAME)); } if let Some(home_dir) = dirs::home_dir() { paths.push( home_dir .join(".config") .join("just") .join(DEFAULT_JUSTFILE_NAME), ); for justfile_name in JUSTFILE_NAMES { paths.push(home_dir.join(justfile_name)); } } paths } /// Find justfile given search configuration and invocation directory pub(crate) fn find( search_config: &SearchConfig, invocation_directory: &Path, ) -> SearchResult { match search_config { SearchConfig::FromInvocationDirectory => Self::find_in_directory(invocation_directory), SearchConfig::FromSearchDirectory { search_directory } => { let search_directory = Self::clean(invocation_directory, search_directory); let justfile = Self::justfile(&search_directory)?; let working_directory = Self::working_directory_from_justfile(&justfile)?; Ok(Self { justfile, working_directory, }) } SearchConfig::GlobalJustfile => Ok(Self { justfile: Self::global_justfile_paths() .iter() .find(|path| path.exists()) .cloned() .ok_or(SearchError::GlobalJustfileNotFound)?, working_directory: Self::project_root(invocation_directory)?, }), SearchConfig::WithJustfile { justfile } => { let justfile = Self::clean(invocation_directory, justfile); let working_directory = Self::working_directory_from_justfile(&justfile)?; Ok(Self { justfile, working_directory, }) } SearchConfig::WithJustfileAndWorkingDirectory { justfile, working_directory, } => Ok(Self { justfile: Self::clean(invocation_directory, justfile), working_directory: Self::clean(invocation_directory, working_directory), }), } } /// Find justfile starting from parent directory of current justfile pub(crate) fn search_parent_directory(&self) -> SearchResult { let parent = self .justfile .parent() .and_then(|path| path.parent()) .ok_or_else(|| SearchError::JustfileHadNoParent { path: self.justfile.clone(), })?; Self::find_in_directory(parent) } /// Find justfile starting in given directory searching upwards in directory tree fn find_in_directory(starting_dir: &Path) -> SearchResult { let justfile = Self::justfile(starting_dir)?; let working_directory = Self::working_directory_from_justfile(&justfile)?; Ok(Self { justfile, working_directory, }) } /// Get working directory and justfile path for newly-initialized justfile pub(crate) fn init( search_config: &SearchConfig, invocation_directory: &Path, ) -> SearchResult { match search_config { SearchConfig::FromInvocationDirectory => { let working_directory = Self::project_root(invocation_directory)?; let justfile = working_directory.join(DEFAULT_JUSTFILE_NAME); Ok(Self { justfile, working_directory, }) } SearchConfig::FromSearchDirectory { search_directory } => { let search_directory = Self::clean(invocation_directory, search_directory); let working_directory = Self::project_root(&search_directory)?; let justfile = working_directory.join(DEFAULT_JUSTFILE_NAME); Ok(Self { justfile, working_directory, }) } SearchConfig::GlobalJustfile => Err(SearchError::GlobalJustfileInit), SearchConfig::WithJustfile { justfile } => { let justfile = Self::clean(invocation_directory, justfile); let working_directory = Self::working_directory_from_justfile(&justfile)?; Ok(Self { justfile, working_directory, }) } SearchConfig::WithJustfileAndWorkingDirectory { justfile, working_directory, } => Ok(Self { justfile: Self::clean(invocation_directory, justfile), working_directory: Self::clean(invocation_directory, working_directory), }), } } /// Search upwards from `directory` for a file whose name matches one of /// `JUSTFILE_NAMES` fn justfile(directory: &Path) -> SearchResult { for directory in directory.ancestors() { let mut candidates = BTreeSet::new(); let entries = fs::read_dir(directory).map_err(|io_error| SearchError::Io { io_error, directory: directory.to_owned(), })?; for entry in entries { let entry = entry.map_err(|io_error| SearchError::Io { io_error, directory: directory.to_owned(), })?; if let Some(name) = entry.file_name().to_str() { for justfile_name in JUSTFILE_NAMES { if name.eq_ignore_ascii_case(justfile_name) { candidates.insert(entry.path()); } } } } match candidates.len() { 0 => {} 1 => return Ok(candidates.into_iter().next().unwrap()), _ => return Err(SearchError::MultipleCandidates { candidates }), } } Err(SearchError::NotFound) } fn clean(invocation_directory: &Path, path: &Path) -> PathBuf { let path = invocation_directory.join(path); let mut clean = Vec::new(); for component in path.components() { if component == Component::ParentDir { if let Some(Component::Normal(_)) = clean.last() { clean.pop(); } } else { clean.push(component); } } clean.into_iter().collect() } /// Search upwards from `directory` for the root directory of a software /// project, as determined by the presence of one of the version control /// system directories given in `PROJECT_ROOT_CHILDREN` fn project_root(directory: &Path) -> SearchResult { for directory in directory.ancestors() { let entries = fs::read_dir(directory).map_err(|io_error| SearchError::Io { io_error, directory: directory.to_owned(), })?; for entry in entries { let entry = entry.map_err(|io_error| SearchError::Io { io_error, directory: directory.to_owned(), })?; for project_root_child in PROJECT_ROOT_CHILDREN.iter().copied() { if entry.file_name() == project_root_child { return Ok(directory.to_owned()); } } } } Ok(directory.to_owned()) } fn working_directory_from_justfile(justfile: &Path) -> SearchResult { Ok( justfile .parent() .ok_or_else(|| SearchError::JustfileHadNoParent { path: justfile.to_path_buf(), })? .to_owned(), ) } } #[cfg(test)] mod tests { use super::*; use temptree::temptree; #[test] fn not_found() { let tmp = testing::tempdir(); match Search::justfile(tmp.path()) { Err(SearchError::NotFound) => {} _ => panic!("No justfile found error was expected"), } } #[test] fn multiple_candidates() { let tmp = testing::tempdir(); let mut path = tmp.path().to_path_buf(); path.push(DEFAULT_JUSTFILE_NAME); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); path.push(DEFAULT_JUSTFILE_NAME.to_uppercase()); if fs::File::open(path.as_path()).is_ok() { // We are in case-insensitive file system return; } fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); match Search::justfile(path.as_path()) { Err(SearchError::MultipleCandidates { .. }) => {} _ => panic!("Multiple candidates error was expected"), } } #[test] fn found() { let tmp = testing::tempdir(); let mut path = tmp.path().to_path_buf(); path.push(DEFAULT_JUSTFILE_NAME); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); if let Err(err) = Search::justfile(path.as_path()) { panic!("No errors were expected: {err}"); } } #[test] fn found_spongebob_case() { let tmp = testing::tempdir(); let mut path = tmp.path().to_path_buf(); let spongebob_case = DEFAULT_JUSTFILE_NAME .chars() .enumerate() .map(|(i, c)| { if i % 2 == 0 { c.to_ascii_uppercase() } else { c } }) .collect::(); path.push(spongebob_case); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); if let Err(err) = Search::justfile(path.as_path()) { panic!("No errors were expected: {err}"); } } #[test] fn found_from_inner_dir() { let tmp = testing::tempdir(); let mut path = tmp.path().to_path_buf(); path.push(DEFAULT_JUSTFILE_NAME); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); path.push("a"); fs::create_dir(&path).expect("test justfile search: failed to create intermediary directory"); path.push("b"); fs::create_dir(&path).expect("test justfile search: failed to create intermediary directory"); if let Err(err) = Search::justfile(path.as_path()) { panic!("No errors were expected: {err}"); } } #[test] fn found_and_stopped_at_first_justfile() { let tmp = testing::tempdir(); let mut path = tmp.path().to_path_buf(); path.push(DEFAULT_JUSTFILE_NAME); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); path.push("a"); fs::create_dir(&path).expect("test justfile search: failed to create intermediary directory"); path.push(DEFAULT_JUSTFILE_NAME); fs::write(&path, "default:\n\techo ok").unwrap(); path.pop(); path.push("b"); fs::create_dir(&path).expect("test justfile search: failed to create intermediary directory"); match Search::justfile(path.as_path()) { Ok(found_path) => { path.pop(); path.push(DEFAULT_JUSTFILE_NAME); assert_eq!(found_path, path); } Err(err) => panic!("No errors were expected: {err}"), } } #[test] fn justfile_symlink_parent() { let tmp = temptree! { src: "", sub: {}, }; let src = tmp.path().join("src"); let sub = tmp.path().join("sub"); let justfile = sub.join("justfile"); #[cfg(unix)] std::os::unix::fs::symlink(src, &justfile).unwrap(); #[cfg(windows)] std::os::windows::fs::symlink_file(&src, &justfile).unwrap(); let search_config = SearchConfig::FromInvocationDirectory; let search = Search::find(&search_config, &sub).unwrap(); assert_eq!(search.justfile, justfile); assert_eq!(search.working_directory, sub); } #[test] fn clean() { let cases = &[ ("/", "foo", "/foo"), ("/bar", "/foo", "/foo"), #[cfg(windows)] ("//foo", "bar//baz", "//foo\\bar\\baz"), #[cfg(not(windows))] ("/", "..", "/"), ("/", "/..", "/"), ("/..", "", "/"), ("/../../../..", "../../../", "/"), ("/.", "./", "/"), ("/foo/../", "bar", "/bar"), ("/foo/bar", "..", "/foo"), ("/foo/bar/", "..", "/foo"), ]; for (prefix, suffix, want) in cases { let have = Search::clean(Path::new(prefix), Path::new(suffix)); assert_eq!(have, Path::new(want)); } } } just-1.40.0/src/search_config.rs000064400000000000000000000014441046102023000146250ustar 00000000000000use super::*; /// Controls how `just` will search for the justfile. #[derive(Debug, PartialEq)] pub(crate) enum SearchConfig { /// Recursively search for the justfile upwards from the invocation directory /// to the root, setting the working directory to the directory in which the /// justfile is found. FromInvocationDirectory, /// As in `Invocation`, but start from `search_directory`. FromSearchDirectory { search_directory: PathBuf }, /// Search for global justfile GlobalJustfile, /// Use user-specified justfile, with the working directory set to the /// directory that contains it. WithJustfile { justfile: PathBuf }, /// Use user-specified justfile and working directory. WithJustfileAndWorkingDirectory { justfile: PathBuf, working_directory: PathBuf, }, } just-1.40.0/src/search_error.rs000064400000000000000000000025261046102023000145130ustar 00000000000000use super::*; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub(crate) enum SearchError { #[snafu(display("Cannot initialize global justfile"))] GlobalJustfileInit, #[snafu(display("Global justfile not found"))] GlobalJustfileNotFound, #[snafu(display( "I/O error reading directory `{}`: {}", directory.display(), io_error ))] Io { directory: PathBuf, io_error: io::Error, }, #[snafu(display("Justfile path had no parent: {}", path.display()))] JustfileHadNoParent { path: PathBuf }, #[snafu(display( "Multiple candidate justfiles found in `{}`: {}", candidates.iter().next().unwrap().parent().unwrap().display(), List::and_ticked( candidates .iter() .map(|candidate| candidate.file_name().unwrap().to_string_lossy()) ), ))] MultipleCandidates { candidates: BTreeSet }, #[snafu(display("No justfile found"))] NotFound, } #[cfg(test)] mod tests { use super::*; #[test] fn multiple_candidates_formatting() { let error = SearchError::MultipleCandidates { candidates: [Path::new("/foo/justfile"), Path::new("/foo/JUSTFILE")] .iter() .map(|path| path.to_path_buf()) .collect(), }; assert_eq!( error.to_string(), "Multiple candidate justfiles found in `/foo`: `JUSTFILE` and `justfile`" ); } } just-1.40.0/src/set.rs000064400000000000000000000005701046102023000126250ustar 00000000000000use super::*; #[derive(Debug, Clone)] pub(crate) struct Set<'src> { pub(crate) name: Name<'src>, pub(crate) value: Setting<'src>, } impl<'src> Keyed<'src> for Set<'src> { fn key(&self) -> &'src str { self.name.lexeme() } } impl Display for Set<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "set {} := {}", self.name, self.value) } } just-1.40.0/src/setting.rs000064400000000000000000000026701046102023000135120ustar 00000000000000use super::*; #[derive(Debug, Clone)] pub(crate) enum Setting<'src> { AllowDuplicateRecipes(bool), AllowDuplicateVariables(bool), DotenvFilename(StringLiteral<'src>), DotenvLoad(bool), DotenvPath(StringLiteral<'src>), DotenvRequired(bool), Export(bool), Fallback(bool), IgnoreComments(bool), NoExitMessage(bool), PositionalArguments(bool), Quiet(bool), ScriptInterpreter(Interpreter<'src>), Shell(Interpreter<'src>), Tempdir(StringLiteral<'src>), Unstable(bool), WindowsPowerShell(bool), WindowsShell(Interpreter<'src>), WorkingDirectory(StringLiteral<'src>), } impl Display for Setting<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::AllowDuplicateRecipes(value) | Self::AllowDuplicateVariables(value) | Self::DotenvLoad(value) | Self::DotenvRequired(value) | Self::Export(value) | Self::Fallback(value) | Self::IgnoreComments(value) | Self::NoExitMessage(value) | Self::PositionalArguments(value) | Self::Quiet(value) | Self::Unstable(value) | Self::WindowsPowerShell(value) => write!(f, "{value}"), Self::ScriptInterpreter(shell) | Self::Shell(shell) | Self::WindowsShell(shell) => { write!(f, "[{shell}]") } Self::DotenvFilename(value) | Self::DotenvPath(value) | Self::Tempdir(value) | Self::WorkingDirectory(value) => { write!(f, "{value}") } } } } just-1.40.0/src/settings.rs000064400000000000000000000171531046102023000136770ustar 00000000000000use super::*; pub(crate) const DEFAULT_SHELL: &str = "sh"; pub(crate) const DEFAULT_SHELL_ARGS: &[&str] = &["-cu"]; pub(crate) const WINDOWS_POWERSHELL_SHELL: &str = "powershell.exe"; pub(crate) const WINDOWS_POWERSHELL_ARGS: &[&str] = &["-NoLogo", "-Command"]; #[derive(Debug, PartialEq, Serialize, Default)] pub(crate) struct Settings<'src> { pub(crate) allow_duplicate_recipes: bool, pub(crate) allow_duplicate_variables: bool, pub(crate) dotenv_filename: Option, pub(crate) dotenv_load: bool, pub(crate) dotenv_path: Option, pub(crate) dotenv_required: bool, pub(crate) export: bool, pub(crate) fallback: bool, pub(crate) ignore_comments: bool, pub(crate) no_exit_message: bool, pub(crate) positional_arguments: bool, pub(crate) quiet: bool, #[serde(skip)] pub(crate) script_interpreter: Option>, pub(crate) shell: Option>, pub(crate) tempdir: Option, pub(crate) unstable: bool, pub(crate) windows_powershell: bool, pub(crate) windows_shell: Option>, pub(crate) working_directory: Option, } impl<'src> Settings<'src> { pub(crate) fn from_table(sets: Table<'src, Set<'src>>) -> Self { let mut settings = Self::default(); for (_name, set) in sets { match set.value { Setting::AllowDuplicateRecipes(allow_duplicate_recipes) => { settings.allow_duplicate_recipes = allow_duplicate_recipes; } Setting::AllowDuplicateVariables(allow_duplicate_variables) => { settings.allow_duplicate_variables = allow_duplicate_variables; } Setting::DotenvFilename(filename) => { settings.dotenv_filename = Some(filename.cooked); } Setting::DotenvLoad(dotenv_load) => { settings.dotenv_load = dotenv_load; } Setting::DotenvPath(path) => { settings.dotenv_path = Some(PathBuf::from(path.cooked)); } Setting::DotenvRequired(dotenv_required) => { settings.dotenv_required = dotenv_required; } Setting::Export(export) => { settings.export = export; } Setting::Fallback(fallback) => { settings.fallback = fallback; } Setting::IgnoreComments(ignore_comments) => { settings.ignore_comments = ignore_comments; } Setting::NoExitMessage(no_exit_message) => { settings.no_exit_message = no_exit_message; } Setting::PositionalArguments(positional_arguments) => { settings.positional_arguments = positional_arguments; } Setting::Quiet(quiet) => { settings.quiet = quiet; } Setting::ScriptInterpreter(script_interpreter) => { settings.script_interpreter = Some(script_interpreter); } Setting::Shell(shell) => { settings.shell = Some(shell); } Setting::Unstable(unstable) => { settings.unstable = unstable; } Setting::WindowsPowerShell(windows_powershell) => { settings.windows_powershell = windows_powershell; } Setting::WindowsShell(windows_shell) => { settings.windows_shell = Some(windows_shell); } Setting::Tempdir(tempdir) => { settings.tempdir = Some(tempdir.cooked); } Setting::WorkingDirectory(working_directory) => { settings.working_directory = Some(working_directory.cooked.into()); } } } settings } pub(crate) fn shell_command(&self, config: &Config) -> Command { let (command, args) = self.shell(config); let mut cmd = Command::new(command); cmd.args(args); cmd } pub(crate) fn shell<'a>(&'a self, config: &'a Config) -> (&'a str, Vec<&'a str>) { match (&config.shell, &config.shell_args) { (Some(shell), Some(shell_args)) => (shell, shell_args.iter().map(String::as_ref).collect()), (Some(shell), None) => (shell, DEFAULT_SHELL_ARGS.to_vec()), (None, Some(shell_args)) => ( DEFAULT_SHELL, shell_args.iter().map(String::as_ref).collect(), ), (None, None) => { if let (true, Some(shell)) = (cfg!(windows), &self.windows_shell) { ( shell.command.cooked.as_ref(), shell .arguments .iter() .map(|argument| argument.cooked.as_ref()) .collect(), ) } else if cfg!(windows) && self.windows_powershell { (WINDOWS_POWERSHELL_SHELL, WINDOWS_POWERSHELL_ARGS.to_vec()) } else if let Some(shell) = &self.shell { ( shell.command.cooked.as_ref(), shell .arguments .iter() .map(|argument| argument.cooked.as_ref()) .collect(), ) } else { (DEFAULT_SHELL, DEFAULT_SHELL_ARGS.to_vec()) } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn default_shell() { let settings = Settings::default(); let config = Config { shell_command: false, ..testing::config(&[]) }; assert_eq!(settings.shell(&config), ("sh", vec!["-cu"])); } #[test] fn default_shell_powershell() { let settings = Settings { windows_powershell: true, ..Default::default() }; let config = Config { shell_command: false, ..testing::config(&[]) }; if cfg!(windows) { assert_eq!( settings.shell(&config), ("powershell.exe", vec!["-NoLogo", "-Command"]) ); } else { assert_eq!(settings.shell(&config), ("sh", vec!["-cu"])); } } #[test] fn overwrite_shell() { let settings = Settings::default(); let config = Config { shell_command: true, shell: Some("lol".to_string()), shell_args: Some(vec!["-nice".to_string()]), ..testing::config(&[]) }; assert_eq!(settings.shell(&config), ("lol", vec!["-nice"])); } #[test] fn overwrite_shell_powershell() { let settings = Settings { windows_powershell: true, ..Default::default() }; let config = Config { shell_command: true, shell: Some("lol".to_string()), shell_args: Some(vec!["-nice".to_string()]), ..testing::config(&[]) }; assert_eq!(settings.shell(&config), ("lol", vec!["-nice"])); } #[test] fn shell_cooked() { let settings = Settings { shell: Some(Interpreter { command: StringLiteral { kind: StringKind::from_token_start("\"").unwrap(), raw: "asdf.exe", cooked: "asdf.exe".to_string(), expand: false, }, arguments: vec![StringLiteral { kind: StringKind::from_token_start("\"").unwrap(), raw: "-nope", cooked: "-nope".to_string(), expand: false, }], }), ..Default::default() }; let config = Config { shell_command: false, ..testing::config(&[]) }; assert_eq!(settings.shell(&config), ("asdf.exe", vec!["-nope"])); } #[test] fn shell_present_but_not_shell_args() { let settings = Settings { windows_powershell: true, ..Default::default() }; let config = Config { shell: Some("lol".to_string()), ..testing::config(&[]) }; assert_eq!(settings.shell(&config).0, "lol"); } #[test] fn shell_args_present_but_not_shell() { let settings = Settings { windows_powershell: true, ..Default::default() }; let config = Config { shell_command: false, shell_args: Some(vec!["-nice".to_string()]), ..testing::config(&[]) }; assert_eq!(settings.shell(&config), ("sh", vec!["-nice"])); } } just-1.40.0/src/shebang.rs000064400000000000000000000067761046102023000134570ustar 00000000000000#[derive(Copy, Clone)] pub(crate) struct Shebang<'line> { pub(crate) argument: Option<&'line str>, pub(crate) interpreter: &'line str, } impl<'line> Shebang<'line> { pub(crate) fn new(line: &'line str) -> Option { if !line.starts_with("#!") { return None; } let mut pieces = line[2..] .lines() .next() .unwrap_or("") .trim() .splitn(2, [' ', '\t']); let interpreter = pieces.next().unwrap_or(""); let argument = pieces.next(); if interpreter.is_empty() { return None; } Some(Self { argument, interpreter, }) } pub fn interpreter_filename(&self) -> &str { self .interpreter .split(['/', '\\']) .last() .unwrap_or(self.interpreter) } pub(crate) fn include_shebang_line(&self) -> bool { !(cfg!(windows) || matches!(self.interpreter_filename(), "cmd" | "cmd.exe")) } } #[cfg(test)] mod tests { use super::Shebang; #[test] fn split_shebang() { fn check(text: &str, expected_split: Option<(&str, Option<&str>)>) { let shebang = Shebang::new(text); assert_eq!( shebang.map(|shebang| (shebang.interpreter, shebang.argument)), expected_split ); } check("#! ", None); check("#!", None); check("#!/bin/bash", Some(("/bin/bash", None))); check("#!/bin/bash ", Some(("/bin/bash", None))); check( "#!/usr/bin/env python", Some(("/usr/bin/env", Some("python"))), ); check( "#!/usr/bin/env python ", Some(("/usr/bin/env", Some("python"))), ); check( "#!/usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))), ); check( "#!/usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))), ); check( "#!/usr/bin/env python \t-x\t", Some(("/usr/bin/env", Some("python \t-x"))), ); check("#/usr/bin/env python \t-x\t", None); check("#! /bin/bash", Some(("/bin/bash", None))); check("#!\t\t/bin/bash ", Some(("/bin/bash", None))); check( "#! \t\t/usr/bin/env python", Some(("/usr/bin/env", Some("python"))), ); check( "#! /usr/bin/env python ", Some(("/usr/bin/env", Some("python"))), ); check( "#! /usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))), ); check( "#! /usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))), ); check( "#! /usr/bin/env python \t-x\t", Some(("/usr/bin/env", Some("python \t-x"))), ); check("# /usr/bin/env python \t-x\t", None); } #[test] fn interpreter_filename_with_forward_slash() { assert_eq!( Shebang::new("#!/foo/bar/baz") .unwrap() .interpreter_filename(), "baz" ); } #[test] fn interpreter_filename_with_backslash() { assert_eq!( Shebang::new("#!\\foo\\bar\\baz") .unwrap() .interpreter_filename(), "baz" ); } #[test] fn dont_include_shebang_line_cmd() { assert!(!Shebang::new("#!cmd").unwrap().include_shebang_line()); } #[test] fn dont_include_shebang_line_cmd_exe() { assert!(!Shebang::new("#!cmd.exe /C").unwrap().include_shebang_line()); } #[test] #[cfg(not(windows))] fn include_shebang_line_other_not_windows() { assert!(Shebang::new("#!foo -c").unwrap().include_shebang_line()); } #[test] #[cfg(windows)] fn include_shebang_line_other_windows() { assert!(!Shebang::new("#!foo -c").unwrap().include_shebang_line()); } } just-1.40.0/src/show_whitespace.rs000064400000000000000000000006321046102023000152250ustar 00000000000000use super::*; /// String wrapper that uses nonblank characters to display spaces and tabs pub struct ShowWhitespace<'str>(pub &'str str); impl Display for ShowWhitespace<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { for c in self.0.chars() { match c { '\t' => write!(f, "␉")?, ' ' => write!(f, "␠")?, _ => write!(f, "{c}")?, }; } Ok(()) } } just-1.40.0/src/source.rs000064400000000000000000000031731046102023000133340ustar 00000000000000use super::*; #[derive(Debug)] pub(crate) struct Source<'src> { pub(crate) file_depth: u32, pub(crate) file_path: Vec, pub(crate) import_offsets: Vec, pub(crate) namepath: Option>, pub(crate) path: PathBuf, pub(crate) working_directory: PathBuf, } impl<'src> Source<'src> { pub(crate) fn root(path: &Path) -> Self { Self { file_depth: 0, file_path: vec![path.into()], import_offsets: Vec::new(), namepath: None, path: path.into(), working_directory: path.parent().unwrap().into(), } } pub(crate) fn import(&self, path: PathBuf, import_offset: usize) -> Self { Self { file_depth: self.file_depth + 1, file_path: self .file_path .clone() .into_iter() .chain(iter::once(path.clone())) .collect(), import_offsets: self .import_offsets .iter() .copied() .chain(iter::once(import_offset)) .collect(), namepath: self.namepath.clone(), path, working_directory: self.working_directory.clone(), } } pub(crate) fn module(&self, name: Name<'src>, path: PathBuf) -> Self { Self { file_depth: self.file_depth + 1, file_path: self .file_path .clone() .into_iter() .chain(iter::once(path.clone())) .collect(), import_offsets: Vec::new(), namepath: Some( self .namepath .as_ref() .map_or_else(|| name.into(), |namepath| namepath.join(name)), ), path: path.clone(), working_directory: path.parent().unwrap().into(), } } } just-1.40.0/src/string_delimiter.rs000064400000000000000000000002141046102023000153710ustar 00000000000000#[derive(Debug, PartialEq, Clone, Copy, Ord, PartialOrd, Eq)] pub(crate) enum StringDelimiter { Backtick, QuoteDouble, QuoteSingle, } just-1.40.0/src/string_kind.rs000064400000000000000000000051031046102023000143420ustar 00000000000000use super::*; #[derive(Debug, PartialEq, Clone, Copy, Ord, PartialOrd, Eq)] pub(crate) struct StringKind { pub(crate) delimiter: StringDelimiter, pub(crate) indented: bool, } impl StringKind { // Indented values must come before un-indented values, or else // `Self::from_token_start` will incorrectly return indented = false // for indented strings. const ALL: &'static [Self] = &[ Self::new(StringDelimiter::Backtick, true), Self::new(StringDelimiter::Backtick, false), Self::new(StringDelimiter::QuoteDouble, true), Self::new(StringDelimiter::QuoteDouble, false), Self::new(StringDelimiter::QuoteSingle, true), Self::new(StringDelimiter::QuoteSingle, false), ]; const fn new(delimiter: StringDelimiter, indented: bool) -> Self { Self { delimiter, indented, } } pub(crate) fn delimiter(self) -> &'static str { match (self.delimiter, self.indented) { (StringDelimiter::Backtick, false) => "`", (StringDelimiter::Backtick, true) => "```", (StringDelimiter::QuoteDouble, false) => "\"", (StringDelimiter::QuoteDouble, true) => "\"\"\"", (StringDelimiter::QuoteSingle, false) => "'", (StringDelimiter::QuoteSingle, true) => "'''", } } pub(crate) fn delimiter_len(self) -> usize { self.delimiter().len() } pub(crate) fn token_kind(self) -> TokenKind { match self.delimiter { StringDelimiter::QuoteDouble | StringDelimiter::QuoteSingle => TokenKind::StringToken, StringDelimiter::Backtick => TokenKind::Backtick, } } pub(crate) fn unterminated_error_kind(self) -> CompileErrorKind<'static> { match self.delimiter { StringDelimiter::QuoteDouble | StringDelimiter::QuoteSingle => { CompileErrorKind::UnterminatedString } StringDelimiter::Backtick => CompileErrorKind::UnterminatedBacktick, } } pub(crate) fn processes_escape_sequences(self) -> bool { match self.delimiter { StringDelimiter::QuoteDouble => true, StringDelimiter::Backtick | StringDelimiter::QuoteSingle => false, } } pub(crate) fn indented(self) -> bool { self.indented } pub(crate) fn from_string_or_backtick(token: Token) -> CompileResult { Self::from_token_start(token.lexeme()).ok_or_else(|| { token.error(CompileErrorKind::Internal { message: "StringKind::from_token: Expected String or Backtick".to_owned(), }) }) } pub(crate) fn from_token_start(token_start: &str) -> Option { Self::ALL .iter() .find(|&&kind| token_start.starts_with(kind.delimiter())) .copied() } } just-1.40.0/src/string_literal.rs000064400000000000000000000016711046102023000150570ustar 00000000000000use super::*; #[derive(PartialEq, Debug, Clone, Ord, Eq, PartialOrd)] pub(crate) struct StringLiteral<'src> { pub(crate) cooked: String, pub(crate) expand: bool, pub(crate) kind: StringKind, pub(crate) raw: &'src str, } impl<'src> StringLiteral<'src> { pub(crate) fn from_raw(raw: &'src str) -> Self { Self { cooked: raw.into(), expand: false, kind: StringKind { delimiter: StringDelimiter::QuoteSingle, indented: false, }, raw, } } } impl Display for StringLiteral<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.expand { write!(f, "x")?; } write!( f, "{}{}{}", self.kind.delimiter(), self.raw, self.kind.delimiter() ) } } impl Serialize for StringLiteral<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.cooked) } } just-1.40.0/src/subcommand.rs000064400000000000000000000504751046102023000141730ustar 00000000000000use {super::*, clap_mangen::Man}; const INIT_JUSTFILE: &str = "default:\n echo 'Hello, world!'\n"; fn backtick_re() -> &'static Regex { static BACKTICK_RE: OnceLock = OnceLock::new(); BACKTICK_RE.get_or_init(|| Regex::new("(`.*?`)|(`[^`]*$)").unwrap()) } #[derive(PartialEq, Clone, Debug)] pub(crate) enum Subcommand { Changelog, Choose { overrides: BTreeMap, chooser: Option, }, Command { arguments: Vec, binary: OsString, overrides: BTreeMap, }, Completions { shell: completions::Shell, }, Dump, Edit, Evaluate { overrides: BTreeMap, variable: Option, }, Format, Groups, Init, List { path: ModulePath, }, Man, Request { request: Request, }, Run { arguments: Vec, overrides: BTreeMap, }, Show { path: ModulePath, }, Summary, Variables, } impl Subcommand { pub(crate) fn execute<'src>(&self, config: &Config, loader: &'src Loader) -> RunResult<'src> { use Subcommand::*; match self { Changelog => { Self::changelog(); return Ok(()); } Completions { shell } => return Self::completions(*shell), Init => return Self::init(config), Man => return Self::man(), _ => {} } let search = Search::find(&config.search_config, &config.invocation_directory)?; if let Edit = self { return Self::edit(&search); } let compilation = Self::compile(config, loader, &search)?; let justfile = &compilation.justfile; match self { Choose { overrides, chooser } => { Self::choose(config, justfile, &search, overrides, chooser.as_deref())?; } Command { overrides, .. } | Evaluate { overrides, .. } => { justfile.run(config, &search, overrides, &[])?; } Dump => Self::dump(config, compilation)?, Format => Self::format(config, &search, compilation)?, Groups => Self::groups(config, justfile), List { path } => Self::list(config, justfile, path)?, Request { request } => Self::request(request)?, Run { arguments, overrides, } => Self::run(config, loader, search, compilation, arguments, overrides)?, Show { path } => Self::show(config, justfile, path)?, Summary => Self::summary(config, justfile), Variables => Self::variables(justfile), Changelog | Completions { .. } | Edit | Init | Man => unreachable!(), } Ok(()) } fn groups(config: &Config, justfile: &Justfile) { println!("Recipe groups:"); for group in justfile.public_groups(config) { println!("{}{group}", config.list_prefix); } } fn run<'src>( config: &Config, loader: &'src Loader, mut search: Search, mut compilation: Compilation<'src>, arguments: &[String], overrides: &BTreeMap, ) -> RunResult<'src> { let starting_parent = search.justfile.parent().as_ref().unwrap().lexiclean(); loop { let justfile = &compilation.justfile; let fallback = justfile.settings.fallback && matches!( config.search_config, SearchConfig::FromInvocationDirectory | SearchConfig::FromSearchDirectory { .. } ); let result = justfile.run(config, &search, overrides, arguments); if fallback { if let Err(err @ (Error::UnknownRecipe { .. } | Error::UnknownSubmodule { .. })) = result { search = search.search_parent_directory().map_err(|_| err)?; if config.verbosity.loquacious() { eprintln!( "Trying {}", starting_parent .strip_prefix(search.justfile.parent().unwrap()) .unwrap() .components() .map(|_| path::Component::ParentDir) .collect::() .join(search.justfile.file_name().unwrap()) .display() ); } compilation = Self::compile(config, loader, &search)?; continue; } } if config.allow_missing && matches!( result, Err(Error::UnknownRecipe { .. } | Error::UnknownSubmodule { .. }) ) { return Ok(()); } return result; } } fn compile<'src>( config: &Config, loader: &'src Loader, search: &Search, ) -> RunResult<'src, Compilation<'src>> { let compilation = Compiler::compile(loader, &search.justfile)?; compilation.justfile.check_unstable(config)?; if config.verbosity.loud() { for warning in &compilation.justfile.warnings { eprintln!("{}", warning.color_display(config.color.stderr())); } } Ok(compilation) } fn changelog() { write!(io::stdout(), "{}", include_str!("../CHANGELOG.md")).ok(); } fn choose<'src>( config: &Config, justfile: &Justfile<'src>, search: &Search, overrides: &BTreeMap, chooser: Option<&str>, ) -> RunResult<'src> { let mut recipes = Vec::<&Recipe>::new(); let mut stack = vec![justfile]; while let Some(module) = stack.pop() { recipes.extend( module .public_recipes(config) .iter() .filter(|recipe| recipe.min_arguments() == 0), ); stack.extend(module.modules.values()); } if recipes.is_empty() { return Err(Error::NoChoosableRecipes); } let chooser = if let Some(chooser) = chooser { OsString::from(chooser) } else { let mut chooser = OsString::new(); chooser.push("fzf --multi --preview 'just --unstable --color always --justfile \""); chooser.push(&search.justfile); chooser.push("\" --show {}'"); chooser }; let result = justfile .settings .shell_command(config) .arg(&chooser) .current_dir(&search.working_directory) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn(); let mut child = match result { Ok(child) => child, Err(io_error) => { let (shell_binary, shell_arguments) = justfile.settings.shell(config); return Err(Error::ChooserInvoke { shell_binary: shell_binary.to_owned(), shell_arguments: shell_arguments.join(" "), chooser, io_error, }); } }; let stdin = child.stdin.as_mut().unwrap(); for recipe in recipes { if let Err(io_error) = writeln!(stdin, "{}", recipe.namepath.spaced()) { if io_error.kind() != std::io::ErrorKind::BrokenPipe { return Err(Error::ChooserWrite { io_error, chooser }); } } } let output = match child.wait_with_output() { Ok(output) => output, Err(io_error) => { return Err(Error::ChooserRead { io_error, chooser }); } }; if !output.status.success() { return Err(Error::ChooserStatus { status: output.status, chooser, }); } let stdout = String::from_utf8_lossy(&output.stdout); let recipes = stdout .split_whitespace() .map(str::to_owned) .collect::>(); justfile.run(config, search, overrides, &recipes) } fn completions(shell: completions::Shell) -> RunResult<'static, ()> { println!("{}", shell.script()?); Ok(()) } fn dump(config: &Config, compilation: Compilation) -> RunResult<'static> { match config.dump_format { DumpFormat::Json => { serde_json::to_writer(io::stdout(), &compilation.justfile) .map_err(|source| Error::DumpJson { source })?; println!(); } DumpFormat::Just => print!("{}", compilation.root_ast()), } Ok(()) } fn edit(search: &Search) -> RunResult<'static> { let editor = env::var_os("VISUAL") .or_else(|| env::var_os("EDITOR")) .unwrap_or_else(|| "vim".into()); let error = Command::new(&editor) .current_dir(&search.working_directory) .arg(&search.justfile) .status(); let status = match error { Err(io_error) => return Err(Error::EditorInvoke { editor, io_error }), Ok(status) => status, }; if !status.success() { return Err(Error::EditorStatus { editor, status }); } Ok(()) } fn format(config: &Config, search: &Search, compilation: Compilation) -> RunResult<'static> { let justfile = &compilation.justfile; let src = compilation.root_src(); let ast = compilation.root_ast(); config.require_unstable(justfile, UnstableFeature::FormatSubcommand)?; let formatted = ast.to_string(); if formatted == src { return Ok(()); } if config.check { if !config.verbosity.quiet() { use similar::{ChangeTag, TextDiff}; let diff = TextDiff::configure() .algorithm(similar::Algorithm::Patience) .diff_lines(src, &formatted); for op in diff.ops() { for change in diff.iter_changes(op) { let (symbol, color) = match change.tag() { ChangeTag::Delete => ("-", config.color.stdout().diff_deleted()), ChangeTag::Equal => (" ", config.color.stdout()), ChangeTag::Insert => ("+", config.color.stdout().diff_added()), }; print!("{}{symbol}{change}{}", color.prefix(), color.suffix()); } } } Err(Error::FormatCheckFoundDiff) } else { fs::write(&search.justfile, formatted).map_err(|io_error| Error::WriteJustfile { justfile: search.justfile.clone(), io_error, })?; if config.verbosity.loud() { eprintln!("Wrote justfile to `{}`", search.justfile.display()); } Ok(()) } } fn init(config: &Config) -> RunResult<'static> { let search = Search::init(&config.search_config, &config.invocation_directory)?; if search.justfile.is_file() { return Err(Error::InitExists { justfile: search.justfile, }); } if let Err(io_error) = fs::write(&search.justfile, INIT_JUSTFILE) { return Err(Error::WriteJustfile { justfile: search.justfile, io_error, }); } if config.verbosity.loud() { eprintln!("Wrote justfile to `{}`", search.justfile.display()); } Ok(()) } fn man() -> RunResult<'static> { let mut buffer = Vec::::new(); Man::new(Config::app()) .render(&mut buffer) .expect("writing to buffer cannot fail"); let mut stdout = io::stdout().lock(); stdout .write_all(&buffer) .map_err(|io_error| Error::StdoutIo { io_error })?; stdout .flush() .map_err(|io_error| Error::StdoutIo { io_error })?; Ok(()) } fn request(request: &Request) -> RunResult<'static> { let response = match request { Request::EnvironmentVariable(key) => Response::EnvironmentVariable(env::var_os(key)), }; serde_json::to_writer(io::stdout(), &response).map_err(|source| Error::DumpJson { source })?; Ok(()) } fn list(config: &Config, mut module: &Justfile, path: &ModulePath) -> RunResult<'static> { for name in &path.path { module = module .modules .get(name) .ok_or_else(|| Error::UnknownSubmodule { path: path.to_string(), })?; } Self::list_module(config, module, 0); Ok(()) } fn list_module(config: &Config, module: &Justfile, depth: usize) { fn print_doc_and_aliases( config: &Config, name: &str, doc: Option<&str>, aliases: &[&str], max_signature_width: usize, signature_widths: &BTreeMap<&str, usize>, ) { let color = config.color.stdout(); let inline_aliases = config.alias_style != AliasStyle::Separate && !aliases.is_empty(); if inline_aliases || doc.is_some() { print!( "{:padding$}{}", "", color.doc().paint("#"), padding = max_signature_width.saturating_sub(signature_widths[name]) + 1, ); } let print_aliases = || { print!( " {}", color.alias().paint(&format!( "[alias{}: {}]", if aliases.len() == 1 { "" } else { "es" }, aliases.join(", ") )) ); }; if inline_aliases && config.alias_style == AliasStyle::Left { print_aliases(); } if let Some(doc) = doc { print!(" "); let mut end = 0; for backtick in backtick_re().find_iter(doc) { let prefix = &doc[end..backtick.start()]; if !prefix.is_empty() { print!("{}", color.doc().paint(prefix)); } print!("{}", color.doc_backtick().paint(backtick.as_str())); end = backtick.end(); } let suffix = &doc[end..]; if !suffix.is_empty() { print!("{}", color.doc().paint(suffix)); } } if inline_aliases && config.alias_style == AliasStyle::Right { print_aliases(); } println!(); } let aliases = if config.no_aliases { BTreeMap::new() } else { let mut aliases = BTreeMap::<&str, Vec<&str>>::new(); for alias in module.aliases.values().filter(|alias| !alias.is_private()) { aliases .entry(alias.target.name.lexeme()) .or_default() .push(alias.name.lexeme()); } aliases }; let signature_widths = { let mut signature_widths: BTreeMap<&str, usize> = BTreeMap::new(); for (name, recipe) in &module.recipes { if !recipe.is_public() { continue; } for name in iter::once(name).chain(aliases.get(name).unwrap_or(&Vec::new())) { signature_widths.insert( name, UnicodeWidthStr::width( RecipeSignature { name, recipe } .color_display(Color::never()) .to_string() .as_str(), ), ); } } if !config.list_submodules { for (name, _) in &module.modules { signature_widths.insert(name, UnicodeWidthStr::width(format!("{name} ...").as_str())); } } signature_widths }; let max_signature_width = signature_widths .values() .copied() .filter(|width| *width <= 50) .max() .unwrap_or(0); let list_prefix = config.list_prefix.repeat(depth + 1); if depth == 0 { print!("{}", config.list_heading); } let recipe_groups = { let mut groups = BTreeMap::, Vec<&Recipe>>::new(); for recipe in module.public_recipes(config) { let recipe_groups = recipe.groups(); if recipe_groups.is_empty() { groups.entry(None).or_default().push(recipe); } else { for group in recipe_groups { groups.entry(Some(group)).or_default().push(recipe); } } } groups }; let submodule_groups = { let mut groups = BTreeMap::, Vec<&Justfile>>::new(); for submodule in module.modules(config) { let submodule_groups = submodule.groups(); if submodule_groups.is_empty() { groups.entry(None).or_default().push(submodule); } else { for group in submodule_groups { groups .entry(Some(group.to_string())) .or_default() .push(submodule); } } } groups }; let mut ordered_groups = module .public_groups(config) .into_iter() .map(Some) .collect::>>(); if recipe_groups.contains_key(&None) || submodule_groups.contains_key(&None) { ordered_groups.insert(0, None); } let no_groups = ordered_groups.len() == 1 && ordered_groups.first() == Some(&None); let mut groups_count = 0; if !no_groups { groups_count = ordered_groups.len(); } for (i, group) in ordered_groups.into_iter().enumerate() { if i > 0 { println!(); } if !no_groups { if let Some(group) = &group { println!( "{list_prefix}{}", config.color.stdout().group().paint(&format!("[{group}]")) ); } } if let Some(recipes) = recipe_groups.get(&group) { for recipe in recipes { let recipe_alias_entries = if config.alias_style == AliasStyle::Separate { aliases.get(recipe.name()) } else { None }; for (i, name) in iter::once(&recipe.name()) .chain(recipe_alias_entries.unwrap_or(&Vec::new())) .enumerate() { let doc = if i == 0 { recipe.doc().map(Cow::Borrowed) } else { Some(Cow::Owned(format!("alias for `{}`", recipe.name))) }; if let Some(doc) = &doc { if doc.lines().count() > 1 { for line in doc.lines() { println!( "{list_prefix}{} {}", config.color.stdout().doc().paint("#"), config.color.stdout().doc().paint(line), ); } } } print!( "{list_prefix}{}", RecipeSignature { name, recipe }.color_display(config.color.stdout()) ); print_doc_and_aliases( config, name, doc.filter(|doc| doc.lines().count() <= 1).as_deref(), aliases .get(recipe.name()) .map(Vec::as_slice) .unwrap_or_default(), max_signature_width, &signature_widths, ); } } } if let Some(submodules) = submodule_groups.get(&group) { for (i, submodule) in submodules.iter().enumerate() { if config.list_submodules { if no_groups && (i + groups_count > 0) { println!(); } println!("{list_prefix}{}:", submodule.name()); Self::list_module(config, submodule, depth + 1); } else { print!("{list_prefix}{} ...", submodule.name()); print_doc_and_aliases( config, submodule.name(), submodule.doc.as_deref(), &[], max_signature_width, &signature_widths, ); } } } } } fn show<'src>( config: &Config, mut module: &Justfile<'src>, path: &ModulePath, ) -> RunResult<'src> { for name in &path.path[0..path.path.len() - 1] { module = module .modules .get(name) .ok_or_else(|| Error::UnknownSubmodule { path: path.to_string(), })?; } let name = path.path.last().unwrap(); if let Some(alias) = module.get_alias(name) { let recipe = module.get_recipe(alias.target.name.lexeme()).unwrap(); println!("{alias}"); println!("{}", recipe.color_display(config.color.stdout())); Ok(()) } else if let Some(recipe) = module.get_recipe(name) { println!("{}", recipe.color_display(config.color.stdout())); Ok(()) } else { Err(Error::UnknownRecipe { recipe: name.to_owned(), suggestion: module.suggest_recipe(name), }) } } fn summary(config: &Config, justfile: &Justfile) { let mut printed = 0; Self::summary_recursive(config, &mut Vec::new(), &mut printed, justfile); println!(); if printed == 0 && config.verbosity.loud() { eprintln!("Justfile contains no recipes."); } } fn summary_recursive<'a>( config: &Config, components: &mut Vec<&'a str>, printed: &mut usize, justfile: &'a Justfile, ) { let path = components.join("::"); for recipe in justfile.public_recipes(config) { if *printed > 0 { print!(" "); } if path.is_empty() { print!("{}", recipe.name()); } else { print!("{}::{}", path, recipe.name()); } *printed += 1; } for (name, module) in &justfile.modules { components.push(name); Self::summary_recursive(config, components, printed, module); components.pop(); } } fn variables(justfile: &Justfile) { for (i, (_, assignment)) in justfile .assignments .iter() .filter(|(_, binding)| !binding.private) .enumerate() { if i > 0 { print!(" "); } print!("{}", assignment.name); } println!(); } } #[cfg(test)] mod tests { use super::*; #[test] fn init_justfile() { testing::compile(INIT_JUSTFILE); } } just-1.40.0/src/suggestion.rs000064400000000000000000000006421046102023000142210ustar 00000000000000use super::*; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Suggestion<'src> { pub(crate) name: &'src str, pub(crate) target: Option<&'src str>, } impl Display for Suggestion<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Did you mean `{}`", self.name)?; if let Some(target) = self.target { write!(f, ", an alias for `{target}`")?; } write!(f, "?") } } just-1.40.0/src/summary.rs000064400000000000000000000242421046102023000135310ustar 00000000000000//! Justfile summary creation, for testing purposes only. //! //! The contents of this module are not bound by any stability guarantees. //! Breaking changes may be introduced at any time. //! //! The main entry point into this module is the `summary` function, which //! parses a justfile at a given path and produces a `Summary` object, which //! broadly captures the functionality of the parsed justfile, or an error //! message. //! //! This functionality is intended to be used with `janus`, a tool for ensuring //! that changes to just do not inadvertently break or change the interpretation //! of existing justfiles. use { crate::{compiler::Compiler, error::Error, loader::Loader}, std::{collections::BTreeMap, io, path::Path}, }; mod full { pub(crate) use crate::{ assignment::Assignment, condition::Condition, conditional_operator::ConditionalOperator, dependency::Dependency, expression::Expression, fragment::Fragment, justfile::Justfile, line::Line, parameter::Parameter, parameter_kind::ParameterKind, recipe::Recipe, thunk::Thunk, }; } pub fn summary(path: &Path) -> io::Result> { let loader = Loader::new(); match Compiler::compile(&loader, path) { Ok(compilation) => Ok(Ok(Summary::new(&compilation.justfile))), Err(error) => Ok(Err(if let Error::Compile { compile_error } = error { compile_error.to_string() } else { format!("{error:?}") })), } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Summary { pub assignments: BTreeMap, pub recipes: BTreeMap, } impl Summary { fn new(justfile: &full::Justfile) -> Self { let mut aliases = BTreeMap::new(); for alias in justfile.aliases.values() { aliases .entry(alias.target.name()) .or_insert_with(Vec::new) .push(alias.name.to_string()); } Self { recipes: justfile .recipes .iter() .map(|(name, recipe)| { ( (*name).to_string(), Recipe::new(recipe, aliases.remove(name).unwrap_or_default()), ) }) .collect(), assignments: justfile .assignments .iter() .map(|(name, assignment)| ((*name).to_owned(), Assignment::new(assignment))) .collect(), } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Recipe { pub aliases: Vec, pub dependencies: Vec, pub lines: Vec, pub parameters: Vec, pub private: bool, pub quiet: bool, pub shebang: bool, } impl Recipe { fn new(recipe: &full::Recipe, aliases: Vec) -> Self { Self { aliases, dependencies: recipe.dependencies.iter().map(Dependency::new).collect(), lines: recipe.body.iter().map(Line::new).collect(), parameters: recipe.parameters.iter().map(Parameter::new).collect(), private: recipe.private, quiet: recipe.quiet, shebang: recipe.shebang, } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Parameter { pub default: Option, pub kind: ParameterKind, pub name: String, } impl Parameter { fn new(parameter: &full::Parameter) -> Self { Self { kind: ParameterKind::new(parameter.kind), name: parameter.name.lexeme().to_owned(), default: parameter.default.as_ref().map(Expression::new), } } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum ParameterKind { Plus, Singular, Star, } impl ParameterKind { fn new(parameter_kind: full::ParameterKind) -> Self { match parameter_kind { full::ParameterKind::Singular => Self::Singular, full::ParameterKind::Plus => Self::Plus, full::ParameterKind::Star => Self::Star, } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Line { pub fragments: Vec, } impl Line { fn new(line: &full::Line) -> Self { Self { fragments: line.fragments.iter().map(Fragment::new).collect(), } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub enum Fragment { Expression { expression: Expression }, Text { text: String }, } impl Fragment { fn new(fragment: &full::Fragment) -> Self { match fragment { full::Fragment::Text { token } => Self::Text { text: token.lexeme().to_owned(), }, full::Fragment::Interpolation { expression } => Self::Expression { expression: Expression::new(expression), }, } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Assignment { pub exported: bool, pub expression: Expression, } impl Assignment { fn new(assignment: &full::Assignment) -> Self { Self { exported: assignment.export, expression: Expression::new(&assignment.value), } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub enum Expression { And { lhs: Box, rhs: Box, }, Assert { condition: Condition, error: Box, }, Backtick { command: String, }, Call { name: String, arguments: Vec, }, Concatenation { lhs: Box, rhs: Box, }, Conditional { lhs: Box, rhs: Box, then: Box, otherwise: Box, operator: ConditionalOperator, }, Join { lhs: Option>, rhs: Box, }, Or { lhs: Box, rhs: Box, }, String { text: String, }, Variable { name: String, }, } impl Expression { fn new(expression: &full::Expression) -> Self { use full::Expression::*; match expression { And { lhs, rhs } => Self::And { lhs: Self::new(lhs).into(), rhs: Self::new(rhs).into(), }, Assert { condition: full::Condition { lhs, rhs, operator }, error, } => Expression::Assert { condition: Condition { lhs: Box::new(Expression::new(lhs)), rhs: Box::new(Expression::new(rhs)), operator: ConditionalOperator::new(*operator), }, error: Box::new(Expression::new(error)), }, Backtick { contents, .. } => Self::Backtick { command: (*contents).clone(), }, Call { thunk } => match thunk { full::Thunk::Nullary { name, .. } => Self::Call { name: name.lexeme().to_owned(), arguments: Vec::new(), }, full::Thunk::Unary { name, arg, .. } => Self::Call { name: name.lexeme().to_owned(), arguments: vec![Self::new(arg)], }, full::Thunk::UnaryOpt { name, args: (a, opt_b), .. } => { let mut arguments = Vec::new(); if let Some(b) = opt_b.as_ref() { arguments.push(Self::new(b)); } arguments.push(Self::new(a)); Self::Call { name: name.lexeme().to_owned(), arguments, } } full::Thunk::UnaryPlus { name, args: (a, rest), .. } => { let mut arguments = vec![Expression::new(a)]; for arg in rest { arguments.push(Expression::new(arg)); } Expression::Call { name: name.lexeme().to_owned(), arguments, } } full::Thunk::Binary { name, args: [a, b], .. } => Self::Call { name: name.lexeme().to_owned(), arguments: vec![Self::new(a), Self::new(b)], }, full::Thunk::BinaryPlus { name, args: ([a, b], rest), .. } => { let mut arguments = vec![Self::new(a), Self::new(b)]; for arg in rest { arguments.push(Self::new(arg)); } Self::Call { name: name.lexeme().to_owned(), arguments, } } full::Thunk::Ternary { name, args: [a, b, c], .. } => Self::Call { name: name.lexeme().to_owned(), arguments: vec![Self::new(a), Self::new(b), Self::new(c)], }, }, Concatenation { lhs, rhs } => Self::Concatenation { lhs: Self::new(lhs).into(), rhs: Self::new(rhs).into(), }, Conditional { condition: full::Condition { lhs, rhs, operator }, otherwise, then, } => Self::Conditional { lhs: Self::new(lhs).into(), operator: ConditionalOperator::new(*operator), otherwise: Self::new(otherwise).into(), rhs: Self::new(rhs).into(), then: Self::new(then).into(), }, Group { contents } => Self::new(contents), Join { lhs, rhs } => Self::Join { lhs: lhs.as_ref().map(|lhs| Self::new(lhs).into()), rhs: Self::new(rhs).into(), }, Or { lhs, rhs } => Self::Or { lhs: Self::new(lhs).into(), rhs: Self::new(rhs).into(), }, StringLiteral { string_literal } => Self::String { text: string_literal.cooked.clone(), }, Variable { name, .. } => Self::Variable { name: name.lexeme().to_owned(), }, } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Condition { lhs: Box, operator: ConditionalOperator, rhs: Box, } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub enum ConditionalOperator { Equality, Inequality, RegexMatch, RegexMismatch, } impl ConditionalOperator { fn new(operator: full::ConditionalOperator) -> Self { match operator { full::ConditionalOperator::Equality => Self::Equality, full::ConditionalOperator::Inequality => Self::Inequality, full::ConditionalOperator::RegexMatch => Self::RegexMatch, full::ConditionalOperator::RegexMismatch => Self::RegexMismatch, } } } #[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Debug, Clone)] pub struct Dependency { pub arguments: Vec, pub recipe: String, } impl Dependency { fn new(dependency: &full::Dependency) -> Self { Self { recipe: dependency.recipe.name().to_owned(), arguments: dependency.arguments.iter().map(Expression::new).collect(), } } } just-1.40.0/src/table.rs000064400000000000000000000043031046102023000131170ustar 00000000000000use {super::*, std::collections::btree_map}; #[derive(Debug, PartialEq, Serialize)] #[serde(transparent)] pub(crate) struct Table<'key, V: Keyed<'key>> { map: BTreeMap<&'key str, V>, } impl<'key, V: Keyed<'key>> Table<'key, V> { pub(crate) fn new() -> Self { Self { map: BTreeMap::new(), } } pub(crate) fn insert(&mut self, value: V) { self.map.insert(value.key(), value); } pub(crate) fn len(&self) -> usize { self.map.len() } pub(crate) fn get(&self, key: &str) -> Option<&V> { self.map.get(key) } pub(crate) fn is_empty(&self) -> bool { self.map.is_empty() } pub(crate) fn values(&self) -> btree_map::Values<&'key str, V> { self.map.values() } pub(crate) fn contains_key(&self, key: &str) -> bool { self.map.contains_key(key) } pub(crate) fn keys(&self) -> btree_map::Keys<&'key str, V> { self.map.keys() } pub(crate) fn iter(&self) -> btree_map::Iter<&'key str, V> { self.map.iter() } pub(crate) fn pop(&mut self) -> Option { let key = self.map.keys().next().copied()?; self.map.remove(key) } pub(crate) fn remove(&mut self, key: &str) -> Option { self.map.remove(key) } } impl<'key, V: Keyed<'key>> Default for Table<'key, V> { fn default() -> Self { Self::new() } } impl<'key, V: Keyed<'key>> FromIterator for Table<'key, V> { fn from_iter>(iter: I) -> Self { Self { map: iter.into_iter().map(|value| (value.key(), value)).collect(), } } } impl<'key, V: Keyed<'key>> Index<&'key str> for Table<'key, V> { type Output = V; #[inline] fn index(&self, key: &str) -> &V { self.map.get(key).expect("no entry found for key") } } impl<'key, V: Keyed<'key>> IntoIterator for Table<'key, V> { type IntoIter = btree_map::IntoIter<&'key str, V>; type Item = (&'key str, V); fn into_iter(self) -> btree_map::IntoIter<&'key str, V> { self.map.into_iter() } } impl<'table, V: Keyed<'table> + 'table> IntoIterator for &'table Table<'table, V> { type IntoIter = btree_map::Iter<'table, &'table str, V>; type Item = (&'table &'table str, &'table V); fn into_iter(self) -> btree_map::Iter<'table, &'table str, V> { self.map.iter() } } just-1.40.0/src/testing.rs000064400000000000000000000065071046102023000135150ustar 00000000000000use {super::*, pretty_assertions::assert_eq}; pub(crate) fn compile(src: &str) -> Justfile { Compiler::test_compile(src).expect("expected successful compilation") } pub(crate) fn config(args: &[&str]) -> Config { let mut args = Vec::from(args); args.insert(0, "just"); let app = Config::app(); let matches = app.try_get_matches_from(args).unwrap(); Config::from_matches(&matches).unwrap() } pub(crate) fn search(config: &Config) -> Search { let working_directory = config.invocation_directory.clone(); let justfile = working_directory.join("justfile"); Search { justfile, working_directory, } } pub(crate) fn tempdir() -> tempfile::TempDir { tempfile::Builder::new() .prefix("just-test-tempdir") .tempdir() .expect("failed to create temporary directory") } macro_rules! analysis_error { ( name: $name:ident, input: $input:expr, offset: $offset:expr, line: $line:expr, column: $column:expr, width: $width:expr, kind: $kind:expr, ) => { #[test] fn $name() { $crate::testing::analysis_error($input, $offset, $line, $column, $width, $kind); } }; } pub(crate) fn analysis_error( src: &str, offset: usize, line: usize, column: usize, length: usize, kind: CompileErrorKind, ) { let tokens = Lexer::test_lex(src).expect("Lexing failed in parse test..."); let ast = Parser::parse(0, &[], None, &tokens, &PathBuf::new()) .expect("Parsing failed in analysis test..."); let root = PathBuf::from("justfile"); let mut asts: HashMap = HashMap::new(); asts.insert(root.clone(), ast); let mut paths: HashMap = HashMap::new(); paths.insert("justfile".into(), "justfile".into()); match Analyzer::analyze(&asts, None, &[], &[], None, &paths, &root) { Ok(_) => panic!("Analysis unexpectedly succeeded"), Err(have) => { let want = CompileError { token: Token { kind: have.token.kind, src, offset, line, column, length, path: "justfile".as_ref(), }, kind: kind.into(), }; assert_eq!(have, want); } } } macro_rules! run_error { { name: $name:ident, src: $src:expr, args: $args:expr, error: $error:pat, check: $check:block $(,)? } => { #[test] fn $name() { let config = $crate::testing::config(&$args); let search = $crate::testing::search(&config); if let Subcommand::Run{ overrides, arguments } = &config.subcommand { match $crate::testing::compile(&$crate::unindent::unindent($src)) .run( &config, &search, &overrides, &arguments, ).expect_err("Expected runtime error") { $error => $check other => { panic!("Unexpected run error: {other:?}"); } } } else { panic!("Unexpected subcommand: {:?}", config.subcommand); } } }; } macro_rules! assert_matches { ($expression:expr, $( $pattern:pat_param )|+ $( if $guard:expr )? $(,)?) => { match $expression { $( $pattern )|+ $( if $guard )? => {} left => panic!( "assertion failed: (left ~= right)\n left: `{:?}`\n right: `{}`", left, stringify!($($pattern)|+ $(if $guard)?) ), } } } just-1.40.0/src/thunk.rs000064400000000000000000000147071046102023000131720ustar 00000000000000use super::*; #[allow(clippy::arbitrary_source_item_ordering)] #[derive_where(Debug, PartialEq)] #[derive(Clone)] pub(crate) enum Thunk<'src> { Nullary { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context) -> FunctionResult, }, Unary { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str) -> FunctionResult, arg: Box>, }, UnaryOpt { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str, Option<&str>) -> FunctionResult, args: (Box>, Box>>), }, UnaryPlus { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str, &[String]) -> FunctionResult, args: (Box>, Vec>), }, Binary { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str, &str) -> FunctionResult, args: [Box>; 2], }, BinaryPlus { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str, &str, &[String]) -> FunctionResult, args: ([Box>; 2], Vec>), }, Ternary { name: Name<'src>, #[derive_where(skip(Debug, EqHashOrd))] function: fn(function::Context, &str, &str, &str) -> FunctionResult, args: [Box>; 3], }, } impl<'src> Thunk<'src> { pub(crate) fn name(&self) -> Name<'src> { match self { Self::Nullary { name, .. } | Self::Unary { name, .. } | Self::UnaryOpt { name, .. } | Self::UnaryPlus { name, .. } | Self::Binary { name, .. } | Self::BinaryPlus { name, .. } | Self::Ternary { name, .. } => *name, } } pub(crate) fn resolve( name: Name<'src>, mut arguments: Vec>, ) -> CompileResult<'src, Thunk<'src>> { function::get(name.lexeme()).map_or( Err(name.error(CompileErrorKind::UnknownFunction { function: name.lexeme(), })), |function| match (function, arguments.len()) { (Function::Nullary(function), 0) => Ok(Thunk::Nullary { function, name }), (Function::Unary(function), 1) => Ok(Thunk::Unary { function, arg: arguments.pop().unwrap().into(), name, }), (Function::UnaryOpt(function), 1..=2) => { let a = arguments.remove(0).into(); let b = match arguments.pop() { Some(value) => Some(value).into(), None => None.into(), }; Ok(Thunk::UnaryOpt { function, args: (a, b), name, }) } (Function::UnaryPlus(function), 1..=usize::MAX) => { let rest = arguments.drain(1..).collect(); let a = Box::new(arguments.pop().unwrap()); Ok(Thunk::UnaryPlus { function, args: (a, rest), name, }) } (Function::Binary(function), 2) => { let b = arguments.pop().unwrap().into(); let a = arguments.pop().unwrap().into(); Ok(Thunk::Binary { function, args: [a, b], name, }) } (Function::BinaryPlus(function), 2..=usize::MAX) => { let rest = arguments.drain(2..).collect(); let b = arguments.pop().unwrap().into(); let a = arguments.pop().unwrap().into(); Ok(Thunk::BinaryPlus { function, args: ([a, b], rest), name, }) } (Function::Ternary(function), 3) => { let c = arguments.pop().unwrap().into(); let b = arguments.pop().unwrap().into(); let a = arguments.pop().unwrap().into(); Ok(Thunk::Ternary { function, args: [a, b, c], name, }) } (function, _) => Err(name.error(CompileErrorKind::FunctionArgumentCountMismatch { function: name.lexeme(), found: arguments.len(), expected: function.argc(), })), }, ) } } impl Display for Thunk<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Thunk::*; match self { Nullary { name, .. } => write!(f, "{}()", name.lexeme()), Unary { name, arg, .. } => write!(f, "{}({arg})", name.lexeme()), UnaryOpt { name, args: (a, b), .. } => { if let Some(b) = b.as_ref() { write!(f, "{}({a}, {b})", name.lexeme()) } else { write!(f, "{}({a})", name.lexeme()) } } UnaryPlus { name, args: (a, rest), .. } => { write!(f, "{}({a}", name.lexeme())?; for arg in rest { write!(f, ", {arg}")?; } write!(f, ")") } Binary { name, args: [a, b], .. } => write!(f, "{}({a}, {b})", name.lexeme()), BinaryPlus { name, args: ([a, b], rest), .. } => { write!(f, "{}({a}, {b}", name.lexeme())?; for arg in rest { write!(f, ", {arg}")?; } write!(f, ")") } Ternary { name, args: [a, b, c], .. } => write!(f, "{}({a}, {b}, {c})", name.lexeme()), } } } impl Serialize for Thunk<'_> { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element("call")?; seq.serialize_element(&self.name())?; match self { Self::Nullary { .. } => {} Self::Unary { arg, .. } => seq.serialize_element(&arg)?, Self::UnaryOpt { args: (a, opt_b), .. } => { seq.serialize_element(a)?; if let Some(b) = opt_b.as_ref() { seq.serialize_element(b)?; } } Self::UnaryPlus { args: (a, rest), .. } => { seq.serialize_element(a)?; for arg in rest { seq.serialize_element(arg)?; } } Self::Binary { args, .. } => { for arg in args { seq.serialize_element(arg)?; } } Self::BinaryPlus { args, .. } => { for arg in args.0.iter().map(Box::as_ref).chain(&args.1) { seq.serialize_element(arg)?; } } Self::Ternary { args, .. } => { for arg in args { seq.serialize_element(arg)?; } } } seq.end() } } just-1.40.0/src/token.rs000064400000000000000000000054261046102023000131570ustar 00000000000000use super::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub(crate) struct Token<'src> { pub(crate) column: usize, pub(crate) kind: TokenKind, pub(crate) length: usize, pub(crate) line: usize, pub(crate) offset: usize, pub(crate) path: &'src Path, pub(crate) src: &'src str, } impl<'src> Token<'src> { pub(crate) fn lexeme(&self) -> &'src str { &self.src[self.offset..self.offset + self.length] } pub(crate) fn error(&self, kind: CompileErrorKind<'src>) -> CompileError<'src> { CompileError::new(*self, kind) } } impl ColorDisplay for Token<'_> { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { let width = if self.length == 0 { 1 } else { self.length }; let line_number = self.line.ordinal(); match self.src.lines().nth(self.line) { Some(line) => { let mut i = 0; let mut space_column = 0; let mut space_line = String::new(); let mut space_width = 0; for c in line.chars() { if c == '\t' { space_line.push_str(" "); if i < self.column { space_column += 4; } if i >= self.column && i < self.column + width { space_width += 4; } } else { if i < self.column { space_column += UnicodeWidthChar::width(c).unwrap_or(0); } if i >= self.column && i < self.column + width { space_width += UnicodeWidthChar::width(c).unwrap_or(0); } space_line.push(c); } i += c.len_utf8(); } let line_number_width = line_number.to_string().len(); writeln!( f, "{:width$}{} {}:{}:{}", "", color.context().paint("——▶"), self.path.display(), line_number, self.column.ordinal(), width = line_number_width )?; writeln!( f, "{:width$} {}", "", color.context().paint("│"), width = line_number_width )?; writeln!( f, "{} {space_line}", color.context().paint(&format!("{line_number} │")) )?; write!( f, "{:width$} {}", "", color.context().paint("│"), width = line_number_width )?; write!( f, " {0:1$}{2}{3:^<4$}{5}", "", space_column, color.prefix(), "", space_width.max(1), color.suffix() )?; } None => { if self.offset != self.src.len() { write!( f, "internal error: Error has invalid line number: {line_number}" )?; } } } Ok(()) } } just-1.40.0/src/token_kind.rs000064400000000000000000000034501046102023000141570ustar 00000000000000use super::*; #[derive(Debug, PartialEq, Clone, Copy, Ord, PartialOrd, Eq)] pub(crate) enum TokenKind { AmpersandAmpersand, Asterisk, At, Backtick, BangEquals, BangTilde, BarBar, BraceL, BraceR, BracketL, BracketR, ByteOrderMark, Colon, ColonColon, ColonEquals, Comma, Comment, Dedent, Dollar, Eof, Eol, Equals, EqualsEquals, EqualsTilde, Identifier, Indent, InterpolationEnd, InterpolationStart, ParenL, ParenR, Plus, QuestionMark, Slash, StringToken, Text, Unspecified, Whitespace, } impl Display for TokenKind { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use TokenKind::*; write!( f, "{}", match *self { AmpersandAmpersand => "'&&'", Asterisk => "'*'", At => "'@'", Backtick => "backtick", BangEquals => "'!='", BangTilde => "'!~'", BarBar => "'||'", BraceL => "'{'", BraceR => "'}'", BracketL => "'['", BracketR => "']'", ByteOrderMark => "byte order mark", Colon => "':'", ColonColon => "'::'", ColonEquals => "':='", Comma => "','", Comment => "comment", Dedent => "dedent", Dollar => "'$'", Eof => "end of file", Eol => "end of line", Equals => "'='", EqualsEquals => "'=='", EqualsTilde => "'=~'", Identifier => "identifier", Indent => "indent", InterpolationEnd => "'}}'", InterpolationStart => "'{{'", ParenL => "'('", ParenR => "')'", Plus => "'+'", QuestionMark => "?", Slash => "'/'", StringToken => "string", Text => "command text", Unspecified => "unspecified", Whitespace => "whitespace", } ) } } just-1.40.0/src/tree.rs000064400000000000000000000062211046102023000127700ustar 00000000000000use {super::*, std::borrow::Cow}; /// Construct a `Tree` from a symbolic expression literal. This macro, and the /// Tree type, are only used in the Parser unit tests, providing a concise /// notation for representing the expected results of parsing a given string. macro_rules! tree { { ($($child:tt)*) } => { $crate::tree::Tree::List(vec![$(tree!($child),)*]) }; { $atom:ident } => { $crate::tree::Tree::atom(stringify!($atom)) }; { $atom:literal } => { $crate::tree::Tree::atom(format!("\"{}\"", $atom)) }; { # } => { $crate::tree::Tree::atom("#") }; { ? } => { $crate::tree::Tree::atom("?") }; { + } => { $crate::tree::Tree::atom("+") }; { * } => { $crate::tree::Tree::atom("*") }; { && } => { $crate::tree::Tree::atom("&&") }; { == } => { $crate::tree::Tree::atom("==") }; { != } => { $crate::tree::Tree::atom("!=") }; } /// A `Tree` is either… #[derive(Debug, PartialEq)] pub(crate) enum Tree<'text> { /// …an atom containing text, or… Atom(Cow<'text, str>), /// …a list containing zero or more `Tree`s. List(Vec), } impl<'text> Tree<'text> { /// Construct an Atom from a text scalar pub(crate) fn atom(text: impl Into>) -> Self { Self::Atom(text.into()) } /// Construct a List from an iterable of trees pub(crate) fn list(children: impl IntoIterator) -> Self { Self::List(children.into_iter().collect()) } /// Convenience function to create an atom containing quoted text pub(crate) fn string(contents: impl AsRef) -> Self { Self::atom(format!("\"{}\"", contents.as_ref())) } /// Push a child node into self, turning it into a List if it was an Atom pub(crate) fn push(self, tree: impl Into) -> Self { match self { Self::List(mut children) => { children.push(tree.into()); Self::List(children) } Self::Atom(text) => Self::List(vec![Self::Atom(text), tree.into()]), } } /// Extend a self with a tail of Trees, turning self into a List if it was an /// Atom pub(crate) fn extend(self, tail: I) -> Self where I: IntoIterator, T: Into, { // Tree::List(children.into_iter().collect()) let mut head = match self { Self::List(children) => children, Self::Atom(text) => vec![Self::Atom(text)], }; for child in tail { head.push(child.into()); } Self::List(head) } /// Like `push`, but modify self in-place pub(crate) fn push_mut(&mut self, tree: impl Into) { *self = mem::replace(self, Self::List(Vec::new())).push(tree.into()); } } impl Display for Tree<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::List(children) => { write!(f, "(")?; for (i, child) in children.iter().enumerate() { if i > 0 { write!(f, " ")?; } write!(f, "{child}")?; } write!(f, ")") } Self::Atom(text) => write!(f, "{text}"), } } } impl<'text, T> From for Tree<'text> where T: Into>, { fn from(text: T) -> Self { Self::Atom(text.into()) } } just-1.40.0/src/unindent.rs000064400000000000000000000055501046102023000136610ustar 00000000000000#[must_use] pub fn unindent(text: &str) -> String { // find line start and end indices let mut lines = Vec::new(); let mut start = 0; for (i, c) in text.char_indices() { if c == '\n' || i == text.len() - c.len_utf8() { let end = i + c.len_utf8(); lines.push(&text[start..end]); start = end; } } let common_indentation = lines .iter() .filter(|line| !blank(line)) .copied() .map(indentation) .fold( None, |common_indentation, line_indentation| match common_indentation { Some(common_indentation) => Some(common(common_indentation, line_indentation)), None => Some(line_indentation), }, ) .unwrap_or(""); let mut replacements = Vec::with_capacity(lines.len()); for (i, line) in lines.iter().enumerate() { let blank = blank(line); let first = i == 0; let last = i == lines.len() - 1; let replacement = match (blank, first, last) { (true, false, false) => "\n", (true, _, _) => "", (false, _, _) => &line[common_indentation.len()..], }; replacements.push(replacement); } replacements.into_iter().collect() } fn indentation(line: &str) -> &str { let i = line .char_indices() .take_while(|(_, c)| matches!(c, ' ' | '\t')) .map(|(i, _)| i + 1) .last() .unwrap_or(0); &line[..i] } fn blank(line: &str) -> bool { line.chars().all(|c| matches!(c, ' ' | '\t' | '\r' | '\n')) } fn common<'s>(a: &'s str, b: &'s str) -> &'s str { let i = a .char_indices() .zip(b.chars()) .take_while(|((_, ac), bc)| ac == bc) .map(|((i, c), _)| i + c.len_utf8()) .last() .unwrap_or(0); &a[0..i] } #[cfg(test)] mod tests { use super::*; #[test] fn unindents() { assert_eq!(unindent("foo"), "foo"); assert_eq!(unindent("foo\nbar\nbaz\n"), "foo\nbar\nbaz\n"); assert_eq!(unindent(""), ""); assert_eq!(unindent(" foo\n bar"), "foo\nbar"); assert_eq!(unindent(" foo\n bar\n\n"), "foo\nbar\n"); assert_eq!( unindent( " hello bar " ), "hello\nbar\n" ); assert_eq!(unindent("hello\n bar\n foo"), "hello\n bar\n foo"); assert_eq!( unindent( " hello bar " ), "\nhello\nbar\n\n" ); } #[test] fn indentations() { assert_eq!(indentation(""), ""); assert_eq!(indentation("foo"), ""); assert_eq!(indentation(" foo"), " "); assert_eq!(indentation("\t\tfoo"), "\t\t"); assert_eq!(indentation("\t \t foo"), "\t \t "); } #[test] fn blanks() { assert!(blank(" \n")); assert!(!blank(" foo\n")); assert!(blank("\t\t\n")); } #[test] fn commons() { assert_eq!(common("foo", "foobar"), "foo"); assert_eq!(common("foo", "bar"), ""); assert_eq!(common("", ""), ""); assert_eq!(common("", "bar"), ""); } } just-1.40.0/src/unresolved_dependency.rs000064400000000000000000000010031046102023000164060ustar 00000000000000use super::*; #[derive(PartialEq, Debug, Clone)] pub(crate) struct UnresolvedDependency<'src> { pub(crate) arguments: Vec>, pub(crate) recipe: Name<'src>, } impl Display for UnresolvedDependency<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { if self.arguments.is_empty() { write!(f, "{}", self.recipe) } else { write!(f, "({}", self.recipe)?; for argument in &self.arguments { write!(f, " {argument}")?; } write!(f, ")") } } } just-1.40.0/src/unresolved_recipe.rs000064400000000000000000000032701046102023000155470ustar 00000000000000use super::*; pub(crate) type UnresolvedRecipe<'src> = Recipe<'src, UnresolvedDependency<'src>>; impl<'src> UnresolvedRecipe<'src> { pub(crate) fn resolve( self, resolved: Vec>>, ) -> CompileResult<'src, Recipe<'src>> { assert_eq!( self.dependencies.len(), resolved.len(), "UnresolvedRecipe::resolve: dependency count not equal to resolved count: {} != {}", self.dependencies.len(), resolved.len() ); for (unresolved, resolved) in self.dependencies.iter().zip(&resolved) { assert_eq!(unresolved.recipe.lexeme(), resolved.name.lexeme()); if !resolved .argument_range() .contains(&unresolved.arguments.len()) { return Err( unresolved .recipe .error(CompileErrorKind::DependencyArgumentCountMismatch { dependency: unresolved.recipe.lexeme(), found: unresolved.arguments.len(), min: resolved.min_arguments(), max: resolved.max_arguments(), }), ); } } let dependencies = self .dependencies .into_iter() .zip(resolved) .map(|(unresolved, resolved)| Dependency { recipe: resolved, arguments: unresolved.arguments, }) .collect(); Ok(Recipe { attributes: self.attributes, body: self.body, dependencies, doc: self.doc, file_depth: self.file_depth, import_offsets: self.import_offsets, name: self.name, namepath: self.namepath, parameters: self.parameters, priors: self.priors, private: self.private, quiet: self.quiet, shebang: self.shebang, }) } } just-1.40.0/src/unstable_feature.rs000064400000000000000000000015361046102023000153650ustar 00000000000000use super::*; #[derive(Copy, Clone, Debug, PartialEq, Ord, Eq, PartialOrd)] pub(crate) enum UnstableFeature { FormatSubcommand, LogicalOperators, ScriptAttribute, ScriptInterpreterSetting, WhichFunction, } impl Display for UnstableFeature { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::FormatSubcommand => write!(f, "The `--fmt` command is currently unstable."), Self::LogicalOperators => write!( f, "The logical operators `&&` and `||` are currently unstable." ), Self::ScriptAttribute => write!(f, "The `[script]` attribute is currently unstable."), Self::ScriptInterpreterSetting => { write!(f, "The `script-interpreter` setting is currently unstable.") } Self::WhichFunction => write!(f, "The `which()` function is currently unstable."), } } } just-1.40.0/src/use_color.rs000064400000000000000000000001731046102023000140230ustar 00000000000000use super::*; #[derive(Copy, Clone, Debug, PartialEq, ValueEnum)] pub(crate) enum UseColor { Always, Auto, Never, } just-1.40.0/src/variables.rs000064400000000000000000000056401046102023000140050ustar 00000000000000use super::*; pub(crate) struct Variables<'expression, 'src> { stack: Vec<&'expression Expression<'src>>, } impl<'expression, 'src> Variables<'expression, 'src> { pub(crate) fn new(root: &'expression Expression<'src>) -> Self { Self { stack: vec![root] } } } impl<'src> Iterator for Variables<'_, 'src> { type Item = Token<'src>; fn next(&mut self) -> Option> { loop { match self.stack.pop()? { Expression::And { lhs, rhs } | Expression::Or { lhs, rhs } => { self.stack.push(lhs); self.stack.push(rhs); } Expression::Assert { condition: Condition { lhs, rhs, operator: _, }, error, } => { self.stack.push(error); self.stack.push(rhs); self.stack.push(lhs); } Expression::Backtick { .. } | Expression::StringLiteral { .. } => {} Expression::Call { thunk } => match thunk { Thunk::Nullary { .. } => {} Thunk::Unary { arg, .. } => self.stack.push(arg), Thunk::UnaryOpt { args: (a, opt_b), .. } => { self.stack.push(a); if let Some(b) = opt_b.as_ref() { self.stack.push(b); } } Thunk::UnaryPlus { args: (a, rest), .. } => { let first: &[&Expression] = &[a]; for arg in first.iter().copied().chain(rest).rev() { self.stack.push(arg); } } Thunk::Binary { args, .. } => { for arg in args.iter().rev() { self.stack.push(arg); } } Thunk::BinaryPlus { args: ([a, b], rest), .. } => { let first: &[&Expression] = &[a, b]; for arg in first.iter().copied().chain(rest).rev() { self.stack.push(arg); } } Thunk::Ternary { args, .. } => { for arg in args.iter().rev() { self.stack.push(arg); } } }, Expression::Concatenation { lhs, rhs } => { self.stack.push(rhs); self.stack.push(lhs); } Expression::Conditional { condition: Condition { lhs, rhs, operator: _, }, then, otherwise, } => { self.stack.push(otherwise); self.stack.push(then); self.stack.push(rhs); self.stack.push(lhs); } Expression::Group { contents } => { self.stack.push(contents); } Expression::Join { lhs, rhs } => { self.stack.push(rhs); if let Some(lhs) = lhs { self.stack.push(lhs); } } Expression::Variable { name, .. } => return Some(name.token), } } } } just-1.40.0/src/verbosity.rs000064400000000000000000000014741046102023000140640ustar 00000000000000#[allow(clippy::arbitrary_source_item_ordering)] #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] pub(crate) enum Verbosity { Quiet, Taciturn, Loquacious, Grandiloquent, } impl Verbosity { pub(crate) fn from_flag_occurrences(flag_occurrences: u8) -> Self { match flag_occurrences { 0 => Self::Taciturn, 1 => Self::Loquacious, _ => Self::Grandiloquent, } } pub(crate) fn quiet(self) -> bool { self == Self::Quiet } pub(crate) fn loud(self) -> bool { !self.quiet() } pub(crate) fn loquacious(self) -> bool { self >= Self::Loquacious } pub(crate) fn grandiloquent(self) -> bool { self >= Self::Grandiloquent } pub const fn default() -> Self { Self::Taciturn } } impl Default for Verbosity { fn default() -> Self { Self::default() } } just-1.40.0/src/warning.rs000064400000000000000000000015671046102023000135060ustar 00000000000000use super::*; #[derive(Clone, Debug, PartialEq)] pub(crate) enum Warning {} impl Warning { #[allow(clippy::unused_self)] fn context(&self) -> Option<&Token> { None } } impl ColorDisplay for Warning { fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result { let warning = color.warning(); let message = color.message(); write!(f, "{} {}", warning.paint("warning:"), message.prefix())?; write!(f, "{}", message.suffix())?; if let Some(token) = self.context() { writeln!(f)?; write!(f, "{}", token.color_display(color))?; } Ok(()) } } impl Serialize for Warning { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut map = serializer.serialize_map(None)?; map.serialize_entry("message", &self.color_display(Color::never()).to_string())?; map.end() } } just-1.40.0/src/which.rs000064400000000000000000000025061046102023000131350ustar 00000000000000use super::*; pub(crate) fn which(context: function::Context, name: &str) -> Result, String> { let name = Path::new(name); let candidates = match name.components().count() { 0 => return Err("empty command".into()), 1 => { // cmd is a regular command env::split_paths(&env::var_os("PATH").ok_or("`PATH` environment variable not set")?) .map(|path| path.join(name)) .collect() } _ => { // cmd contains a path separator, treat it as a path vec![name.into()] } }; for mut candidate in candidates { if candidate.is_relative() { // This candidate is a relative path, either because the user invoked `which("rel/path")`, // or because there was a relative path in `PATH`. Resolve it to an absolute path, // relative to the working directory of the just invocation. candidate = context .evaluator .context .working_directory() .join(candidate); } candidate = candidate.lexiclean(); if is_executable::is_executable(&candidate) { return candidate .to_str() .map(|candidate| Some(candidate.into())) .ok_or_else(|| { format!( "Executable path is not valid unicode: {}", candidate.display() ) }); } } Ok(None) } just-1.40.0/tests/alias.rs000064400000000000000000000017051046102023000134770ustar 00000000000000use super::*; #[test] fn alias_nested_module() { Test::new() .write("foo.just", "mod bar\nbaz: \n @echo FOO") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo alias b := foo::bar::baz baz: @echo 'HERE' ", ) .arg("b") .stdout("BAZ\n") .run(); } #[test] fn unknown_nested_alias() { Test::new() .write("foo.just", "baz: \n @echo FOO") .justfile( " mod foo alias b := foo::bar::baz ", ) .arg("b") .stderr( "\ error: Alias `b` has an unknown target `foo::bar::baz` ——▶ justfile:3:7 │ 3 │ alias b := foo::bar::baz │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn alias_in_submodule() { Test::new() .write( "foo.just", " alias b := bar bar: @echo BAR ", ) .justfile( " mod foo ", ) .arg("foo::b") .stdout("BAR\n") .run(); } just-1.40.0/tests/alias_style.rs000064400000000000000000000031221046102023000147120ustar 00000000000000use super::*; #[test] fn default() { Test::new() .justfile( " alias f := foo # comment foo: bar: ", ) .args(["--list"]) .stdout( " Available recipes: bar foo # comment [alias: f] ", ) .run(); } #[test] fn multiple() { Test::new() .justfile( " alias a := foo alias b := foo # comment foo: bar: ", ) .args(["--list"]) .stdout( " Available recipes: bar foo # comment [aliases: a, b] ", ) .run(); } #[test] fn right() { Test::new() .justfile( " alias f := foo # comment foo: bar: ", ) .args(["--alias-style=right", "--list"]) .stdout( " Available recipes: bar foo # comment [alias: f] ", ) .run(); } #[test] fn left() { Test::new() .justfile( " alias f := foo # comment foo: bar: ", ) .args(["--alias-style=left", "--list"]) .stdout( " Available recipes: bar foo # [alias: f] comment ", ) .run(); } #[test] fn separate() { Test::new() .justfile( " alias f := foo # comment foo: bar: ", ) .args(["--alias-style=separate", "--list"]) .stdout( " Available recipes: bar foo # comment f # alias for `foo` ", ) .run(); } just-1.40.0/tests/allow_duplicate_recipes.rs000064400000000000000000000010651046102023000172670ustar 00000000000000use super::*; #[test] fn allow_duplicate_recipes() { Test::new() .justfile( " b: echo foo b: echo bar set allow-duplicate-recipes ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn allow_duplicate_recipes_with_args() { Test::new() .justfile( " b a: echo foo b c d: echo bar {{c}} {{d}} set allow-duplicate-recipes ", ) .args(["b", "one", "two"]) .stdout("bar one two\n") .stderr("echo bar one two\n") .run(); } just-1.40.0/tests/allow_duplicate_variables.rs000064400000000000000000000004331046102023000176030ustar 00000000000000use super::*; #[test] fn allow_duplicate_variables() { Test::new() .justfile( " a := 'foo' a := 'bar' set allow-duplicate-variables b: echo {{a}} ", ) .arg("b") .stdout("bar\n") .stderr("echo bar\n") .run(); } just-1.40.0/tests/allow_missing.rs000064400000000000000000000021341046102023000152520ustar 00000000000000use super::*; #[test] fn allow_missing_recipes_in_run_invocation() { Test::new() .arg("foo") .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); Test::new().args(["--allow-missing", "foo"]).run(); } #[test] fn allow_missing_modules_in_run_invocation() { Test::new() .arg("foo::bar") .stderr("error: Justfile does not contain submodule `foo`\n") .status(EXIT_FAILURE) .run(); Test::new().args(["--allow-missing", "foo::bar"]).run(); } #[test] fn allow_missing_does_not_apply_to_compilation_errors() { Test::new() .justfile("bar: foo") .args(["--allow-missing", "foo"]) .stderr( " error: Recipe `bar` has unknown dependency `foo` ——▶ justfile:1:6 │ 1 │ bar: foo │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn allow_missing_does_not_apply_to_other_subcommands() { Test::new() .args(["--allow-missing", "--show", "foo"]) .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/assert_stdout.rs000064400000000000000000000002651046102023000153110ustar 00000000000000use super::*; pub(crate) fn assert_stdout(output: &std::process::Output, stdout: &str) { assert_success(output); assert_eq!(String::from_utf8_lossy(&output.stdout), stdout); } just-1.40.0/tests/assert_success.rs000064400000000000000000000004411046102023000154330ustar 00000000000000#[track_caller] pub(crate) fn assert_success(output: &std::process::Output) { if !output.status.success() { eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr)); eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout)); panic!("{}", output.status); } } just-1.40.0/tests/assertions.rs000064400000000000000000000006031046102023000145740ustar 00000000000000use super::*; #[test] fn assert_pass() { Test::new() .justfile( " foo: {{ assert('a' == 'a', 'error message') }} ", ) .run(); } #[test] fn assert_fail() { Test::new() .justfile( " foo: {{ assert('a' != 'a', 'error message') }} ", ) .stderr("error: Assert failed: error message\n") .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/assignment.rs000064400000000000000000000020761046102023000145600ustar 00000000000000use super::*; #[test] fn set_export_parse_error() { Test::new() .justfile( " set export := fals ", ) .stderr( " error: Expected keyword `true` or `false` but found identifier `fals` ——▶ justfile:1:15 │ 1 │ set export := fals │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn set_export_parse_error_eol() { Test::new() .justfile( " set export := ", ) .stderr( " error: Expected identifier, but found end of line ——▶ justfile:1:14 │ 1 │ set export := │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn invalid_attributes_are_an_error() { Test::new() .justfile( " [group: 'bar'] x := 'foo' ", ) .args(["--evaluate", "x"]) .stderr( " error: Assignment `x` has invalid attribute `group` ——▶ justfile:2:1 │ 2 │ x := 'foo' │ ^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/attributes.rs000064400000000000000000000076161046102023000146030ustar 00000000000000use super::*; #[test] fn all() { Test::new() .justfile( " [macos] [linux] [openbsd] [unix] [windows] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn duplicate_attributes_are_disallowed() { Test::new() .justfile( " [no-exit-message] [no-exit-message] foo: echo bar ", ) .stderr( " error: Recipe attribute `no-exit-message` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [no-exit-message] │ ^^^^^^^^^^^^^^^ ", ) .status(1) .run(); } #[test] fn multiple_attributes_one_line() { Test::new() .justfile( " [macos,windows,linux,openbsd] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn multiple_attributes_one_line_error_message() { Test::new() .justfile( " [macos,windows linux,openbsd] [no-exit-message] foo: exit 1 ", ) .stderr( " error: Expected ']', ':', ',', or '(', but found identifier ——▶ justfile:1:16 │ 1 │ [macos,windows linux,openbsd] │ ^^^^^ ", ) .status(1) .run(); } #[test] fn multiple_attributes_one_line_duplicate_check() { Test::new() .justfile( " [macos, windows, linux, openbsd] [linux] foo: exit 1 ", ) .stderr( " error: Recipe attribute `linux` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [linux] │ ^^^^^ ", ) .status(1) .run(); } #[test] fn unexpected_attribute_argument() { Test::new() .justfile( " [private('foo')] foo: exit 1 ", ) .stderr( " error: Attribute `private` got 1 argument but takes 0 arguments ——▶ justfile:1:2 │ 1 │ [private('foo')] │ ^^^^^^^ ", ) .status(1) .run(); } #[test] fn doc_attribute() { Test::new() .justfile( " # Non-document comment [doc('The real docstring')] foo: echo foo ", ) .args(["--list"]) .stdout( " Available recipes: foo # The real docstring ", ) .run(); } #[test] fn doc_attribute_suppress() { Test::new() .justfile( " # Non-document comment [doc] foo: echo foo ", ) .args(["--list"]) .stdout( " Available recipes: foo ", ) .run(); } #[test] fn doc_multiline() { Test::new() .justfile( " [doc('multiline comment')] foo: ", ) .args(["--list"]) .stdout( " Available recipes: # multiline # comment foo ", ) .run(); } #[test] fn extension() { Test::new() .justfile( " [extension: '.txt'] baz: #!/bin/sh echo $0 ", ) .stdout_regex(r"*baz\.txt\n") .run(); } #[test] fn extension_on_linewise_error() { Test::new() .justfile( " [extension: '.txt'] baz: ", ) .stderr( " error: Recipe `baz` has invalid attribute `extension` ——▶ justfile:2:1 │ 2 │ baz: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_non_repeatable_attributes_are_forbidden() { Test::new() .justfile( " [confirm: 'yes'] [confirm: 'no'] baz: ", ) .stderr( " error: Recipe attribute `confirm` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [confirm: 'no'] │ ^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/backticks.rs000064400000000000000000000004121046102023000143360ustar 00000000000000use super::*; #[test] fn trailing_newlines_are_stripped() { Test::new() .shell(false) .args(["--evaluate", "foos"]) .justfile( " set shell := ['python3', '-c'] foos := `print('foo' * 4)` ", ) .stdout("foofoofoofoo") .run(); } just-1.40.0/tests/byte_order_mark.rs000064400000000000000000000016651046102023000155630ustar 00000000000000use super::*; #[test] fn ignore_leading_byte_order_mark() { Test::new() .justfile( " \u{feff}foo: echo bar ", ) .stderr("echo bar\n") .stdout("bar\n") .run(); } #[test] fn non_leading_byte_order_mark_produces_error() { Test::new() .justfile( " foo: echo bar \u{feff} ", ) .stderr( " error: Expected \'@\', \'[\', comment, end of file, end of line, or identifier, but found byte order mark ——▶ justfile:3:1 │ 3 │ \u{feff} │ ^ ") .status(EXIT_FAILURE) .run(); } #[test] fn dont_mention_byte_order_mark_in_errors() { Test::new() .justfile("{") .stderr( " error: Expected '@', '[', comment, end of file, end of line, or identifier, but found '{' ——▶ justfile:1:1 │ 1 │ { │ ^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/changelog.rs000064400000000000000000000002361046102023000143330ustar 00000000000000use super::*; #[test] fn print_changelog() { Test::new() .args(["--changelog"]) .stdout(fs::read_to_string("CHANGELOG.md").unwrap()) .run(); } just-1.40.0/tests/choose.rs000064400000000000000000000103221046102023000136610ustar 00000000000000use super::*; #[test] fn env() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo bar\n") .stdout("bar\n") .run(); } #[test] fn chooser() { Test::new() .arg("--choose") .arg("--chooser") .arg("head -n1") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo bar\n") .stdout("bar\n") .run(); } #[test] fn override_variable() { Test::new() .arg("--choose") .arg("baz=B") .env("JUST_CHOOSER", "head -n1") .justfile( " baz := 'A' foo: echo foo bar: echo {{baz}} ", ) .stderr("echo B\n") .stdout("B\n") .run(); } #[test] fn skip_private_recipes() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo _bar: echo bar ", ) .stderr("echo foo\n") .stdout("foo\n") .run(); } #[test] fn recipes_in_submodules_can_be_chosen() { Test::new() .args(["--unstable", "--choose"]) .env("JUST_CHOOSER", "head -n10") .write("bar.just", "baz:\n echo BAZ") .justfile( " mod bar ", ) .stderr("echo BAZ\n") .stdout("BAZ\n") .run(); } #[test] fn skip_recipes_that_require_arguments() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo bar BAR: echo {{BAR}} ", ) .stderr("echo foo\n") .stdout("foo\n") .run(); } #[test] fn no_choosable_recipes() { Test::new() .arg("--choose") .justfile( " _foo: echo foo bar BAR: echo {{BAR}} ", ) .status(EXIT_FAILURE) .stderr("error: Justfile contains no choosable recipes.\n") .run(); } #[test] #[ignore] fn multiple_recipes() { Test::new() .arg("--choose") .arg("--chooser") .arg("echo foo bar") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo foo\necho bar\n") .stdout("foo\nbar\n") .run(); } #[test] fn invoke_error_function() { Test::new() .justfile( " foo: echo foo bar: echo bar ", ) .stderr_regex( r#"error: Chooser `/ -cu fzf --multi --preview 'just --unstable --color always --justfile ".*justfile" --show \{\}'` invocation failed: .*\n"#, ) .status(EXIT_FAILURE) .shell(false) .args(["--shell", "/", "--choose"]) .run(); } #[test] #[cfg(not(windows))] fn status_error() { let tmp = temptree! { justfile: "foo:\n echo foo\nbar:\n echo bar\n", "exit-2": "#!/usr/bin/env bash\nexit 2\n", }; let output = Command::new("chmod") .arg("+x") .arg(tmp.path().join("exit-2")) .output() .unwrap(); assert!(output.status.success()); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--choose") .arg("--chooser") .arg("exit-2") .env("PATH", path) .output() .unwrap(); assert!( Regex::new("^error: Chooser `exit-2` failed: exit (code|status): 2\n$") .unwrap() .is_match(str::from_utf8(&output.stderr).unwrap()) ); assert_eq!(output.status.code().unwrap(), 2); } #[test] fn default() { let tmp = temptree! { justfile: "foo:\n echo foo\n", }; let cat = which("cat").unwrap(); let fzf = tmp.path().join(format!("fzf{EXE_SUFFIX}")); #[cfg(unix)] std::os::unix::fs::symlink(cat, fzf).unwrap(); #[cfg(windows)] std::os::windows::fs::symlink_file(cat, fzf).unwrap(); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .arg("--choose") .arg("--chooser=fzf") .current_dir(tmp.path()) .env("PATH", path) .output() .unwrap(); assert_stdout(&output, "foo\n"); } just-1.40.0/tests/command.rs000064400000000000000000000062701046102023000140260ustar 00000000000000use super::*; #[test] fn long() { Test::new() .arg("--command") .arg("printf") .arg("foo") .justfile( " x: echo XYZ ", ) .stdout("foo") .run(); } #[test] fn short() { Test::new() .arg("-c") .arg("printf") .arg("foo") .justfile( " x: echo XYZ ", ) .stdout("foo") .run(); } #[test] fn command_color() { Test::new() .arg("--color") .arg("always") .arg("--command-color") .arg("cyan") .justfile( " x: echo XYZ ", ) .stdout("XYZ\n") .stderr("\u{1b}[1;36mecho XYZ\u{1b}[0m\n") .status(EXIT_SUCCESS) .run(); } #[test] fn no_binary() { Test::new() .arg("--command") .justfile( " x: echo XYZ ", ) .stderr( " error: a value is required for '--command ...' but none was supplied For more information, try '--help'. ", ) .status(2) .run(); } #[test] fn env_is_loaded() { Test::new() .justfile( " set dotenv-load x: echo XYZ ", ) .args(["--command", "sh", "-c", "printf $DOTENV_KEY"]) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value") .run(); } #[test] fn exports_are_available() { Test::new() .arg("--command") .arg("sh") .arg("-c") .arg("printf $FOO") .justfile( " export FOO := 'bar' x: echo XYZ ", ) .stdout("bar") .run(); } #[test] fn set_overrides_work() { Test::new() .arg("--set") .arg("FOO") .arg("baz") .arg("--command") .arg("sh") .arg("-c") .arg("printf $FOO") .justfile( " export FOO := 'bar' x: echo XYZ ", ) .stdout("baz") .run(); } #[test] fn run_in_shell() { Test::new() .arg("--shell-command") .arg("--command") .arg("bar baz") .justfile( " set shell := ['printf'] ", ) .stdout("bar baz") .shell(false) .run(); } #[test] fn exit_status() { Test::new() .arg("--command") .arg("false") .justfile( " x: echo XYZ ", ) .stderr_regex("error: Command `false` failed: exit (code|status): 1\n") .status(EXIT_FAILURE) .run(); } #[test] fn working_directory_is_correct() { let tmp = tempdir(); fs::write(tmp.path().join("justfile"), "").unwrap(); fs::write(tmp.path().join("bar"), "baz").unwrap(); fs::create_dir(tmp.path().join("foo")).unwrap(); let output = Command::new(executable_path("just")) .args(["--command", "cat", "bar"]) .current_dir(tmp.path().join("foo")) .output() .unwrap(); assert_eq!(str::from_utf8(&output.stderr).unwrap(), ""); assert!(output.status.success()); assert_eq!(str::from_utf8(&output.stdout).unwrap(), "baz"); } #[test] fn command_not_found() { let tmp = tempdir(); fs::write(tmp.path().join("justfile"), "").unwrap(); let output = Command::new(executable_path("just")) .args(["--command", "asdfasdfasdfasdfadfsadsfadsf", "bar"]) .output() .unwrap(); assert!(str::from_utf8(&output.stderr) .unwrap() .starts_with("error: Failed to invoke `asdfasdfasdfasdfadfsadsfadsf` `bar`:")); assert!(!output.status.success()); } just-1.40.0/tests/completions/just.bash000075500000000000000000000027461046102023000162310ustar 00000000000000#!/usr/bin/env bash # --- Shared functions --- reply_equals() { local reply=$(declare -p COMPREPLY) local expected=$1 if [ "$reply" = "$expected" ]; then echo "${FUNCNAME[1]}: ok" else exit_code=1 echo >&2 "${FUNCNAME[1]}: failed! Completion for \`${COMP_WORDS[*]}\` does not match." echo diff -U3 --label expected <(echo "$expected") --label actual <(echo "$reply") >&2 echo fi } # --- Initial Setup --- source "$1" cd tests/completions cargo build PATH="$(git rev-parse --show-toplevel)/target/debug:$PATH" exit_code=0 # --- Tests --- test_complete_all_recipes() { COMP_WORDS=(just) COMP_CWORD=1 _just just reply_equals 'declare -a COMPREPLY=([0]="deploy" [1]="install" [2]="publish" [3]="push" [4]="test")' } test_complete_all_recipes test_complete_recipes_starting_with_i() { COMP_WORDS=(just i) COMP_CWORD=1 _just just reply_equals 'declare -a COMPREPLY=([0]="install")' } test_complete_recipes_starting_with_i test_complete_recipes_starting_with_p() { COMP_WORDS=(just p) COMP_CWORD=1 _just just reply_equals 'declare -a COMPREPLY=([0]="publish" [1]="push")' } test_complete_recipes_starting_with_p test_complete_recipes_from_subdirs() { COMP_WORDS=(just subdir/) COMP_CWORD=1 _just just reply_equals 'declare -a COMPREPLY=([0]="subdir/special" [1]="subdir/surprise")' } test_complete_recipes_from_subdirs # --- Conclusion --- if [ $exit_code = 0 ]; then echo "All tests passed." else echo "Some test[s] failed." fi exit $exit_code just-1.40.0/tests/completions/justfile000075500000000000000000000000461046102023000161440ustar 00000000000000install: test: deploy: push: publish: just-1.40.0/tests/completions/subdir/justfile000075500000000000000000000000231046102023000174270ustar 00000000000000special: surprise: just-1.40.0/tests/completions.rs000064400000000000000000000016641046102023000147460ustar 00000000000000use super::*; #[test] #[cfg(target_os = "linux")] fn bash() { let output = Command::new(executable_path("just")) .args(["--completions", "bash"]) .output() .unwrap(); assert!(output.status.success()); let script = str::from_utf8(&output.stdout).unwrap(); let tempdir = tempdir(); let path = tempdir.path().join("just.bash"); fs::write(&path, script).unwrap(); let status = Command::new("./tests/completions/just.bash") .arg(path) .status() .unwrap(); assert!(status.success()); } #[test] fn replacements() { for shell in ["bash", "elvish", "fish", "nushell", "powershell", "zsh"] { let output = Command::new(executable_path("just")) .args(["--completions", shell]) .output() .unwrap(); assert!( output.status.success(), "shell completion generation for {shell} failed: {}\n{}", output.status, String::from_utf8_lossy(&output.stderr), ); } } just-1.40.0/tests/conditional.rs000064400000000000000000000105771046102023000147200ustar 00000000000000use super::*; #[test] fn then_branch_unevaluated() { Test::new() .justfile( " foo: echo {{ if 'a' == 'b' { `exit 1` } else { 'otherwise' } }} ", ) .stdout("otherwise\n") .stderr("echo otherwise\n") .run(); } #[test] fn otherwise_branch_unevaluated() { Test::new() .justfile( " foo: echo {{ if 'a' == 'a' { 'then' } else { `exit 1` } }} ", ) .stdout("then\n") .stderr("echo then\n") .run(); } #[test] fn otherwise_branch_unevaluated_inverted() { Test::new() .justfile( " foo: echo {{ if 'a' != 'b' { 'then' } else { `exit 1` } }} ", ) .stdout("then\n") .stderr("echo then\n") .run(); } #[test] fn then_branch_unevaluated_inverted() { Test::new() .justfile( " foo: echo {{ if 'a' != 'a' { `exit 1` } else { 'otherwise' } }} ", ) .stdout("otherwise\n") .stderr("echo otherwise\n") .run(); } #[test] fn complex_expressions() { Test::new() .justfile( " foo: echo {{ if 'a' + 'b' == `echo ab` { 'c' + 'd' } else { 'e' + 'f' } }} ", ) .stdout("cd\n") .stderr("echo cd\n") .run(); } #[test] fn undefined_lhs() { Test::new() .justfile( " a := if b == '' { '' } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:9 │ 1 │ a := if b == '' { '' } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_rhs() { Test::new() .justfile( " a := if '' == b { '' } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:15 │ 1 │ a := if '' == b { '' } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_then() { Test::new() .justfile( " a := if '' == '' { b } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:20 │ 1 │ a := if '' == '' { b } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_otherwise() { Test::new() .justfile( " a := if '' == '' { '' } else { b } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:32 │ 1 │ a := if '' == '' { '' } else { b } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unexpected_op() { Test::new() .justfile( " a := if '' a '' { '' } else { b } foo: echo {{ a }} ", ) .stderr( " error: Expected '&&', '!=', '!~', '||', '==', '=~', '+', or '/', but found identifier ——▶ justfile:1:12 │ 1 │ a := if '' a '' { '' } else { b } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dump() { Test::new() .arg("--dump") .justfile( " a := if '' == '' { '' } else { '' } foo: echo {{ a }} ", ) .stdout( " a := if '' == '' { '' } else { '' } foo: echo {{ a }} ", ) .run(); } #[test] fn if_else() { Test::new() .justfile( " x := if '0' == '1' { 'a' } else if '0' == '0' { 'b' } else { 'c' } foo: echo {{ x }} ", ) .stdout("b\n") .stderr("echo b\n") .run(); } #[test] fn missing_else() { Test::new() .justfile( " TEST := if path_exists('/bin/bash') == 'true' {'yes'} ", ) .stderr( " error: Expected keyword `else` but found `end of line` ——▶ justfile:1:54 │ 1 │ TEST := if path_exists('/bin/bash') == 'true' {'yes'} │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn incorrect_else_identifier() { Test::new() .justfile( " TEST := if path_exists('/bin/bash') == 'true' {'yes'} els {'no'} ", ) .stderr( " error: Expected keyword `else` but found identifier `els` ——▶ justfile:1:55 │ 1 │ TEST := if path_exists('/bin/bash') == 'true' {'yes'} els {'no'} │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/confirm.rs000064400000000000000000000061011046102023000140360ustar 00000000000000use super::*; #[test] fn confirm_recipe_arg() { Test::new() .arg("--yes") .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("echo confirmed\n") .stdout("confirmed\n") .run(); } #[test] fn recipe_with_confirm_recipe_dependency_arg() { Test::new() .arg("--yes") .justfile( " dep_confirmation: requires_confirmation echo confirmed2 [confirm] requires_confirmation: echo confirmed ", ) .stderr("echo confirmed\necho confirmed2\n") .stdout("confirmed\nconfirmed2\n") .run(); } #[test] fn confirm_recipe() { Test::new() .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? echo confirmed\n") .stdout("confirmed\n") .stdin("y") .run(); } #[test] fn recipe_with_confirm_recipe_dependency() { Test::new() .justfile( " dep_confirmation: requires_confirmation echo confirmed2 [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? echo confirmed\necho confirmed2\n") .stdout("confirmed\nconfirmed2\n") .stdin("y") .run(); } #[test] fn do_not_confirm_recipe() { Test::new() .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? error: Recipe `requires_confirmation` was not confirmed\n") .status(1) .run(); } #[test] fn do_not_confirm_recipe_with_confirm_recipe_dependency() { Test::new() .justfile( " dep_confirmation: requires_confirmation echo mistake [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? error: Recipe `requires_confirmation` was not confirmed\n") .status(1) .run(); } #[test] fn confirm_recipe_with_prompt() { Test::new() .justfile( " [confirm(\"This is dangerous - are you sure you want to run it?\")] requires_confirmation: echo confirmed ", ) .stderr("This is dangerous - are you sure you want to run it? echo confirmed\n") .stdout("confirmed\n") .stdin("y") .run(); } #[test] fn confirm_recipe_with_prompt_too_many_args() { Test::new() .justfile( r#" [confirm("PROMPT","EXTRA")] requires_confirmation: echo confirmed "#, ) .stderr( r#" error: Attribute `confirm` got 2 arguments but takes at most 1 argument ——▶ justfile:1:2 │ 1 │ [confirm("PROMPT","EXTRA")] │ ^^^^^^^ "#, ) .status(1) .run(); } #[test] fn confirm_attribute_is_formatted_correctly() { Test::new() .justfile( " [confirm('prompt')] foo: ", ) .arg("--dump") .stdout("[confirm('prompt')]\nfoo:\n") .run(); } just-1.40.0/tests/constants.rs000064400000000000000000000016751046102023000144300ustar 00000000000000use super::*; #[test] fn constants_are_defined() { assert_eval_eq("HEX", "0123456789abcdef"); } #[test] fn constants_are_defined_in_recipe_bodies() { Test::new() .justfile( " @foo: echo {{HEX}} ", ) .stdout("0123456789abcdef\n") .run(); } #[test] fn constants_are_defined_in_recipe_parameters() { Test::new() .justfile( " @foo hex=HEX: echo {{hex}} ", ) .stdout("0123456789abcdef\n") .run(); } #[test] fn constants_can_be_redefined() { Test::new() .justfile( " HEX := 'foo' ", ) .args(["--evaluate", "HEX"]) .stdout("foo") .run(); } #[test] fn constants_are_not_exported() { Test::new() .justfile( r#" set export foo: @'{{just_executable()}}' --request '{"environment-variable": "HEXUPPER"}' "#, ) .response(Response::EnvironmentVariable(None)) .run(); } just-1.40.0/tests/datetime.rs000064400000000000000000000006571046102023000142070ustar 00000000000000use super::*; #[test] fn datetime() { Test::new() .justfile( " x := datetime('%Y-%m-%d %z') ", ) .args(["--eval", "x"]) .stdout_regex(r"\d\d\d\d-\d\d-\d\d [+-]\d\d\d\d") .run(); } #[test] fn datetime_utc() { Test::new() .justfile( " x := datetime_utc('%Y-%m-%d %Z') ", ) .args(["--eval", "x"]) .stdout_regex(r"\d\d\d\d-\d\d-\d\d UTC") .run(); } just-1.40.0/tests/delimiters.rs000064400000000000000000000034121046102023000145440ustar 00000000000000use super::*; #[test] fn mismatched_delimiter() { Test::new() .justfile("(]") .stderr( " error: Mismatched closing delimiter `]`. (Did you mean to close the `(` on line 1?) ——▶ justfile:1:2 │ 1 │ (] │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unexpected_delimiter() { Test::new() .justfile("]") .stderr( " error: Unexpected closing delimiter `]` ——▶ justfile:1:1 │ 1 │ ] │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn paren_continuation() { Test::new() .justfile( " x := ( 'a' + 'b' ) foo: echo {{x}} ", ) .stdout("ab\n") .stderr("echo ab\n") .run(); } #[test] fn brace_continuation() { Test::new() .justfile( " x := if '' == '' { 'a' } else { 'b' } foo: echo {{x}} ", ) .stdout("a\n") .stderr("echo a\n") .run(); } #[test] fn bracket_continuation() { Test::new() .justfile( " set shell := [ 'sh', '-cu', ] foo: echo foo ", ) .stdout("foo\n") .stderr("echo foo\n") .run(); } #[test] fn dependency_continuation() { Test::new() .justfile( " foo: ( bar 'bar' ) echo foo bar x: echo {{x}} ", ) .stdout("bar\nfoo\n") .stderr("echo bar\necho foo\n") .run(); } #[test] fn no_interpolation_continuation() { Test::new() .justfile( " foo: echo {{ ( 'a' + 'b')}} ", ) .stderr( " error: Unterminated interpolation ——▶ justfile:2:8 │ 2 │ echo {{ ( │ ^^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/directories.rs000064400000000000000000000036511046102023000147240ustar 00000000000000use super::*; #[test] fn cache_directory() { Test::new() .justfile("x := cache_directory()") .args(["--evaluate", "x"]) .stdout(dirs::cache_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn config_directory() { Test::new() .justfile("x := config_directory()") .args(["--evaluate", "x"]) .stdout(dirs::config_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn config_local_directory() { Test::new() .justfile("x := config_local_directory()") .args(["--evaluate", "x"]) .stdout( dirs::config_local_dir() .unwrap_or_default() .to_string_lossy(), ) .run(); } #[test] fn data_directory() { Test::new() .justfile("x := data_directory()") .args(["--evaluate", "x"]) .stdout(dirs::data_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn data_local_directory() { Test::new() .justfile("x := data_local_directory()") .args(["--evaluate", "x"]) .stdout(dirs::data_local_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn executable_directory() { if let Some(executable_dir) = dirs::executable_dir() { Test::new() .justfile("x := executable_directory()") .args(["--evaluate", "x"]) .stdout(executable_dir.to_string_lossy()) .run(); } else { Test::new() .justfile("x := executable_directory()") .args(["--evaluate", "x"]) .stderr( " error: Call to function `executable_directory` failed: executable directory not found ——▶ justfile:1:6 │ 1 │ x := executable_directory() │ ^^^^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } } #[test] fn home_directory() { Test::new() .justfile("x := home_directory()") .args(["--evaluate", "x"]) .stdout(dirs::home_dir().unwrap_or_default().to_string_lossy()) .run(); } just-1.40.0/tests/dotenv.rs000064400000000000000000000164671046102023000137200ustar 00000000000000use super::*; #[test] fn dotenv() { Test::new() .write(".env", "KEY=ROOT") .write("sub/.env", "KEY=SUB") .write("sub/justfile", "default:\n\techo KEY=${KEY:-unset}") .args(["sub/default"]) .stdout("KEY=unset\n") .stderr("echo KEY=${KEY:-unset}\n") .run(); } #[test] fn set_false() { Test::new() .justfile( r#" set dotenv-load := false @foo: if [ -n "${DOTENV_KEY+1}" ]; then echo defined; else echo undefined; fi "#, ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("undefined\n") .run(); } #[test] fn set_implicit() { Test::new() .justfile( " set dotenv-load foo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\n") .stderr("echo $DOTENV_KEY\n") .run(); } #[test] fn set_true() { Test::new() .justfile( " set dotenv-load := true foo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\n") .stderr("echo $DOTENV_KEY\n") .run(); } #[test] fn no_warning() { Test::new() .justfile( " foo: echo ${DOTENV_KEY:-unset} ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("unset\n") .stderr("echo ${DOTENV_KEY:-unset}\n") .run(); } #[test] fn dotenv_required() { Test::new() .justfile( " set dotenv-required foo: ", ) .stderr("error: Dotenv file not found\n") .status(1) .run(); } #[test] fn path_resolves() { Test::new() .justfile( " foo: @echo $JUST_TEST_VARIABLE ", ) .tree(tree! { subdir: { ".env": "JUST_TEST_VARIABLE=bar" } }) .args(["--dotenv-path", "subdir/.env"]) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn filename_resolves() { Test::new() .justfile( " foo: @echo $JUST_TEST_VARIABLE ", ) .tree(tree! { ".env.special": "JUST_TEST_VARIABLE=bar" }) .args(["--dotenv-filename", ".env.special"]) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn filename_flag_overwrites_no_load() { Test::new() .justfile( " set dotenv-load := false foo: @echo $JUST_TEST_VARIABLE ", ) .tree(tree! { ".env.special": "JUST_TEST_VARIABLE=bar" }) .args(["--dotenv-filename", ".env.special"]) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn path_flag_overwrites_no_load() { Test::new() .justfile( " set dotenv-load := false foo: @echo $JUST_TEST_VARIABLE ", ) .tree(tree! { subdir: { ".env": "JUST_TEST_VARIABLE=bar" } }) .args(["--dotenv-path", "subdir/.env"]) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn can_set_dotenv_filename_from_justfile() { Test::new() .justfile( r#" set dotenv-filename := ".env.special" foo: @echo $JUST_TEST_VARIABLE "#, ) .tree(tree! { ".env.special": "JUST_TEST_VARIABLE=bar" }) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn can_set_dotenv_path_from_justfile() { Test::new() .justfile( r#" set dotenv-path := "subdir/.env" foo: @echo $JUST_TEST_VARIABLE "#, ) .tree(tree! { subdir: { ".env": "JUST_TEST_VARIABLE=bar" } }) .stdout("bar\n") .status(EXIT_SUCCESS) .run(); } #[test] fn program_argument_has_priority_for_dotenv_filename() { Test::new() .justfile( r#" set dotenv-filename := ".env.special" foo: @echo $JUST_TEST_VARIABLE "#, ) .tree(tree! { ".env.special": "JUST_TEST_VARIABLE=bar", ".env.superspecial": "JUST_TEST_VARIABLE=baz" }) .args(["--dotenv-filename", ".env.superspecial"]) .stdout("baz\n") .status(EXIT_SUCCESS) .run(); } #[test] fn program_argument_has_priority_for_dotenv_path() { Test::new() .justfile( " set dotenv-path := 'subdir/.env' foo: @echo $JUST_TEST_VARIABLE ", ) .tree(tree! { subdir: { ".env": "JUST_TEST_VARIABLE=bar", ".env.special": "JUST_TEST_VARIABLE=baz" } }) .args(["--dotenv-path", "subdir/.env.special"]) .stdout("baz\n") .status(EXIT_SUCCESS) .run(); } #[test] fn dotenv_path_is_relative_to_working_directory() { Test::new() .justfile( " set dotenv-path := '.env' foo: @echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .tree(tree! { subdir: { } }) .current_dir("subdir") .stdout("dotenv-value\n") .run(); } #[test] fn dotenv_variable_in_recipe() { Test::new() .justfile( " set dotenv-load echo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\n") .stderr("echo $DOTENV_KEY\n") .run(); } #[test] fn dotenv_variable_in_backtick() { Test::new() .justfile( " set dotenv-load X:=`echo $DOTENV_KEY` echo: echo {{X}} ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\n") .stderr("echo dotenv-value\n") .run(); } #[test] fn dotenv_variable_in_function_in_recipe() { Test::new() .justfile( " set dotenv-load echo: echo {{env_var_or_default('DOTENV_KEY', 'foo')}} echo {{env_var('DOTENV_KEY')}} ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\ndotenv-value\n") .stderr("echo dotenv-value\necho dotenv-value\n") .run(); } #[test] fn dotenv_variable_in_function_in_backtick() { Test::new() .justfile( " set dotenv-load X:=env_var_or_default('DOTENV_KEY', 'foo') Y:=env_var('DOTENV_KEY') echo: echo {{X}} echo {{Y}} ", ) .write(".env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\ndotenv-value\n") .stderr("echo dotenv-value\necho dotenv-value\n") .run(); } #[test] fn no_dotenv() { Test::new() .justfile( " X:=env_var_or_default('DOTENV_KEY', 'DEFAULT') echo: echo {{X}} ", ) .write(".env", "DOTENV_KEY=dotenv-value") .arg("--no-dotenv") .stdout("DEFAULT\n") .stderr("echo DEFAULT\n") .run(); } #[test] fn dotenv_env_var_override() { Test::new() .justfile( " echo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .env("DOTENV_KEY", "not-the-dotenv-value") .stdout("not-the-dotenv-value\n") .stderr("echo $DOTENV_KEY\n") .run(); } #[test] fn dotenv_path_usable_from_subdir() { Test::new() .justfile( " set dotenv-path := '.custom-env' @echo: echo $DOTENV_KEY ", ) .create_dir("sub") .current_dir("sub") .write(".custom-env", "DOTENV_KEY=dotenv-value") .stdout("dotenv-value\n") .run(); } #[test] fn dotenv_path_does_not_override_dotenv_file() { Test::new() .write(".env", "KEY=ROOT") .write( "sub/justfile", "set dotenv-path := '.'\n@foo:\n echo ${KEY}", ) .current_dir("sub") .stdout("ROOT\n") .run(); } just-1.40.0/tests/edit.rs000064400000000000000000000076761046102023000133500ustar 00000000000000use super::*; const JUSTFILE: &str = "Yooooooo, hopefully this never becomes valid syntax."; /// Test that --edit doesn't require a valid justfile #[test] fn invalid_justfile() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); assert!(!output.status.success()); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "cat") .output() .unwrap(); assert_stdout(&output, JUSTFILE); } #[test] fn invoke_error() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); assert!(!output.status.success()); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "/") .output() .unwrap(); assert_eq!( String::from_utf8_lossy(&output.stderr), if cfg!(windows) { "error: Editor `/` invocation failed: program path has no file name\n" } else { "error: Editor `/` invocation failed: Permission denied (os error 13)\n" } ); } #[test] #[cfg(not(windows))] fn status_error() { let tmp = temptree! { justfile: JUSTFILE, "exit-2": "#!/usr/bin/env bash\nexit 2\n", }; let output = Command::new("chmod") .arg("+x") .arg(tmp.path().join("exit-2")) .output() .unwrap(); assert!(output.status.success()); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("PATH", path) .env("VISUAL", "exit-2") .output() .unwrap(); assert!( Regex::new("^error: Editor `exit-2` failed: exit (code|status): 2\n$") .unwrap() .is_match(str::from_utf8(&output.stderr).unwrap()) ); assert_eq!(output.status.code().unwrap(), 2); } /// Test that editor is $VISUAL, $EDITOR, or "vim" in that order #[test] fn editor_precedence() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "cat") .env("EDITOR", "this-command-doesnt-exist") .output() .unwrap(); assert_stdout(&output, JUSTFILE); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env_remove("VISUAL") .env("EDITOR", "cat") .output() .unwrap(); assert_stdout(&output, JUSTFILE); let cat = which("cat").unwrap(); let vim = tmp.path().join(format!("vim{EXE_SUFFIX}")); #[cfg(unix)] std::os::unix::fs::symlink(cat, vim).unwrap(); #[cfg(windows)] std::os::windows::fs::symlink_file(cat, vim).unwrap(); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("PATH", path) .env_remove("VISUAL") .env_remove("EDITOR") .output() .unwrap(); assert_stdout(&output, JUSTFILE); } /// Test that editor working directory is the same as edited justfile #[cfg(unix)] #[test] fn editor_working_directory() { let tmp = temptree! { justfile: JUSTFILE, child: {}, editor: "#!/usr/bin/env sh\ncat $1\npwd", }; let editor = tmp.path().join("editor"); let permissions = std::os::unix::fs::PermissionsExt::from_mode(0o700); fs::set_permissions(&editor, permissions).unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("child")) .arg("--edit") .env("VISUAL", &editor) .output() .unwrap(); let want = format!( "{JUSTFILE}{}\n", tmp.path().canonicalize().unwrap().display() ); assert_stdout(&output, &want); } just-1.40.0/tests/equals.rs000064400000000000000000000006001046102023000136710ustar 00000000000000use super::*; #[test] fn export_recipe() { Test::new() .justfile( " export foo='bar': echo {{foo}} ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn alias_recipe() { Test::new() .justfile( " alias foo='bar': echo {{foo}} ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } just-1.40.0/tests/error_messages.rs000064400000000000000000000052061046102023000154260ustar 00000000000000use super::*; #[test] fn invalid_alias_attribute() { Test::new() .justfile("[private]\n[linux]\nalias t := test\n\ntest:\n") .stderr( " error: Alias `t` has invalid attribute `linux` ——▶ justfile:3:7 │ 3 │ alias t := test │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn expected_keyword() { Test::new() .justfile("foo := if '' == '' { '' } arlo { '' }") .stderr( " error: Expected keyword `else` but found identifier `arlo` ——▶ justfile:1:27 │ 1 │ foo := if '' == '' { '' } arlo { '' } │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unexpected_character() { Test::new() .justfile("&~") .stderr( " error: Expected character `&` ——▶ justfile:1:2 │ 1 │ &~ │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn argument_count_mismatch() { Test::new() .justfile("foo a b:") .args(["foo"]) .stderr( " error: Recipe `foo` got 0 arguments but takes 2 usage: just foo a b ", ) .status(EXIT_FAILURE) .run(); } #[test] fn file_path_is_indented_if_justfile_is_long() { Test::new() .justfile("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfoo") .status(EXIT_FAILURE) .stderr( " error: Expected '*', ':', '$', identifier, or '+', but found end of file ——▶ justfile:20:4 │ 20 │ foo │ ^ ", ) .run(); } #[test] fn file_paths_are_relative() { Test::new() .justfile("import 'foo/bar.just'") .write("foo/bar.just", "baz") .status(EXIT_FAILURE) .stderr(format!( " error: Expected '*', ':', '$', identifier, or '+', but found end of file ——▶ foo{MAIN_SEPARATOR}bar.just:1:4 │ 1 │ baz │ ^ ", )) .run(); } #[test] #[cfg(not(windows))] fn file_paths_not_in_subdir_are_absolute() { Test::new() .write("foo/justfile", "import '../bar.just'") .write("bar.just", "baz") .no_justfile() .args(["--justfile", "foo/justfile"]) .status(EXIT_FAILURE) .stderr_regex( r"error: Expected '\*', ':', '\$', identifier, or '\+', but found end of file ——▶ /.*/bar.just:1:4 │ 1 │ baz │ \^ ", ) .run(); } #[test] fn redefinition_errors_properly_swap_types() { Test::new() .write("foo.just", "foo:") .justfile("foo:\n echo foo\n\nmod foo 'foo.just'") .status(EXIT_FAILURE) .stderr( " error: Recipe `foo` defined on line 1 is redefined as a module on line 4 ——▶ justfile:4:5 │ 4 │ mod foo 'foo.just' │ ^^^ ", ) .run(); } just-1.40.0/tests/evaluate.rs000064400000000000000000000037571046102023000142250ustar 00000000000000use super::*; #[test] fn evaluate() { Test::new() .arg("--evaluate") .justfile( r#" foo := "a\t" hello := "c" bar := "b\t" ab := foo + bar + hello wut: touch /this/is/not/a/file "#, ) .stdout( r#"ab := "a b c" bar := "b " foo := "a " hello := "c" "#, ) .run(); } #[test] fn evaluate_empty() { Test::new() .arg("--evaluate") .justfile( " a := 'foo' ", ) .stdout( r#" a := "foo" "#, ) .run(); } #[test] fn evaluate_multiple() { Test::new() .arg("--evaluate") .arg("a") .arg("c") .justfile( " a := 'x' b := 'y' c := 'z' ", ) .stderr("error: `--evaluate` used with unexpected argument: `c`\n") .status(EXIT_FAILURE) .run(); } #[test] fn evaluate_single_free() { Test::new() .arg("--evaluate") .arg("b") .justfile( " a := 'x' b := 'y' c := 'z' ", ) .stdout("y") .run(); } #[test] fn evaluate_no_suggestion() { Test::new() .arg("--evaluate") .arg("aby") .justfile( " abc := 'x' ", ) .status(EXIT_FAILURE) .stderr( " error: Justfile does not contain variable `aby`. Did you mean `abc`? ", ) .run(); } #[test] fn evaluate_suggestion() { Test::new() .arg("--evaluate") .arg("goodbye") .justfile( " hello := 'x' ", ) .status(EXIT_FAILURE) .stderr( " error: Justfile does not contain variable `goodbye`. ", ) .run(); } #[test] fn evaluate_private() { Test::new() .arg("--evaluate") .justfile( " [private] foo := 'one' bar := 'two' _baz := 'three' ", ) .stdout("bar := \"two\"\n") .status(EXIT_SUCCESS) .run(); } #[test] fn evaluate_single_private() { Test::new() .arg("--evaluate") .arg("foo") .justfile( " [private] foo := 'one' bar := 'two' _baz := 'three' ", ) .stdout("one") .status(EXIT_SUCCESS) .run(); } just-1.40.0/tests/examples.rs000064400000000000000000000006101046102023000142160ustar 00000000000000use super::*; #[test] fn examples() { for result in fs::read_dir("examples").unwrap() { let entry = result.unwrap(); let path = entry.path(); println!("Parsing `{}`…", path.display()); let output = Command::new(executable_path("just")) .arg("--justfile") .arg(&path) .arg("--dump") .output() .unwrap(); assert_success(&output); } } just-1.40.0/tests/explain.rs000064400000000000000000000005521046102023000140450ustar 00000000000000use super::*; #[test] fn explain_recipe() { Test::new() .justfile( " # List some fruits fruits: echo 'apple peach dragonfruit' ", ) .args(["--explain", "fruits"]) .stdout("apple peach dragonfruit\n") .stderr( " #### List some fruits echo 'apple peach dragonfruit' ", ) .run(); } just-1.40.0/tests/export.rs000064400000000000000000000073001046102023000137240ustar 00000000000000use super::*; #[test] fn success() { Test::new() .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + BAR + baz wut: echo $FOO $BAR $ABC "#, ) .stdout("a b abc\n") .stderr("echo $FOO $BAR $ABC\n") .run(); } #[test] fn parameter() { Test::new() .justfile( r#" wut $FOO='a' BAR='b': echo $FOO echo {{BAR}} if [ -n "${BAR+1}" ]; then echo defined; else echo undefined; fi "#, ) .stdout("a\nb\nundefined\n") .stderr( "echo $FOO\necho b\nif [ -n \"${BAR+1}\" ]; then echo defined; else echo undefined; fi\n", ) .run(); } #[test] fn parameter_not_visible_to_backtick() { Test::new() .arg("wut") .arg("bar") .justfile( r#" wut $FOO BAR=`if [ -n "${FOO+1}" ]; then echo defined; else echo undefined; fi`: echo $FOO echo {{BAR}} "#, ) .stdout("bar\nundefined\n") .stderr("echo $FOO\necho undefined\n") .run(); } #[test] fn override_variable() { Test::new() .arg("--set") .arg("BAR") .arg("bye") .arg("FOO=hello") .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + "-" + BAR + "-" + baz wut: echo $FOO $BAR $ABC "#, ) .stdout("hello bye hello-bye-c\n") .stderr("echo $FOO $BAR $ABC\n") .run(); } #[test] fn shebang() { Test::new() .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + BAR + baz wut: #!/bin/sh echo $FOO $BAR $ABC "#, ) .stdout("a b abc\n") .run(); } #[test] fn recipe_backtick() { Test::new() .justfile( r#" export EXPORTED_VARIABLE := "A-IS-A" recipe: echo {{`echo recipe $EXPORTED_VARIABLE`}} "#, ) .stdout("recipe A-IS-A\n") .stderr("echo recipe A-IS-A\n") .run(); } #[test] fn setting_implicit() { Test::new() .arg("foo") .arg("goodbye") .justfile( " set export A := 'hello' foo B C=`echo $A`: echo $A echo $B echo $C ", ) .stdout("hello\ngoodbye\nhello\n") .stderr("echo $A\necho $B\necho $C\n") .run(); } #[test] fn setting_true() { Test::new() .justfile( " set export := true A := 'hello' foo B C=`echo $A`: echo $A echo $B echo $C ", ) .arg("foo") .arg("goodbye") .stdout("hello\ngoodbye\nhello\n") .stderr("echo $A\necho $B\necho $C\n") .run(); } #[test] fn setting_false() { Test::new() .justfile( r#" set export := false A := 'hello' foo: if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi "#, ) .stdout("undefined\n") .stderr("if [ -n \"${A+1}\" ]; then echo defined; else echo undefined; fi\n") .run(); } #[test] fn setting_shebang() { Test::new() .arg("foo") .arg("goodbye") .justfile( " set export A := 'hello' foo B: #!/bin/sh echo $A echo $B ", ) .stdout("hello\ngoodbye\n") .run(); } #[test] fn setting_override_undefined() { Test::new() .arg("A=zzz") .arg("foo") .justfile( r#" set export A := 'hello' B := `if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi` foo C='goodbye' D=`if [ -n "${C+1}" ]; then echo defined; else echo undefined; fi`: echo $B echo $D "#, ) .stdout("undefined\nundefined\n") .stderr("echo $B\necho $D\n") .run(); } #[test] fn setting_variable_not_visible() { Test::new() .arg("A=zzz") .justfile( r#" export A := 'hello' export B := `if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi` foo: echo $B "#, ) .stdout("undefined\n") .stderr("echo $B\n") .run(); } just-1.40.0/tests/fallback.rs000064400000000000000000000133031046102023000141420ustar 00000000000000use super::*; #[test] fn fallback_from_subdir_bugfix() { Test::new() .write( "sub/justfile", unindent( " set fallback @default: echo foo ", ), ) .args(["sub/default"]) .stdout("foo\n") .run(); } #[test] fn fallback_from_subdir_message() { Test::new() .justfile("bar:\n echo bar") .write( "sub/justfile", unindent( " set fallback @foo: echo foo ", ), ) .args(["sub/bar"]) .stderr(path("echo bar\n")) .stdout("bar\n") .run(); } #[test] fn fallback_from_subdir_verbose_message() { Test::new() .justfile("bar:\n echo bar") .write( "sub/justfile", unindent( " set fallback @foo: echo foo ", ), ) .args(["--verbose", "sub/bar"]) .stderr(path( " Trying ../justfile ===> Running recipe `bar`... echo bar ", )) .stdout("bar\n") .run(); } #[test] fn runs_recipe_in_parent_if_not_found_in_current() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .stderr( " echo root ", ) .stdout("root\n") .run(); } #[test] fn setting_accepts_value() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .stderr( " echo root ", ) .stdout("root\n") .run(); } #[test] fn print_error_from_parent_if_recipe_not_found_in_current() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile("foo:\n echo {{bar}}") .args(["foo"]) .current_dir("bar") .stderr( " error: Variable `bar` not defined ——▶ justfile:2:9 │ 2 │ echo {{bar}} │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn requires_setting() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn works_with_provided_search_directory() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["./foo"]) .stdout("root\n") .stderr( " echo root ", ) .current_dir("bar") .run(); } #[test] fn doesnt_work_with_justfile() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["--justfile", "justfile", "foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn doesnt_work_with_justfile_and_working_directory() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["--justfile", "justfile", "--working-directory", ".", "foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn prints_correct_error_message_when_recipe_not_found() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true bar: echo subdir " } }) .justfile( " bar: echo root ", ) .args(["foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr( " error: Justfile does not contain recipe `foo` ", ) .run(); } #[test] fn multiple_levels_of_fallback_work() { Test::new() .tree(tree! { a: { b: { justfile: " set fallback := true foo: echo subdir " }, justfile: " set fallback := true bar: echo subdir " } }) .justfile( " baz: echo root ", ) .args(["baz"]) .current_dir("a/b") .stdout("root\n") .stderr( " echo root ", ) .run(); } #[test] fn stop_fallback_when_fallback_is_false() { Test::new() .tree(tree! { a: { b: { justfile: " set fallback := true foo: echo subdir " }, justfile: " bar: echo subdir " } }) .justfile( " baz: echo root ", ) .args(["baz"]) .current_dir("a/b") .stderr( " error: Justfile does not contain recipe `baz` Did you mean `bar`? ", ) .status(EXIT_FAILURE) .run(); } #[test] fn works_with_modules() { Test::new() .write("bar/justfile", "set fallback := true") .write("foo.just", "baz:\n @echo BAZ") .justfile("mod foo") .args(["foo::baz"]) .current_dir("bar") .stdout("BAZ\n") .run(); } just-1.40.0/tests/format.rs000064400000000000000000000471271046102023000137060ustar 00000000000000use super::*; #[test] fn unstable_not_passed() { Test::new() .arg("--fmt") .justfile("") .stderr_regex("error: The `--fmt` command is currently unstable..*") .status(EXIT_FAILURE) .run(); } #[test] fn check_without_fmt() { Test::new() .arg("--check") .justfile("") .stderr_regex( "error: the following required arguments were not provided: --fmt (.|\\n)+", ) .status(2) .run(); } #[test] fn check_ok() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .justfile( r#" # comment with spaces export x := `backtick with lines` recipe: deps echo "$x" deps: echo {{ x }} echo '$x' "#, ) .status(EXIT_SUCCESS) .run(); } #[test] fn check_found_diff() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .justfile("x:=``\n") .stdout( " -x:=`` +x := `` ", ) .stderr( " error: Formatted justfile differs from original. ", ) .status(EXIT_FAILURE) .run(); } #[test] fn check_found_diff_quiet() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .arg("--quiet") .justfile("x:=``\n") .status(EXIT_FAILURE) .run(); } #[test] fn check_diff_color() { Test::new() .justfile("x:=``\n") .arg("--unstable") .arg("--fmt") .arg("--check") .arg("--color") .arg("always") .stdout("\n \u{1b}[31m-x:=``\n \u{1b}[0m\u{1b}[32m+x := ``\n \u{1b}[0m") .stderr("\n \u{1b}[1;31merror\u{1b}[0m: \u{1b}[1mFormatted justfile differs from original.\u{1b}[0m\n ") .status(EXIT_FAILURE) .run(); } #[test] fn unstable_passed() { let tmp = tempdir(); let justfile = tmp.path().join("justfile"); fs::write(&justfile, "x := 'hello' ").unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--fmt") .arg("--unstable") .output() .unwrap(); if !output.status.success() { eprintln!("{}", String::from_utf8_lossy(&output.stderr)); eprintln!("{}", String::from_utf8_lossy(&output.stdout)); panic!("justfile failed with status: {}", output.status); } assert_eq!(fs::read_to_string(&justfile).unwrap(), "x := 'hello'\n"); } #[test] fn write_error() { // skip this test if running as root, since root can write files even if // permissions would otherwise forbid it #[cfg(not(windows))] if unsafe { libc::getuid() } == 0 { return; } let tempdir = temptree! { justfile: "x := 'hello' ", }; let test = Test::with_tempdir(tempdir) .no_justfile() .args(["--fmt", "--unstable"]) .status(EXIT_FAILURE) .stderr_regex(if cfg!(windows) { r"error: Failed to write justfile to `.*`: Access is denied. \(os error 5\)\n" } else { r"error: Failed to write justfile to `.*`: Permission denied \(os error 13\)\n" }); let justfile_path = test.justfile_path(); let output = Command::new("chmod") .arg("400") .arg(&justfile_path) .output() .unwrap(); assert!(output.status.success()); let _tempdir = test.run(); assert_eq!( fs::read_to_string(&justfile_path).unwrap(), "x := 'hello' " ); } #[test] fn alias_good() { Test::new() .arg("--dump") .justfile( " alias f := foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn alias_fix_indent() { Test::new() .arg("--dump") .justfile( " alias f:= foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn assignment_singlequote() { Test::new() .arg("--dump") .justfile( " foo := 'foo' ", ) .stdout( " foo := 'foo' ", ) .run(); } #[test] fn assignment_doublequote() { Test::new() .arg("--dump") .justfile( r#" foo := "foo" "#, ) .stdout( r#" foo := "foo" "#, ) .run(); } #[test] fn assignment_indented_singlequote() { Test::new() .arg("--dump") .justfile( " foo := ''' foo ''' ", ) .stdout( r" foo := ''' foo ''' ", ) .run(); } #[test] fn assignment_indented_doublequote() { Test::new() .arg("--dump") .justfile( r#" foo := """ foo """ "#, ) .stdout( r#" foo := """ foo """ "#, ) .run(); } #[test] fn assignment_backtick() { Test::new() .arg("--dump") .justfile( " foo := `foo` ", ) .stdout( " foo := `foo` ", ) .run(); } #[test] fn assignment_indented_backtick() { Test::new() .arg("--dump") .justfile( " foo := ``` foo ``` ", ) .stdout( " foo := ``` foo ``` ", ) .run(); } #[test] fn assignment_name() { Test::new() .arg("--dump") .justfile( " bar := 'bar' foo := bar ", ) .stdout( " bar := 'bar' foo := bar ", ) .run(); } #[test] fn assignment_parenthesized_expression() { Test::new() .arg("--dump") .justfile( " foo := ('foo') ", ) .stdout( " foo := ('foo') ", ) .run(); } #[test] fn assignment_export() { Test::new() .arg("--dump") .justfile( " export foo := 'foo' ", ) .stdout( " export foo := 'foo' ", ) .run(); } #[test] fn assignment_concat_values() { Test::new() .arg("--dump") .justfile( " foo := 'foo' + 'bar' ", ) .stdout( " foo := 'foo' + 'bar' ", ) .run(); } #[test] fn assignment_if_oneline() { Test::new() .arg("--dump") .justfile( " foo := if 'foo' == 'foo' { 'foo' } else { 'bar' } ", ) .stdout( " foo := if 'foo' == 'foo' { 'foo' } else { 'bar' } ", ) .run(); } #[test] fn assignment_if_multiline() { Test::new() .arg("--dump") .justfile( " foo := if 'foo' != 'foo' { 'foo' } else { 'bar' } ", ) .stdout( " foo := if 'foo' != 'foo' { 'foo' } else { 'bar' } ", ) .run(); } #[test] fn assignment_nullary_function() { Test::new() .arg("--dump") .justfile( " foo := arch() ", ) .stdout( " foo := arch() ", ) .run(); } #[test] fn assignment_unary_function() { Test::new() .arg("--dump") .justfile( " foo := env_var('foo') ", ) .stdout( " foo := env_var('foo') ", ) .run(); } #[test] fn assignment_binary_function() { Test::new() .arg("--dump") .justfile( " foo := env_var_or_default('foo', 'bar') ", ) .stdout( " foo := env_var_or_default('foo', 'bar') ", ) .run(); } #[test] fn assignment_path_functions() { Test::new() .arg("--dump") .justfile( " foo := without_extension('foo/bar.baz') foo2 := file_stem('foo/bar.baz') foo3 := parent_directory('foo/bar.baz') foo4 := file_name('foo/bar.baz') foo5 := extension('foo/bar.baz') ", ) .stdout( " foo := without_extension('foo/bar.baz') foo2 := file_stem('foo/bar.baz') foo3 := parent_directory('foo/bar.baz') foo4 := file_name('foo/bar.baz') foo5 := extension('foo/bar.baz') ", ) .run(); } #[test] fn recipe_ordinary() { Test::new() .justfile( " foo: echo bar ", ) .arg("--dump") .stdout( " foo: echo bar ", ) .run(); } #[test] fn recipe_with_docstring() { Test::new() .arg("--dump") .justfile( " # bar foo: echo bar ", ) .stdout( " # bar foo: echo bar ", ) .run(); } #[test] fn recipe_with_comments_in_body() { Test::new() .arg("--dump") .justfile( " foo: # bar echo bar ", ) .stdout( " foo: # bar echo bar ", ) .run(); } #[test] fn recipe_body_is_comment() { Test::new() .arg("--dump") .justfile( " foo: # bar ", ) .stdout( " foo: # bar ", ) .run(); } #[test] fn recipe_several_commands() { Test::new() .arg("--dump") .justfile( " foo: echo bar echo baz ", ) .stdout( " foo: echo bar echo baz ", ) .run(); } #[test] fn recipe_quiet() { Test::new() .arg("--dump") .justfile( " @foo: echo bar ", ) .stdout( " @foo: echo bar ", ) .run(); } #[test] fn recipe_quiet_command() { Test::new() .arg("--dump") .justfile( " foo: @echo bar ", ) .stdout( " foo: @echo bar ", ) .run(); } #[test] fn recipe_quiet_comment() { Test::new() .arg("--dump") .justfile( " foo: @# bar ", ) .stdout( " foo: @# bar ", ) .run(); } #[test] fn recipe_ignore_errors() { Test::new() .arg("--dump") .justfile( " foo: -echo foo ", ) .stdout( " foo: -echo foo ", ) .run(); } #[test] fn recipe_parameter() { Test::new() .arg("--dump") .justfile( " foo BAR: echo foo ", ) .stdout( " foo BAR: echo foo ", ) .run(); } #[test] fn recipe_parameter_default() { Test::new() .arg("--dump") .justfile( " foo BAR='bar': echo foo ", ) .stdout( " foo BAR='bar': echo foo ", ) .run(); } #[test] fn recipe_parameter_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR: echo foo ", ) .stdout( " foo $BAR: echo foo ", ) .run(); } #[test] fn recipe_parameter_default_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR='foo': echo foo ", ) .stdout( " foo $BAR='foo': echo foo ", ) .run(); } #[test] fn recipe_parameter_concat() { Test::new() .arg("--dump") .justfile( " foo BAR=('bar' + 'baz'): echo foo ", ) .stdout( " foo BAR=('bar' + 'baz'): echo foo ", ) .run(); } #[test] fn recipe_parameters() { Test::new() .arg("--dump") .justfile( " foo BAR BAZ: echo foo ", ) .stdout( " foo BAR BAZ: echo foo ", ) .run(); } #[test] fn recipe_parameters_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR $BAZ: echo foo ", ) .stdout( " foo $BAR $BAZ: echo foo ", ) .run(); } #[test] fn recipe_variadic_plus() { Test::new() .arg("--dump") .justfile( " foo +BAR: echo foo ", ) .stdout( " foo +BAR: echo foo ", ) .run(); } #[test] fn recipe_variadic_star() { Test::new() .arg("--dump") .justfile( " foo *BAR: echo foo ", ) .stdout( " foo *BAR: echo foo ", ) .run(); } #[test] fn recipe_positional_variadic() { Test::new() .arg("--dump") .justfile( " foo BAR *BAZ: echo foo ", ) .stdout( " foo BAR *BAZ: echo foo ", ) .run(); } #[test] fn recipe_variadic_default() { Test::new() .arg("--dump") .justfile( " foo +BAR='bar': echo foo ", ) .stdout( " foo +BAR='bar': echo foo ", ) .run(); } #[test] fn recipe_parameter_in_body() { Test::new() .arg("--dump") .justfile( " foo BAR: echo {{ BAR }} ", ) .stdout( " foo BAR: echo {{ BAR }} ", ) .run(); } #[test] fn recipe_parameter_conditional() { Test::new() .arg("--dump") .justfile( " foo BAR: echo {{ if 'foo' == 'foo' { 'foo' } else { 'bar' } }} ", ) .stdout( " foo BAR: echo {{ if 'foo' == 'foo' { 'foo' } else { 'bar' } }} ", ) .run(); } #[test] fn recipe_escaped_braces() { Test::new() .arg("--dump") .justfile( " foo BAR: echo '{{{{BAR}}}}' ", ) .stdout( " foo BAR: echo '{{{{BAR}}}}' ", ) .run(); } #[test] fn recipe_assignment_in_body() { Test::new() .arg("--dump") .justfile( " bar := 'bar' foo: echo $bar ", ) .stdout( " bar := 'bar' foo: echo $bar ", ) .run(); } #[test] fn recipe_dependency() { Test::new() .arg("--dump") .justfile( " bar: echo bar foo: bar echo foo ", ) .stdout( " bar: echo bar foo: bar echo foo ", ) .run(); } #[test] fn recipe_dependency_param() { Test::new() .arg("--dump") .justfile( " bar BAR: echo bar foo: (bar 'bar') echo foo ", ) .stdout( " bar BAR: echo bar foo: (bar 'bar') echo foo ", ) .run(); } #[test] fn recipe_dependency_params() { Test::new() .arg("--dump") .justfile( " bar BAR BAZ: echo bar foo: (bar 'bar' 'baz') echo foo ", ) .stdout( " bar BAR BAZ: echo bar foo: (bar 'bar' 'baz') echo foo ", ) .run(); } #[test] fn recipe_dependencies() { Test::new() .arg("--dump") .justfile( " bar: echo bar baz: echo baz foo: baz bar echo foo ", ) .stdout( " bar: echo bar baz: echo baz foo: baz bar echo foo ", ) .run(); } #[test] fn recipe_dependencies_params() { Test::new() .arg("--dump") .justfile( " bar BAR: echo bar baz BAZ: echo baz foo: (baz 'baz') (bar 'bar') echo foo ", ) .stdout( " bar BAR: echo bar baz BAZ: echo baz foo: (baz 'baz') (bar 'bar') echo foo ", ) .run(); } #[test] fn set_true_explicit() { Test::new() .arg("--dump") .justfile( " set export := true ", ) .stdout( " set export := true ", ) .run(); } #[test] fn set_true_implicit() { Test::new() .arg("--dump") .justfile( " set export ", ) .stdout( " set export := true ", ) .run(); } #[test] fn set_false() { Test::new() .arg("--dump") .justfile( " set export := false ", ) .stdout( " set export := false ", ) .run(); } #[test] fn set_shell() { Test::new() .arg("--dump") .justfile( r#" set shell := ['sh', "-c"] "#, ) .stdout( r#" set shell := ['sh', "-c"] "#, ) .run(); } #[test] fn comment() { Test::new() .arg("--dump") .justfile( " # foo ", ) .stdout( " # foo ", ) .run(); } #[test] fn comment_multiline() { Test::new() .arg("--dump") .justfile( " # foo # bar ", ) .stdout( " # foo # bar ", ) .run(); } #[test] fn comment_leading() { Test::new() .arg("--dump") .justfile( " # foo foo := 'bar' ", ) .stdout( " # foo foo := 'bar' ", ) .run(); } #[test] fn comment_trailing() { Test::new() .arg("--dump") .justfile( " foo := 'bar' # foo ", ) .stdout( " foo := 'bar' # foo ", ) .run(); } #[test] fn comment_before_recipe() { Test::new() .arg("--dump") .justfile( " # foo foo: echo foo ", ) .stdout( " # foo foo: echo foo ", ) .run(); } #[test] fn comment_before_docstring_recipe() { Test::new() .arg("--dump") .justfile( " # bar # foo foo: echo foo ", ) .stdout( " # bar # foo foo: echo foo ", ) .run(); } #[test] fn group_recipes() { Test::new() .arg("--dump") .justfile( " foo: echo foo bar: echo bar ", ) .stdout( " foo: echo foo bar: echo bar ", ) .run(); } #[test] fn group_aliases() { Test::new() .arg("--dump") .justfile( " alias f := foo alias b := bar foo: echo foo bar: echo bar ", ) .stdout( " alias f := foo alias b := bar foo: echo foo bar: echo bar ", ) .run(); } #[test] fn group_assignments() { Test::new() .arg("--dump") .justfile( " foo := 'foo' bar := 'bar' ", ) .stdout( " foo := 'foo' bar := 'bar' ", ) .run(); } #[test] fn group_sets() { Test::new() .arg("--dump") .justfile( " set export := true set positional-arguments := true ", ) .stdout( " set export := true set positional-arguments := true ", ) .run(); } #[test] fn group_comments() { Test::new() .arg("--dump") .justfile( " # foo # bar ", ) .stdout( " # foo # bar ", ) .run(); } #[test] fn separate_recipes_aliases() { Test::new() .arg("--dump") .justfile( " alias f := foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn no_trailing_newline() { Test::new() .arg("--dump") .justfile( " foo: echo foo", ) .stdout( " foo: echo foo ", ) .run(); } #[test] fn subsequent() { Test::new() .arg("--dump") .justfile( " bar: foo: && bar echo foo", ) .stdout( " bar: foo: && bar echo foo ", ) .run(); } #[test] fn exported_parameter() { Test::new() .justfile("foo +$f:") .args(["--dump"]) .stdout("foo +$f:\n") .run(); } #[test] fn multi_argument_attribute() { Test::new() .justfile( " set unstable [script('a', 'b', 'c')] foo: ", ) .arg("--dump") .stdout( " set unstable := true [script('a', 'b', 'c')] foo: ", ) .run(); } #[test] fn doc_attribute_suppresses_comment() { Test::new() .justfile( " set unstable # COMMENT [doc('ATTRIBUTE')] foo: ", ) .arg("--dump") .stdout( " set unstable := true [doc('ATTRIBUTE')] foo: ", ) .run(); } #[test] fn unchanged_justfiles_are_not_written_to_disk() { let tmp = tempdir(); let justfile = tmp.path().join("justfile"); fs::write(&justfile, "").unwrap(); let mut permissions = fs::metadata(&justfile).unwrap().permissions(); permissions.set_readonly(true); fs::set_permissions(&justfile, permissions).unwrap(); Test::with_tempdir(tmp) .no_justfile() .args(["--fmt", "--unstable"]) .run(); } #[test] fn if_else() { Test::new() .justfile( " x := if '' == '' { '' } else if '' == '' { '' } else { '' } ", ) .arg("--dump") .stdout( " x := if '' == '' { '' } else if '' == '' { '' } else { '' } ", ) .run(); } #[test] fn private_variable() { Test::new() .justfile( " [private] foo := 'bar' ", ) .arg("--dump") .stdout( " [private] foo := 'bar' ", ) .run(); } just-1.40.0/tests/functions.rs000064400000000000000000000715471046102023000144310ustar 00000000000000use super::*; #[test] fn test_os_arch_functions_in_interpolation() { Test::new() .justfile( r" foo: echo {{arch()}} {{os()}} {{os_family()}} {{num_cpus()}} ", ) .stdout( format!( "{} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .stderr( format!( "echo {} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .run(); } #[test] fn test_os_arch_functions_in_expression() { Test::new() .justfile( r" a := arch() o := os() f := os_family() n := num_cpus() foo: echo {{a}} {{o}} {{f}} {{n}} ", ) .stdout( format!( "{} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .stderr( format!( "echo {} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .run(); } #[cfg(not(windows))] #[test] fn env_var_functions() { Test::new() .justfile( r" p := env_var('USER') b := env_var_or_default('ZADDY', 'HTAP') x := env_var_or_default('XYZ', 'ABC') foo: /usr/bin/env echo '{{p}}' '{{b}}' '{{x}}' ", ) .stdout(format!("{} HTAP ABC\n", env::var("USER").unwrap()).as_str()) .stderr( format!( "/usr/bin/env echo '{}' 'HTAP' 'ABC'\n", env::var("USER").unwrap() ) .as_str(), ) .run(); } #[cfg(not(windows))] #[test] fn path_functions() { Test::new() .justfile( r" we := without_extension('/foo/bar/baz.hello') fs := file_stem('/foo/bar/baz.hello') fn := file_name('/foo/bar/baz.hello') dir := parent_directory('/foo/bar/baz.hello') ext := extension('/foo/bar/baz.hello') jn := join('a', 'b') foo: /usr/bin/env echo '{{we}}' '{{fs}}' '{{fn}}' '{{dir}}' '{{ext}}' '{{jn}}' ", ) .stdout("/foo/bar/baz baz baz.hello /foo/bar hello a/b\n") .stderr("/usr/bin/env echo '/foo/bar/baz' 'baz' 'baz.hello' '/foo/bar' 'hello' 'a/b'\n") .run(); } #[cfg(not(windows))] #[test] fn path_functions2() { Test::new() .justfile( r" we := without_extension('/foo/bar/baz') fs := file_stem('/foo/bar/baz.hello.ciao') fn := file_name('/bar/baz.hello.ciao') dir := parent_directory('/foo/') ext := extension('/foo/bar/baz.hello.ciao') foo: /usr/bin/env echo '{{we}}' '{{fs}}' '{{fn}}' '{{dir}}' '{{ext}}' ", ) .stdout("/foo/bar/baz baz.hello baz.hello.ciao / ciao\n") .stderr("/usr/bin/env echo '/foo/bar/baz' 'baz.hello' 'baz.hello.ciao' '/' 'ciao'\n") .run(); } #[cfg(not(windows))] #[test] fn broken_without_extension_function() { Test::new() .justfile( r" we := without_extension('') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{} {}\n{}\n{}\n{}\n{}\n", "error: Call to function `without_extension` failed:", "Could not extract parent from ``", " ——▶ justfile:1:8", " │", "1 │ we := without_extension(\'\')", " │ ^^^^^^^^^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_extension_function() { Test::new() .justfile( r" we := extension('') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{}\n{}\n{}\n{}\n{}\n", "error: Call to function `extension` failed: Could not extract extension from ``", " ——▶ justfile:1:8", " │", "1 │ we := extension(\'\')", " │ ^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_extension_function2() { Test::new() .justfile( r" we := extension('foo') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{}\n{}\n{}\n{}\n{}\n", "error: Call to function `extension` failed: Could not extract extension from `foo`", " ——▶ justfile:1:8", " │", "1 │ we := extension(\'foo\')", " │ ^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_file_stem_function() { Test::new() .justfile( r" we := file_stem('') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{}\n{}\n{}\n{}\n{}\n", "error: Call to function `file_stem` failed: Could not extract file stem from ``", " ——▶ justfile:1:8", " │", "1 │ we := file_stem(\'\')", " │ ^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_file_name_function() { Test::new() .justfile( r" we := file_name('') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{}\n{}\n{}\n{}\n{}\n", "error: Call to function `file_name` failed: Could not extract file name from ``", " ——▶ justfile:1:8", " │", "1 │ we := file_name(\'\')", " │ ^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_directory_function() { Test::new() .justfile( r" we := parent_directory('') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{} {}\n{}\n{}\n{}\n{}\n", "error: Call to function `parent_directory` failed:", "Could not extract parent directory from ``", " ——▶ justfile:1:8", " │", "1 │ we := parent_directory(\'\')", " │ ^^^^^^^^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] #[test] fn broken_directory_function2() { Test::new() .justfile( r" we := parent_directory('/') foo: /usr/bin/env echo '{{we}}' ", ) .stderr( format!( "{} {}\n{}\n{}\n{}\n{}\n", "error: Call to function `parent_directory` failed:", "Could not extract parent directory from `/`", " ——▶ justfile:1:8", " │", "1 │ we := parent_directory(\'/\')", " │ ^^^^^^^^^^^^^^^^" ) .as_str(), ) .status(EXIT_FAILURE) .run(); } #[cfg(windows)] #[test] fn env_var_functions() { Test::new() .justfile( r#" p := env_var('USERNAME') b := env_var_or_default('ZADDY', 'HTAP') x := env_var_or_default('XYZ', 'ABC') foo: /usr/bin/env echo '{{p}}' '{{b}}' '{{x}}' "#, ) .stdout(format!("{} HTAP ABC\n", env::var("USERNAME").unwrap()).as_str()) .stderr( format!( "/usr/bin/env echo '{}' 'HTAP' 'ABC'\n", env::var("USERNAME").unwrap() ) .as_str(), ) .run(); } #[test] fn env_var_failure() { Test::new() .arg("a") .justfile("a:\n echo {{env_var('ZADDY')}}") .status(EXIT_FAILURE) .stderr( "error: Call to function `env_var` failed: environment variable `ZADDY` not present ——▶ justfile:2:10 │ 2 │ echo {{env_var('ZADDY')}} │ ^^^^^^^ ", ) .run(); } #[test] fn test_just_executable_function() { Test::new() .arg("a") .justfile( " a: @printf 'Executable path is: %s\\n' '{{ just_executable() }}' ", ) .status(EXIT_SUCCESS) .stdout( format!( "Executable path is: {}\n", executable_path("just").to_str().unwrap() ) .as_str(), ) .run(); } #[test] fn test_os_arch_functions_in_default() { Test::new() .justfile( r" foo a=arch() o=os() f=os_family() n=num_cpus(): echo {{a}} {{o}} {{f}} {{n}} ", ) .stdout( format!( "{} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .stderr( format!( "echo {} {} {} {}\n", target::arch(), target::os(), target::family(), num_cpus::get() ) .as_str(), ) .run(); } #[test] fn clean() { Test::new() .justfile( " foo: echo {{ clean('a/../b') }} ", ) .stdout("b\n") .stderr("echo b\n") .run(); } #[test] fn uppercase() { Test::new() .justfile( " foo: echo {{ uppercase('bar') }} ", ) .stdout("BAR\n") .stderr("echo BAR\n") .run(); } #[test] fn lowercase() { Test::new() .justfile( " foo: echo {{ lowercase('BAR') }} ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn uppercamelcase() { Test::new() .justfile( " foo: echo {{ uppercamelcase('foo bar') }} ", ) .stdout("FooBar\n") .stderr("echo FooBar\n") .run(); } #[test] fn lowercamelcase() { Test::new() .justfile( " foo: echo {{ lowercamelcase('foo bar') }} ", ) .stdout("fooBar\n") .stderr("echo fooBar\n") .run(); } #[test] fn snakecase() { Test::new() .justfile( " foo: echo {{ snakecase('foo bar') }} ", ) .stdout("foo_bar\n") .stderr("echo foo_bar\n") .run(); } #[test] fn kebabcase() { Test::new() .justfile( " foo: echo {{ kebabcase('foo bar') }} ", ) .stdout("foo-bar\n") .stderr("echo foo-bar\n") .run(); } #[test] fn shoutysnakecase() { Test::new() .justfile( " foo: echo {{ shoutysnakecase('foo bar') }} ", ) .stdout("FOO_BAR\n") .stderr("echo FOO_BAR\n") .run(); } #[test] fn titlecase() { Test::new() .justfile( " foo: echo {{ titlecase('foo bar') }} ", ) .stdout("Foo Bar\n") .stderr("echo Foo Bar\n") .run(); } #[test] fn shoutykebabcase() { Test::new() .justfile( " foo: echo {{ shoutykebabcase('foo bar') }} ", ) .stdout("FOO-BAR\n") .stderr("echo FOO-BAR\n") .run(); } #[test] fn trim() { Test::new() .justfile( " foo: echo {{ trim(' bar ') }} ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn replace() { Test::new() .justfile( " foo: echo {{ replace('barbarbar', 'bar', 'foo') }} ", ) .stdout("foofoofoo\n") .stderr("echo foofoofoo\n") .run(); } #[test] fn replace_regex() { Test::new() .justfile( " foo: echo {{ replace_regex('123bar123bar123bar', '\\d+bar', 'foo') }} ", ) .stdout("foofoofoo\n") .stderr("echo foofoofoo\n") .run(); } #[test] fn invalid_replace_regex() { Test::new() .justfile( " foo: echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }} ", ) .stderr( "error: Call to function `replace_regex` failed: regex parse error: foo\\ ^ error: incomplete escape sequence, reached end of pattern prematurely ——▶ justfile:2:11 │ 2 │ echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }} │ ^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn capitalize() { Test::new() .justfile( " foo: echo {{ capitalize('BAR') }} ", ) .stdout("Bar\n") .stderr("echo Bar\n") .run(); } #[test] fn semver_matches() { Test::new() .justfile( " foo: echo {{ semver_matches('0.1.0', '>=0.1.0') }} echo {{ semver_matches('0.1.0', '=0.0.1') }} ", ) .stdout("true\nfalse\n") .stderr("echo true\necho false\n") .run(); } #[test] fn trim_end_matches() { assert_eval_eq("trim_end_matches('foo', 'o')", "f"); assert_eval_eq("trim_end_matches('fabab', 'ab')", "f"); assert_eval_eq("trim_end_matches('fbaabab', 'ab')", "fba"); } #[test] fn trim_end_match() { assert_eval_eq("trim_end_match('foo', 'o')", "fo"); assert_eval_eq("trim_end_match('fabab', 'ab')", "fab"); } #[test] fn trim_start_matches() { assert_eval_eq("trim_start_matches('oof', 'o')", "f"); assert_eval_eq("trim_start_matches('ababf', 'ab')", "f"); assert_eval_eq("trim_start_matches('ababbaf', 'ab')", "baf"); } #[test] fn trim_start_match() { assert_eval_eq("trim_start_match('oof', 'o')", "of"); assert_eval_eq("trim_start_match('ababf', 'ab')", "abf"); } #[test] fn trim_start() { assert_eval_eq("trim_start(' f ')", "f "); } #[test] fn trim_end() { assert_eval_eq("trim_end(' f ')", " f"); } #[test] fn append() { assert_eval_eq("append('8', 'r s t')", "r8 s8 t8"); assert_eval_eq("append('.c', 'main sar x11')", "main.c sar.c x11.c"); assert_eval_eq("append('-', 'c v h y')", "c- v- h- y-"); assert_eval_eq( "append('0000', '11 10 01 00')", "110000 100000 010000 000000", ); assert_eval_eq( "append('tion', ' Determina Acquisi Motiva Conjuc ')", "Determination Acquisition Motivation Conjuction", ); } #[test] fn prepend() { assert_eval_eq("prepend('8', 'r s t\n \n ')", "8r 8s 8t"); assert_eval_eq( "prepend('src/', 'main sar x11')", "src/main src/sar src/x11", ); assert_eval_eq("prepend('-', 'c\tv h\ny')", "-c -v -h -y"); assert_eval_eq( "prepend('0000', '11 10 01 00')", "000011 000010 000001 000000", ); assert_eval_eq( "prepend('April-', ' 1st, 17th, 20th, ')", "April-1st, April-17th, April-20th,", ); } #[test] #[cfg(not(windows))] fn join() { assert_eval_eq("join('a', 'b', 'c', 'd')", "a/b/c/d"); assert_eval_eq("join('a', '/b', 'c', 'd')", "/b/c/d"); assert_eval_eq("join('a', '/b', '/c', 'd')", "/c/d"); assert_eval_eq("join('a', '/b', '/c', '/d')", "/d"); } #[test] #[cfg(windows)] fn join() { assert_eval_eq("join('a', 'b', 'c', 'd')", "a\\b\\c\\d"); assert_eval_eq("join('a', '\\b', 'c', 'd')", "\\b\\c\\d"); assert_eval_eq("join('a', '\\b', '\\c', 'd')", "\\c\\d"); assert_eval_eq("join('a', '\\b', '\\c', '\\d')", "\\d"); } #[test] fn join_argument_count_error() { Test::new() .justfile("x := join('a')") .args(["--evaluate"]) .stderr( " error: Function `join` called with 1 argument but takes 2 or more ——▶ justfile:1:6 │ 1 │ x := join(\'a\') │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn test_path_exists_filepath_exist() { Test::new() .tree(tree! { testfile: "" }) .justfile("x := path_exists('testfile')") .args(["--evaluate", "x"]) .stdout("true") .run(); } #[test] fn test_path_exists_filepath_doesnt_exist() { Test::new() .justfile("x := path_exists('testfile')") .args(["--evaluate", "x"]) .stdout("false") .run(); } #[test] fn error_errors_with_message() { Test::new() .justfile("x := error ('Thing Not Supported')") .args(["--evaluate"]) .status(1) .stderr( " error: Call to function `error` failed: Thing Not Supported ——▶ justfile:1:6 │ 1 │ x := error ('Thing Not Supported') │ ^^^^^ ", ) .run(); } #[test] fn test_absolute_path_resolves() { let test_object = Test::new() .justfile("path := absolute_path('./test_file')") .args(["--evaluate", "path"]); let mut tempdir = test_object.tempdir.path().to_owned(); // Just retrieves the current directory via env::current_dir(), which // does the moral equivalent of canonicalize, which will remove symlinks. // So, we have to canonicalize here, so that we can match it. if cfg!(unix) { tempdir = tempdir.canonicalize().unwrap(); } test_object .stdout(tempdir.join("test_file").to_str().unwrap().to_owned()) .run(); } #[test] fn test_absolute_path_resolves_parent() { let test_object = Test::new() .justfile("path := absolute_path('../test_file')") .args(["--evaluate", "path"]); let mut tempdir = test_object.tempdir.path().to_owned(); // Just retrieves the current directory via env::current_dir(), which // does the moral equivalent of canonicalize, which will remove symlinks. // So, we have to canonicalize here, so that we can match it. if cfg!(unix) { tempdir = tempdir.canonicalize().unwrap(); } test_object .stdout( tempdir .parent() .unwrap() .join("test_file") .to_str() .unwrap() .to_owned(), ) .run(); } #[test] fn path_exists_subdir() { Test::new() .tree(tree! { foo: "", bar: { } }) .justfile("x := path_exists('foo')") .current_dir("bar") .args(["--evaluate", "x"]) .stdout("true") .run(); } #[test] fn uuid() { Test::new() .justfile("x := uuid()") .args(["--evaluate", "x"]) .stdout_regex("........-....-....-....-............") .run(); } #[test] fn choose() { Test::new() .justfile(r"x := choose('10', 'xXyYzZ')") .args(["--evaluate", "x"]) .stdout_regex("^[X-Zx-z]{10}$") .run(); } #[test] fn choose_bad_alphabet_empty() { Test::new() .justfile("x := choose('10', '')") .args(["--evaluate"]) .status(1) .stderr( " error: Call to function `choose` failed: empty alphabet ——▶ justfile:1:6 │ 1 │ x := choose('10', '') │ ^^^^^^ ", ) .run(); } #[test] fn choose_bad_alphabet_repeated() { Test::new() .justfile("x := choose('10', 'aa')") .args(["--evaluate"]) .status(1) .stderr( " error: Call to function `choose` failed: alphabet contains repeated character `a` ——▶ justfile:1:6 │ 1 │ x := choose('10', 'aa') │ ^^^^^^ ", ) .run(); } #[test] fn choose_bad_length() { Test::new() .justfile("x := choose('foo', HEX)") .args(["--evaluate"]) .status(1) .stderr( " error: Call to function `choose` failed: failed to parse `foo` as positive integer: invalid digit found in string ——▶ justfile:1:6 │ 1 │ x := choose('foo', HEX) │ ^^^^^^ ", ) .run(); } #[test] fn sha256() { Test::new() .justfile("x := sha256('5943ee37-0000-1000-8000-010203040506')") .args(["--evaluate", "x"]) .stdout("2330d7f5eb94a820b54fed59a8eced236f80b633a504289c030b6a65aef58871") .run(); } #[test] fn sha256_file() { Test::new() .justfile("x := sha256_file('sub/shafile')") .tree(tree! { sub: { shafile: "just is great\n", } }) .current_dir("sub") .args(["--evaluate", "x"]) .stdout("177b3d79aaafb53a7a4d7aaba99a82f27c73370e8cb0295571aade1e4fea1cd2") .run(); } #[test] fn just_pid() { let Output { stdout, pid, .. } = Test::new() .args(["--evaluate", "x"]) .justfile("x := just_pid()") .stdout_regex(r"\d+") .run(); assert_eq!(stdout.parse::().unwrap(), pid); } #[test] fn shell_no_argument() { Test::new() .justfile("var := shell()") .args(["--evaluate"]) .stderr( " error: Function `shell` called with 0 arguments but takes 1 or more ——▶ justfile:1:8 │ 1 │ var := shell() │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn shell_minimal() { assert_eval_eq("shell('echo $1 $2', 'justice', 'legs')", "justice legs"); } #[test] fn shell_args() { assert_eval_eq("shell('echo $@', 'justice', 'legs')", "justice legs"); } #[test] fn shell_first_arg() { assert_eval_eq("shell('echo $0')", "echo $0"); } #[test] fn shell_error() { Test::new() .justfile("var := shell('exit 1')") .args(["--evaluate"]) .stderr( " error: Call to function `shell` failed: Process exited with status code 1 ——▶ justfile:1:8 │ 1 │ var := shell('exit 1') │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn blake3() { Test::new() .justfile("x := blake3('5943ee37-0000-1000-8000-010203040506')") .args(["--evaluate", "x"]) .stdout("026c9f740a793ff536ddf05f8915ea4179421f47f0fa9545476076e9ba8f3f2b") .run(); } #[test] fn blake3_file() { Test::new() .justfile("x := blake3_file('sub/blakefile')") .tree(tree! { sub: { blakefile: "just is great\n", } }) .current_dir("sub") .args(["--evaluate", "x"]) .stdout("8379241877190ca4b94076a8c8f89fe5747f95c62f3e4bf41f7408a0088ae16d") .run(); } #[cfg(unix)] #[test] fn canonicalize() { Test::new() .args(["--evaluate", "x"]) .justfile("x := canonicalize('foo')") .symlink("justfile", "foo") .stdout_regex(".*/justfile") .run(); } #[test] fn encode_uri_component() { Test::new() .justfile("x := encode_uri_component(\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\r\\n🌐\")") .args(["--evaluate", "x"]) .stdout("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!%22%23%24%25%26'()*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~%20%09%0D%0A%F0%9F%8C%90") .run(); } #[test] fn source_file() { Test::new() .args(["--evaluate", "x"]) .justfile("x := source_file()") .stdout_regex(r".*[/\\]justfile") .run(); Test::new() .args(["--evaluate", "x"]) .justfile( " import 'foo.just' ", ) .write("foo.just", "x := source_file()") .stdout_regex(r".*[/\\]foo.just") .run(); Test::new() .args(["foo", "bar"]) .justfile( " mod foo ", ) .write("foo.just", "x := source_file()\nbar:\n @echo '{{x}}'") .stdout_regex(r".*[/\\]foo.just\n") .run(); } #[test] fn source_directory() { Test::new() .args(["foo", "bar"]) .justfile( " mod foo ", ) .write( "foo/mod.just", "x := source_directory()\nbar:\n @echo '{{x}}'", ) .stdout_regex(r".*[/\\]foo\n") .run(); } #[test] fn module_paths() { Test::new() .write( "foo/bar.just", " imf := module_file() imd := module_directory() import-outer: import-inner @import-inner pmf=module_file() pmd=module_directory(): echo import echo '{{ imf }}' echo '{{ imd }}' echo '{{ pmf }}' echo '{{ pmd }}' echo '{{ module_file() }}' echo '{{ module_directory() }}' ", ) .write( "baz/mod.just", " import 'foo/bar.just' mmf := module_file() mmd := module_directory() outer: inner @inner pmf=module_file() pmd=module_directory(): echo module echo '{{ mmf }}' echo '{{ mmd }}' echo '{{ pmf }}' echo '{{ pmd }}' echo '{{ module_file() }}' echo '{{ module_directory() }}' ", ) .write( "baz/foo/bar.just", " imf := module_file() imd := module_directory() import-outer: import-inner @import-inner pmf=module_file() pmd=module_directory(): echo import echo '{{ imf }}' echo '{{ imd }}' echo '{{ pmf }}' echo '{{ pmd }}' echo '{{ module_file() }}' echo '{{ module_directory() }}' ", ) .justfile( " import 'foo/bar.just' mod baz rmf := module_file() rmd := module_directory() outer: inner @inner pmf=module_file() pmd=module_directory(): echo root echo '{{ rmf }}' echo '{{ rmd }}' echo '{{ pmf }}' echo '{{ pmd }}' echo '{{ module_file() }}' echo '{{ module_directory() }}' ", ) .args([ "outer", "import-outer", "baz", "outer", "baz", "import-outer", ]) .stdout_regex( r"root .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... import .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... .*[/\\]just-test-tempdir......[/\\]justfile .*[/\\]just-test-tempdir...... module .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz import .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz .*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just .*[/\\]just-test-tempdir......[/\\]baz ", ) .run(); } #[test] fn is_dependency() { let justfile = " alpha: beta @echo 'alpha {{is_dependency()}}' beta: && gamma @echo 'beta {{is_dependency()}}' gamma: @echo 'gamma {{is_dependency()}}' "; Test::new() .args(["alpha"]) .justfile(justfile) .stdout("beta true\ngamma true\nalpha false\n") .run(); Test::new() .args(["beta"]) .justfile(justfile) .stdout("beta false\ngamma true\n") .run(); } #[test] fn unary_argument_count_mismamatch_error_message() { Test::new() .justfile("x := datetime()") .args(["--evaluate"]) .stderr( " error: Function `datetime` called with 0 arguments but takes 1 ——▶ justfile:1:6 │ 1 │ x := datetime() │ ^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dir_abbreviations_are_accepted() { Test::new() .justfile( " abbreviated := justfile_dir() unabbreviated := justfile_directory() @foo: # {{ assert(abbreviated == unabbreviated, 'fail') }} ", ) .run(); } #[test] fn invocation_dir_native_abbreviation_is_accepted() { Test::new() .justfile( " abbreviated := invocation_directory_native() unabbreviated := invocation_dir_native() @foo: # {{ assert(abbreviated == unabbreviated, 'fail') }} ", ) .run(); } #[test] fn absolute_path_argument_is_relative_to_submodule_working_directory() { Test::new() .justfile("mod foo") .write("foo/baz", "") .write( "foo/mod.just", r#" bar: @echo "{{ absolute_path('baz') }}" "#, ) .stdout_regex(r".*[/\\]foo[/\\]baz\n") .args(["foo", "bar"]) .run(); } #[test] fn blake3_file_argument_is_relative_to_submodule_working_directory() { Test::new() .justfile("mod foo") .write("foo/baz", "") .write( "foo/mod.just", " bar: @echo {{ blake3_file('baz') }} ", ) .stdout("af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262\n") .args(["foo", "bar"]) .run(); } #[test] fn canonicalize_argument_is_relative_to_submodule_working_directory() { Test::new() .justfile("mod foo") .write("foo/baz", "") .write( "foo/mod.just", r#" bar: @echo "{{ canonicalize('baz') }}" "#, ) .stdout_regex(r".*[/\\]foo[/\\]baz\n") .args(["foo", "bar"]) .run(); } #[test] fn path_exists_argument_is_relative_to_submodule_working_directory() { Test::new() .justfile("mod foo") .write("foo/baz", "") .write( "foo/mod.just", " bar: @echo {{ path_exists('baz') }} ", ) .stdout_regex("true\n") .args(["foo", "bar"]) .run(); } #[test] fn sha256_file_argument_is_relative_to_submodule_working_directory() { Test::new() .justfile("mod foo") .write("foo/baz", "") .write( "foo/mod.just", " bar: @echo {{ sha256_file('baz') }} ", ) .stdout_regex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n") .args(["foo", "bar"]) .run(); } #[test] fn style_command_default() { Test::new() .justfile( r#" foo: @echo '{{ style("command") }}foo{{NORMAL}}' "#, ) .stdout("\x1b[1mfoo\x1b[0m\n") .run(); } #[test] fn style_command_non_default() { Test::new() .justfile( r#" foo: @echo '{{ style("command") }}foo{{NORMAL}}' "#, ) .args(["--command-color", "red"]) .stdout("\x1b[1;31mfoo\x1b[0m\n") .run(); } #[test] fn style_error() { Test::new() .justfile( r#" foo: @echo '{{ style("error") }}foo{{NORMAL}}' "#, ) .stdout("\x1b[1;31mfoo\x1b[0m\n") .run(); } #[test] fn style_warning() { Test::new() .justfile( r#" foo: @echo '{{ style("warning") }}foo{{NORMAL}}' "#, ) .stdout("\x1b[1;33mfoo\x1b[0m\n") .run(); } #[test] fn style_unknown() { Test::new() .justfile( r#" foo: @echo '{{ style("hippo") }}foo{{NORMAL}}' "#, ) .stderr( r#" error: Call to function `style` failed: unknown style: `hippo` ——▶ justfile:2:13 │ 2 │ @echo '{{ style("hippo") }}foo{{NORMAL}}' │ ^^^^^ "#, ) .status(EXIT_FAILURE) .run(); } #[test] fn read() { Test::new() .justfile("foo := read('bar')") .write("bar", "baz") .args(["--evaluate", "foo"]) .stdout("baz") .run(); } #[test] fn read_file_not_found() { Test::new() .justfile("foo := read('bar')") .args(["--evaluate", "foo"]) .stderr_regex(r"error: Call to function `read` failed: I/O error reading `bar`: .*") .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/global.rs000064400000000000000000000026121046102023000136440ustar 00000000000000use super::*; #[test] #[cfg(target_os = "macos")] fn macos() { let tempdir = tempdir(); let path = tempdir.path().to_owned(); Test::with_tempdir(tempdir) .no_justfile() .test_round_trip(false) .write( "Library/Application Support/just/justfile", "@default:\n echo foo", ) .env("HOME", path.to_str().unwrap()) .args(["--global-justfile"]) .stdout("foo\n") .run(); } #[test] #[cfg(all(unix, not(target_os = "macos")))] fn not_macos() { let tempdir = tempdir(); let path = tempdir.path().to_owned(); Test::with_tempdir(tempdir) .no_justfile() .test_round_trip(false) .write("just/justfile", "@default:\n echo foo") .env("XDG_CONFIG_HOME", path.to_str().unwrap()) .args(["--global-justfile"]) .stdout("foo\n") .run(); } #[test] #[cfg(unix)] fn unix() { let tempdir = tempdir(); let path = tempdir.path().to_owned(); let tempdir = Test::with_tempdir(tempdir) .no_justfile() .test_round_trip(false) .write("justfile", "@default:\n echo foo") .env("HOME", path.to_str().unwrap()) .args(["--global-justfile"]) .stdout("foo\n") .run() .tempdir; Test::with_tempdir(tempdir) .no_justfile() .test_round_trip(false) .write(".config/just/justfile", "@default:\n echo bar") .env("HOME", path.to_str().unwrap()) .args(["--global-justfile"]) .stdout("bar\n") .run(); } just-1.40.0/tests/groups.rs000064400000000000000000000073071046102023000137310ustar 00000000000000use super::*; #[test] fn list_with_groups() { Test::new() .justfile( " [group('alpha')] a: # Doc comment [group('alpha')] [group('beta')] b: c: [group('multi word group')] d: [group('alpha')] e: [group('beta')] [group('alpha')] f: ", ) .arg("--list") .stdout( " Available recipes: c [alpha] a b # Doc comment e f [beta] b # Doc comment f [multi word group] d ", ) .run(); } #[test] fn list_with_groups_unsorted() { Test::new() .justfile( " [group('beta')] [group('alpha')] f: [group('alpha')] e: [group('multi word group')] d: c: # Doc comment [group('alpha')] [group('beta')] b: [group('alpha')] a: ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: c [alpha] f e b # Doc comment a [beta] f b # Doc comment [multi word group] d ", ) .run(); } #[test] fn list_with_groups_unsorted_group_order() { Test::new() .justfile( " [group('y')] [group('x')] f: [group('b')] b: [group('a')] e: c: ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: c [x] f [y] f [b] b [a] e ", ) .run(); } #[test] fn list_groups() { Test::new() .justfile( " [group('B')] bar: [group('A')] [group('B')] foo: ", ) .args(["--groups"]) .stdout( " Recipe groups: A B ", ) .run(); } #[test] fn list_groups_with_custom_prefix() { Test::new() .justfile( " [group('B')] foo: [group('A')] [group('B')] bar: ", ) .args(["--groups", "--list-prefix", "..."]) .stdout( " Recipe groups: ...A ...B ", ) .run(); } #[test] fn list_groups_with_shorthand_syntax() { Test::new() .justfile( " [group: 'B'] foo: [group: 'A', group: 'B'] bar: ", ) .arg("--groups") .stdout( " Recipe groups: A B ", ) .run(); } #[test] fn list_groups_unsorted() { Test::new() .justfile( " [group: 'Z'] baz: [group: 'B'] foo: [group: 'A', group: 'B'] bar: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: Z B A ", ) .run(); } #[test] fn list_groups_private_unsorted() { Test::new() .justfile( " [private] [group: 'A'] foo: [group: 'B'] bar: [group: 'A'] baz: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: B A ", ) .run(); } #[test] fn list_groups_private() { Test::new() .justfile( " [private] [group: 'A'] foo: [group: 'B'] bar: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: B ", ) .run(); } just-1.40.0/tests/ignore_comments.rs000064400000000000000000000045501046102023000155770ustar 00000000000000use super::*; #[test] fn ignore_comments_in_recipe() { Test::new() .justfile( " set ignore-comments some_recipe: # A recipe-internal comment echo something-useful ", ) .stdout("something-useful\n") .stderr("echo something-useful\n") .run(); } #[test] fn dont_ignore_comments_in_recipe_by_default() { Test::new() .justfile( " some_recipe: # A recipe-internal comment echo something-useful ", ) .stdout("something-useful\n") .stderr("# A recipe-internal comment\necho something-useful\n") .run(); } #[test] fn ignore_recipe_comments_with_shell_setting() { Test::new() .justfile( " set shell := ['echo', '-n'] set ignore-comments some_recipe: # Alternate shells still ignore comments echo something-useful ", ) .stdout("something-useful\n") .stderr("echo something-useful\n") .run(); } #[test] fn continuations_with_echo_comments_false() { Test::new() .justfile( " set ignore-comments some_recipe: # Comment lines ignore line continuations \\ echo something-useful ", ) .stdout("something-useful\n") .stderr("echo something-useful\n") .run(); } #[test] fn continuations_with_echo_comments_true() { Test::new() .justfile( " set ignore-comments := false some_recipe: # comment lines can be continued \\ echo something-useful ", ) .stderr("# comment lines can be continued echo something-useful\n") .run(); } #[test] fn dont_evaluate_comments() { Test::new() .justfile( " set ignore-comments some_recipe: # {{ error('foo') }} ", ) .run(); } #[test] fn dont_analyze_comments() { Test::new() .justfile( " set ignore-comments some_recipe: # {{ bar }} ", ) .run(); } #[test] fn comments_still_must_be_parsable_when_ignored() { Test::new() .justfile( " set ignore-comments some_recipe: # {{ foo bar }} ", ) .stderr( " error: Expected '&&', '||', '}}', '(', '+', or '/', but found identifier ——▶ justfile:4:12 │ 4 │ # {{ foo bar }} │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/imports.rs000064400000000000000000000154011046102023000141010ustar 00000000000000use super::*; #[test] fn import_succeeds() { Test::new() .tree(tree! { "import.justfile": " b: @echo B ", }) .justfile( " import './import.justfile' a: b @echo A ", ) .arg("a") .stdout("B\nA\n") .run(); } #[test] fn missing_import_file_error() { Test::new() .justfile( " import './import.justfile' a: @echo A ", ) .arg("a") .status(EXIT_FAILURE) .stderr( " error: Could not find source file for import. ——▶ justfile:1:8 │ 1 │ import './import.justfile' │ ^^^^^^^^^^^^^^^^^^^ ", ) .run(); } #[test] fn missing_optional_imports_are_ignored() { Test::new() .justfile( " import? './import.justfile' a: @echo A ", ) .arg("a") .stdout("A\n") .run(); } #[test] fn trailing_spaces_after_import_are_ignored() { Test::new() .tree(tree! { "import.justfile": "", }) .justfile( " import './import.justfile'\x20 a: @echo A ", ) .stdout("A\n") .run(); } #[test] fn import_after_recipe() { Test::new() .tree(tree! { "import.justfile": " a: @echo A ", }) .justfile( " b: a import './import.justfile' ", ) .stdout("A\n") .run(); } #[test] fn circular_import() { Test::new() .justfile("import 'a'") .tree(tree! { a: "import 'b'", b: "import 'a'", }) .status(EXIT_FAILURE) .stderr_regex(path_for_regex( "error: Import `.*/a` in `.*/b` is circular\n", )) .run(); } #[test] fn import_recipes_are_not_default() { Test::new() .tree(tree! { "import.justfile": "bar:", }) .justfile("import './import.justfile'") .status(EXIT_FAILURE) .stderr("error: Justfile contains no default recipe.\n") .run(); } #[test] fn listed_recipes_in_imports_are_in_load_order() { Test::new() .justfile( " import './import.justfile' foo: ", ) .write("import.justfile", "bar:") .args(["--list", "--unsorted"]) .stdout( " Available recipes: foo bar ", ) .run(); } #[test] fn include_error() { Test::new() .justfile("!include foo") .status(EXIT_FAILURE) .stderr( " error: The `!include` directive has been stabilized as `import` ——▶ justfile:1:1 │ 1 │ !include foo │ ^ ", ) .run(); } #[test] fn recipes_in_import_are_overridden_by_recipes_in_parent() { Test::new() .tree(tree! { "import.justfile": " a: @echo IMPORT ", }) .justfile( " a: @echo ROOT import './import.justfile' set allow-duplicate-recipes ", ) .arg("a") .stdout("ROOT\n") .run(); } #[test] fn variables_in_import_are_overridden_by_variables_in_parent() { Test::new() .tree(tree! { "import.justfile": " f := 'foo' ", }) .justfile( " f := 'bar' import './import.justfile' set allow-duplicate-variables a: @echo {{f}} ", ) .arg("a") .stdout("bar\n") .run(); } #[cfg(not(windows))] #[test] fn import_paths_beginning_with_tilde_are_expanded_to_homdir() { Test::new() .write("foobar/mod.just", "foo:\n @echo FOOBAR") .justfile( " import '~/mod.just' ", ) .arg("foo") .stdout("FOOBAR\n") .env("HOME", "foobar") .run(); } #[test] fn imports_dump_correctly() { Test::new() .write("import.justfile", "") .justfile( " import './import.justfile' ", ) .arg("--dump") .stdout("import './import.justfile'\n") .run(); } #[test] fn optional_imports_dump_correctly() { Test::new() .write("import.justfile", "") .justfile( " import? './import.justfile' ", ) .arg("--dump") .stdout("import? './import.justfile'\n") .run(); } #[test] fn imports_in_root_run_in_justfile_directory() { Test::new() .write("foo/import.justfile", "bar:\n @cat baz") .write("baz", "BAZ") .justfile( " import 'foo/import.justfile' ", ) .arg("bar") .stdout("BAZ") .run(); } #[test] fn imports_in_submodules_run_in_submodule_directory() { Test::new() .justfile("mod foo") .write("foo/mod.just", "import 'import.just'") .write("foo/import.just", "bar:\n @cat baz") .write("foo/baz", "BAZ") .arg("foo") .arg("bar") .stdout("BAZ") .run(); } #[test] fn nested_import_paths_are_relative_to_containing_submodule() { Test::new() .justfile("import 'foo/import.just'") .write("foo/import.just", "import 'bar.just'") .write("foo/bar.just", "bar:\n @echo BAR") .arg("bar") .stdout("BAR\n") .run(); } #[test] fn recipes_in_nested_imports_run_in_parent_module() { Test::new() .justfile("import 'foo/import.just'") .write("foo/import.just", "import 'bar/import.just'") .write("foo/bar/import.just", "bar:\n @cat baz") .write("baz", "BAZ") .arg("bar") .stdout("BAZ") .run(); } #[test] fn shebang_recipes_in_imports_in_root_run_in_justfile_directory() { Test::new() .write( "foo/import.justfile", "bar:\n #!/usr/bin/env bash\n cat baz", ) .write("baz", "BAZ") .justfile( " import 'foo/import.justfile' ", ) .arg("bar") .stdout("BAZ") .run(); } #[test] fn recipes_imported_in_root_run_in_command_line_provided_working_directory() { Test::new() .write("subdir/b.justfile", "@b:\n cat baz") .write("subdir/a.justfile", "import 'b.justfile'\n@a: b\n cat baz") .write("baz", "BAZ") .args([ "--working-directory", ".", "--justfile", "subdir/a.justfile", ]) .stdout("BAZBAZ") .run(); } #[test] fn reused_import_are_allowed() { Test::new() .justfile( " import 'a' import 'b' bar: ", ) .tree(tree! { a: "import 'c'", b: "import 'c'", c: "", }) .run(); } #[test] fn multiply_imported_items_do_not_conflict() { Test::new() .justfile( " import 'a.just' import 'a.just' foo: bar ", ) .write( "a.just", " x := 'y' @bar: echo hello ", ) .stdout("hello\n") .run(); } #[test] fn nested_multiply_imported_items_do_not_conflict() { Test::new() .justfile( " import 'a.just' import 'b.just' foo: bar ", ) .write("a.just", "import 'c.just'") .write("b.just", "import 'c.just'") .write( "c.just", " x := 'y' @bar: echo hello ", ) .stdout("hello\n") .run(); } just-1.40.0/tests/init.rs000064400000000000000000000074141046102023000133540ustar 00000000000000use super::*; const EXPECTED: &str = "default:\n echo 'Hello, world!'\n"; #[test] fn current_dir() { let tmp = tempdir(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), EXPECTED ); } #[test] fn exists() { let output = Test::new() .no_justfile() .arg("--init") .stderr_regex("Wrote justfile to `.*`\n") .run(); Test::with_tempdir(output.tempdir) .no_justfile() .arg("--init") .status(EXIT_FAILURE) .stderr_regex("error: Justfile `.*` already exists\n") .run(); } #[test] fn write_error() { let test = Test::new(); let justfile_path = test.justfile_path(); fs::create_dir(justfile_path).unwrap(); test .no_justfile() .args(["--init"]) .status(EXIT_FAILURE) .stderr_regex(if cfg!(windows) { r"error: Failed to write justfile to `.*`: Access is denied. \(os error 5\)\n" } else { r"error: Failed to write justfile to `.*`: Is a directory \(os error 21\)\n" }) .run(); } #[test] fn invocation_directory() { let tmp = temptree! { ".git": {}, }; let test = Test::with_tempdir(tmp); let justfile_path = test.justfile_path(); let _tmp = test .no_justfile() .stderr_regex("Wrote justfile to `.*`\n") .arg("--init") .run(); assert_eq!(fs::read_to_string(justfile_path).unwrap(), EXPECTED); } #[test] fn parent_dir() { let tmp = temptree! { ".git": {}, sub: {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), EXPECTED ); } #[test] fn alternate_marker() { let tmp = temptree! { "_darcs": {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), EXPECTED ); } #[test] fn search_directory() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .arg("sub/") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("sub/justfile")).unwrap(), EXPECTED ); } #[test] fn justfile() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .arg("--justfile") .arg(tmp.path().join("justfile")) .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), EXPECTED ); } #[test] fn justfile_and_working_directory() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .arg("--justfile") .arg(tmp.path().join("justfile")) .arg("--working-directory") .arg("/") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), EXPECTED ); } #[test] fn fmt_compatibility() { let output = Test::new() .no_justfile() .arg("--init") .stderr_regex("Wrote justfile to `.*`\n") .run(); Test::with_tempdir(output.tempdir) .no_justfile() .arg("--unstable") .arg("--check") .arg("--fmt") .status(EXIT_SUCCESS) .run(); } just-1.40.0/tests/interrupts.rs000064400000000000000000000027501046102023000146260ustar 00000000000000use { super::*, std::time::{Duration, Instant}, }; fn kill(process_id: u32) { unsafe { libc::kill(process_id.try_into().unwrap(), libc::SIGINT); } } fn interrupt_test(arguments: &[&str], justfile: &str) { let tmp = tempdir(); let mut justfile_path = tmp.path().to_path_buf(); justfile_path.push("justfile"); fs::write(justfile_path, unindent(justfile)).unwrap(); let start = Instant::now(); let mut child = Command::new(executable_path("just")) .current_dir(&tmp) .args(arguments) .spawn() .expect("just invocation failed"); while start.elapsed() < Duration::from_millis(500) {} kill(child.id()); let status = child.wait().unwrap(); let elapsed = start.elapsed(); assert!( elapsed <= Duration::from_secs(2), "process returned too late: {elapsed:?}" ); assert!( elapsed >= Duration::from_millis(100), "process returned too early : {elapsed:?}" ); assert_eq!(status.code(), Some(130)); } #[test] #[ignore] fn interrupt_shebang() { interrupt_test( &[], " default: #!/usr/bin/env sh sleep 1 ", ); } #[test] #[ignore] fn interrupt_line() { interrupt_test( &[], " default: @sleep 1 ", ); } #[test] #[ignore] fn interrupt_backtick() { interrupt_test( &[], " foo := `sleep 1` default: @echo {{foo}} ", ); } #[test] #[ignore] fn interrupt_command() { interrupt_test(&["--command", "sleep", "1"], ""); } just-1.40.0/tests/invocation_directory.rs000064400000000000000000000046471046102023000166530ustar 00000000000000use super::*; #[cfg(unix)] fn convert_native_path(path: &Path) -> String { fs::canonicalize(path) .expect("canonicalize failed") .to_str() .map(str::to_string) .expect("unicode decode failed") } #[cfg(windows)] fn convert_native_path(path: &Path) -> String { // Translate path from windows style to unix style let mut cygpath = Command::new("cygpath"); cygpath.arg("--unix"); cygpath.arg(path); let output = cygpath.output().expect("executing cygpath failed"); assert!(output.status.success()); let stdout = str::from_utf8(&output.stdout).expect("cygpath output was not utf8"); if stdout.ends_with('\n') { &stdout[0..stdout.len() - 1] } else if stdout.ends_with("\r\n") { &stdout[0..stdout.len() - 2] } else { stdout } .to_owned() } #[test] fn test_invocation_directory() { let tmp = tempdir(); let mut justfile_path = tmp.path().to_path_buf(); justfile_path.push("justfile"); fs::write( justfile_path, "default:\n @cd {{invocation_directory()}}\n @echo {{invocation_directory()}}", ) .unwrap(); let mut subdir = tmp.path().to_path_buf(); subdir.push("subdir"); fs::create_dir(&subdir).unwrap(); let output = Command::new(executable_path("just")) .current_dir(&subdir) .args(["--shell", "sh"]) .output() .expect("just invocation failed"); let mut failure = false; let expected_status = 0; let expected_stdout = convert_native_path(&subdir) + "\n"; let expected_stderr = ""; let status = output.status.code().unwrap(); if status != expected_status { println!("bad status: {status} != {expected_status}"); failure = true; } let stdout = str::from_utf8(&output.stdout).unwrap(); if stdout != expected_stdout { println!("bad stdout:\ngot:\n{stdout:?}\n\nexpected:\n{expected_stdout:?}"); failure = true; } let stderr = str::from_utf8(&output.stderr).unwrap(); if stderr != expected_stderr { println!("bad stderr:\ngot:\n{stderr:?}\n\nexpected:\n{expected_stderr:?}"); failure = true; } assert!(!failure, "test failed"); } #[test] fn invocation_directory_native() { let Output { stdout, tempdir, .. } = Test::new() .justfile("x := invocation_directory_native()") .args(["--evaluate", "x"]) .stdout_regex(".*") .run(); if cfg!(windows) { assert_eq!(Path::new(&stdout), tempdir.path()); } else { assert_eq!(Path::new(&stdout), tempdir.path().canonicalize().unwrap()); } } just-1.40.0/tests/json.rs000064400000000000000000000400621046102023000133560ustar 00000000000000use super::*; #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Alias<'a> { attributes: Vec<&'a str>, name: &'a str, target: &'a str, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Assignment<'a> { export: bool, name: &'a str, private: bool, value: &'a str, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Dependency<'a> { arguments: Vec, recipe: &'a str, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Interpreter<'a> { arguments: Vec<&'a str>, command: &'a str, } #[derive(Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct Module<'a> { aliases: BTreeMap<&'a str, Alias<'a>>, assignments: BTreeMap<&'a str, Assignment<'a>>, doc: Option<&'a str>, first: Option<&'a str>, groups: Vec<&'a str>, modules: BTreeMap<&'a str, Module<'a>>, recipes: BTreeMap<&'a str, Recipe<'a>>, settings: Settings<'a>, source: PathBuf, unexports: Vec<&'a str>, warnings: Vec<&'a str>, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Parameter<'a> { default: Option<&'a str>, export: bool, kind: &'a str, name: &'a str, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Recipe<'a> { attributes: Vec, body: Vec, dependencies: Vec>, doc: Option<&'a str>, name: &'a str, namepath: &'a str, parameters: Vec>, priors: u32, private: bool, quiet: bool, shebang: bool, } #[derive(Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct Settings<'a> { allow_duplicate_recipes: bool, allow_duplicate_variables: bool, dotenv_filename: Option<&'a str>, dotenv_load: bool, dotenv_path: Option<&'a str>, dotenv_required: bool, export: bool, fallback: bool, ignore_comments: bool, no_exit_message: bool, positional_arguments: bool, quiet: bool, shell: Option>, tempdir: Option<&'a str>, unstable: bool, windows_powershell: bool, windows_shell: Option<&'a str>, working_directory: Option<&'a str>, } #[track_caller] fn case(justfile: &str, expected: Module) { case_with_submodule(justfile, None, expected); } fn fix_source(dir: &Path, module: &mut Module) { let filename = if module.source.as_os_str().is_empty() { Path::new("justfile") } else { &module.source }; module.source = if cfg!(target_os = "macos") { dir.canonicalize().unwrap().join(filename) } else { dir.join(filename) }; for module in module.modules.values_mut() { fix_source(dir, module); } } #[track_caller] fn case_with_submodule(justfile: &str, submodule: Option<(&str, &str)>, mut expected: Module) { let mut test = Test::new() .justfile(justfile) .args(["--dump", "--dump-format", "json"]) .stdout_regex(".*"); if let Some((path, source)) = submodule { test = test.write(path, source); } fix_source(test.tempdir.path(), &mut expected); let actual = test.run().stdout; let actual: Module = serde_json::from_str(actual.as_str()).unwrap(); pretty_assertions::assert_eq!(actual, expected); } #[test] fn alias() { case( " alias f := foo foo: ", Module { aliases: [( "f", Alias { name: "f", target: "foo", ..default() }, )] .into(), first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", ..default() }, )] .into(), ..default() }, ); } #[test] fn assignment() { case( "foo := 'bar'", Module { assignments: [( "foo", Assignment { name: "foo", value: "bar", ..default() }, )] .into(), ..default() }, ); } #[test] fn private_assignment() { case( " _foo := 'foo' [private] bar := 'bar' ", Module { assignments: [ ( "_foo", Assignment { name: "_foo", value: "foo", private: true, ..default() }, ), ( "bar", Assignment { name: "bar", value: "bar", private: true, ..default() }, ), ] .into(), ..default() }, ); } #[test] fn body() { case( " foo: bar abc{{ 'xyz' }}def ", Module { first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", body: [json!(["bar"]), json!(["abc", ["xyz"], "def"])].into(), ..default() }, )] .into(), ..default() }, ); } #[test] fn dependencies() { case( " foo: bar: foo ", Module { first: Some("foo"), recipes: [ ( "foo", Recipe { name: "foo", namepath: "foo", ..default() }, ), ( "bar", Recipe { name: "bar", namepath: "bar", dependencies: [Dependency { recipe: "foo", ..default() }] .into(), priors: 1, ..default() }, ), ] .into(), ..default() }, ); } #[test] fn dependency_argument() { case( " x := 'foo' foo *args: bar: ( foo 'baz' ('baz') ('a' + 'b') `echo` x if 'a' == 'b' { 'c' } else { 'd' } arch() env_var('foo') join('a', 'b') replace('a', 'b', 'c') ) ", Module { assignments: [( "x", Assignment { name: "x", value: "foo", ..default() }, )] .into(), first: Some("foo"), recipes: [ ( "foo", Recipe { name: "foo", namepath: "foo", parameters: [Parameter { kind: "star", name: "args", ..default() }] .into(), ..default() }, ), ( "bar", Recipe { name: "bar", namepath: "bar", dependencies: [Dependency { recipe: "foo", arguments: [ json!("baz"), json!("baz"), json!(["concatenate", "a", "b"]), json!(["evaluate", "echo"]), json!(["variable", "x"]), json!(["if", ["==", "a", "b"], "c", "d"]), json!(["call", "arch"]), json!(["call", "env_var", "foo"]), json!(["call", "join", "a", "b"]), json!(["call", "replace", "a", "b", "c"]), ] .into(), }] .into(), priors: 1, ..default() }, ), ] .into(), ..default() }, ); } #[test] fn duplicate_recipes() { case( " set allow-duplicate-recipes alias f := foo foo: foo bar: ", Module { aliases: [( "f", Alias { name: "f", target: "foo", ..default() }, )] .into(), first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", parameters: [Parameter { kind: "singular", name: "bar", ..default() }] .into(), ..default() }, )] .into(), settings: Settings { allow_duplicate_recipes: true, ..default() }, ..default() }, ); } #[test] fn duplicate_variables() { case( " set allow-duplicate-variables x := 'foo' x := 'bar' ", Module { assignments: [( "x", Assignment { name: "x", value: "bar", ..default() }, )] .into(), settings: Settings { allow_duplicate_variables: true, ..default() }, ..default() }, ); } #[test] fn doc_comment() { case( "# hello\nfoo:", Module { first: Some("foo"), recipes: [( "foo", Recipe { doc: Some("hello"), name: "foo", namepath: "foo", ..default() }, )] .into(), ..default() }, ); } #[test] fn empty_justfile() { case("", Module::default()); } #[test] fn parameters() { case( " a: b x: c x='y': d +x: e *x: f $x: ", Module { first: Some("a"), recipes: [ ( "a", Recipe { name: "a", namepath: "a", ..default() }, ), ( "b", Recipe { name: "b", namepath: "b", parameters: [Parameter { kind: "singular", name: "x", ..default() }] .into(), ..default() }, ), ( "c", Recipe { name: "c", namepath: "c", parameters: [Parameter { default: Some("y"), kind: "singular", name: "x", ..default() }] .into(), ..default() }, ), ( "d", Recipe { name: "d", namepath: "d", parameters: [Parameter { kind: "plus", name: "x", ..default() }] .into(), ..default() }, ), ( "e", Recipe { name: "e", namepath: "e", parameters: [Parameter { kind: "star", name: "x", ..default() }] .into(), ..default() }, ), ( "f", Recipe { name: "f", namepath: "f", parameters: [Parameter { export: true, kind: "singular", name: "x", ..default() }] .into(), ..default() }, ), ] .into(), ..default() }, ); } #[test] fn priors() { case( " a: b: a && c c: ", Module { first: Some("a"), recipes: [ ( "a", Recipe { name: "a", namepath: "a", ..default() }, ), ( "b", Recipe { dependencies: [ Dependency { recipe: "a", ..default() }, Dependency { recipe: "c", ..default() }, ] .into(), name: "b", namepath: "b", priors: 1, ..default() }, ), ( "c", Recipe { name: "c", namepath: "c", ..default() }, ), ] .into(), ..default() }, ); } #[test] fn private() { case( "_foo:", Module { first: Some("_foo"), recipes: [( "_foo", Recipe { name: "_foo", namepath: "_foo", private: true, ..default() }, )] .into(), ..default() }, ); } #[test] fn quiet() { case( "@foo:", Module { first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", quiet: true, ..default() }, )] .into(), ..default() }, ); } #[test] fn settings() { case( " set allow-duplicate-recipes set dotenv-filename := \"filename\" set dotenv-load set dotenv-path := \"path\" set export set fallback set ignore-comments set positional-arguments set quiet set shell := ['a', 'b', 'c'] foo: #!bar ", Module { first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", shebang: true, body: [json!(["#!bar"])].into(), ..default() }, )] .into(), settings: Settings { allow_duplicate_recipes: true, dotenv_filename: Some("filename"), dotenv_path: Some("path"), dotenv_load: true, export: true, fallback: true, ignore_comments: true, positional_arguments: true, quiet: true, shell: Some(Interpreter { arguments: ["b", "c"].into(), command: "a", }), ..default() }, ..default() }, ); } #[test] fn shebang() { case( " foo: #!bar ", Module { first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", shebang: true, body: [json!(["#!bar"])].into(), ..default() }, )] .into(), ..default() }, ); } #[test] fn simple() { case( "foo:", Module { first: Some("foo"), recipes: [( "foo", Recipe { name: "foo", namepath: "foo", ..default() }, )] .into(), ..default() }, ); } #[test] fn attribute() { case( " [no-exit-message] foo: ", Module { first: Some("foo"), recipes: [( "foo", Recipe { attributes: [json!("no-exit-message")].into(), name: "foo", namepath: "foo", ..default() }, )] .into(), ..default() }, ); } #[test] fn module() { case_with_submodule( " # hello mod foo ", Some(("foo.just", "bar:")), Module { modules: [( "foo", Module { doc: Some("hello"), first: Some("bar"), source: "foo.just".into(), recipes: [( "bar", Recipe { name: "bar", namepath: "foo::bar", ..default() }, )] .into(), ..default() }, )] .into(), ..default() }, ); } #[test] fn module_group() { case_with_submodule( " [group('alpha')] mod foo ", Some(("foo.just", "bar:")), Module { modules: [( "foo", Module { first: Some("bar"), groups: ["alpha"].into(), source: "foo.just".into(), recipes: [( "bar", Recipe { name: "bar", namepath: "foo::bar", ..default() }, )] .into(), ..default() }, )] .into(), ..default() }, ); } #[test] fn recipes_with_private_attribute_are_private() { case( " [private] foo: ", Module { first: Some("foo"), recipes: [( "foo", Recipe { attributes: [json!("private")].into(), name: "foo", namepath: "foo", private: true, ..default() }, )] .into(), ..default() }, ); } #[test] fn doc_attribute_overrides_comment() { case( " # COMMENT [doc('ATTRIBUTE')] foo: ", Module { first: Some("foo"), recipes: [( "foo", Recipe { attributes: [json!({"doc": "ATTRIBUTE"})].into(), doc: Some("ATTRIBUTE"), name: "foo", namepath: "foo", ..default() }, )] .into(), ..default() }, ); } just-1.40.0/tests/lib.rs000064400000000000000000000046231046102023000131560ustar 00000000000000pub(crate) use { crate::{ assert_stdout::assert_stdout, assert_success::assert_success, tempdir::tempdir, test::{assert_eval_eq, Output, Test}, }, executable_path::executable_path, just::{unindent, Response}, libc::{EXIT_FAILURE, EXIT_SUCCESS}, pretty_assertions::Comparison, regex::Regex, serde::{Deserialize, Serialize}, serde_json::{json, Value}, std::{ collections::BTreeMap, env::{self, consts::EXE_SUFFIX}, error::Error, fmt::Debug, fs, io::Write, iter, path::{Path, PathBuf, MAIN_SEPARATOR, MAIN_SEPARATOR_STR}, process::{Command, Stdio}, str, }, tempfile::TempDir, temptree::{temptree, tree, Tree}, which::which, }; fn default() -> T { Default::default() } #[macro_use] mod test; mod alias; mod alias_style; mod allow_duplicate_recipes; mod allow_duplicate_variables; mod allow_missing; mod assert_stdout; mod assert_success; mod assertions; mod assignment; mod attributes; mod backticks; mod byte_order_mark; mod changelog; mod choose; mod command; mod completions; mod conditional; mod confirm; mod constants; mod datetime; mod delimiters; mod directories; mod dotenv; mod edit; mod equals; mod error_messages; mod evaluate; mod examples; mod explain; mod export; mod fallback; mod format; mod functions; #[cfg(unix)] mod global; mod groups; mod ignore_comments; mod imports; mod init; #[cfg(unix)] mod interrupts; mod invocation_directory; mod json; mod line_prefixes; mod list; mod logical_operators; mod man; mod misc; mod modules; mod multibyte_char; mod newline_escape; mod no_aliases; mod no_cd; mod no_dependencies; mod no_exit_message; mod os_attributes; mod parameters; mod parser; mod positional_arguments; mod private; mod quiet; mod quote; mod readme; mod recursion_limit; mod regexes; mod request; mod run; mod script; mod search; mod search_arguments; mod shadowing_parameters; mod shebang; mod shell; mod shell_expansion; mod show; mod slash_operator; mod string; mod subsequents; mod summary; mod tempdir; mod timestamps; mod undefined_variables; mod unexport; mod unstable; mod which_function; #[cfg(windows)] mod windows; #[cfg(target_family = "windows")] mod windows_shell; mod working_directory; fn path(s: &str) -> String { if cfg!(windows) { s.replace('/', "\\") } else { s.into() } } fn path_for_regex(s: &str) -> String { if cfg!(windows) { s.replace('/', "\\\\") } else { s.into() } } just-1.40.0/tests/line_prefixes.rs000064400000000000000000000004401046102023000152350ustar 00000000000000use super::*; #[test] fn infallible_after_quiet() { Test::new() .justfile( " foo: @-exit 1 ", ) .run(); } #[test] fn quiet_after_infallible() { Test::new() .justfile( " foo: -@exit 1 ", ) .run(); } just-1.40.0/tests/list.rs000064400000000000000000000174671046102023000133750ustar 00000000000000use super::*; #[test] fn modules_unsorted() { Test::new() .write("foo.just", "foo:") .write("bar.just", "bar:") .justfile( " mod foo mod bar ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: foo ... bar ... ", ) .run(); } #[test] fn unsorted_list_order() { Test::new() .write("a.just", "a:") .write("b.just", "b:") .write("c.just", "c:") .write("d.just", "d:") .justfile( " import 'a.just' import 'b.just' import 'c.just' import 'd.just' x: y: z: ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: x y z a b c d ", ) .run(); Test::new() .write("a.just", "a:") .write("b.just", "b:") .write("c.just", "c:") .write("d.just", "d:") .justfile( " x: y: z: import 'd.just' import 'c.just' import 'b.just' import 'a.just' ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: x y z d c b a ", ) .run(); Test::new() .write("a.just", "a:\nimport 'e.just'") .write("b.just", "b:\nimport 'f.just'") .write("c.just", "c:\nimport 'g.just'") .write("d.just", "d:\nimport 'h.just'") .write("e.just", "e:") .write("f.just", "f:") .write("g.just", "g:") .write("h.just", "h:") .justfile( " x: y: z: import 'd.just' import 'c.just' import 'b.just' import 'a.just' ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: x y z d h c g b f a e ", ) .run(); Test::new() .write("task1.just", "task1:") .write("task2.just", "task2:") .justfile( " import 'task1.just' import 'task2.just' ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: task1 task2 ", ) .run(); } #[test] fn list_submodule() { Test::new() .write("foo.just", "bar:") .justfile( " mod foo ", ) .args(["--list", "foo"]) .stdout( " Available recipes: bar ", ) .run(); } #[test] fn list_nested_submodule() { Test::new() .write("foo.just", "mod bar") .write("bar.just", "baz:") .justfile( " mod foo ", ) .args(["--list", "foo", "bar"]) .stdout( " Available recipes: baz ", ) .run(); Test::new() .write("foo.just", "mod bar") .write("bar.just", "baz:") .justfile( " mod foo ", ) .args(["--list", "foo::bar"]) .stdout( " Available recipes: baz ", ) .run(); } #[test] fn list_invalid_path() { Test::new() .args(["--list", "$hello"]) .stderr("error: Invalid module path `$hello`\n") .status(1) .run(); } #[test] fn list_unknown_submodule() { Test::new() .args(["--list", "hello"]) .stderr("error: Justfile does not contain submodule `hello`\n") .status(1) .run(); } #[test] fn list_with_groups_in_modules() { Test::new() .justfile( " [group('FOO')] foo: mod bar ", ) .write("bar.just", "[group('BAZ')]\nbaz:") .args(["--list", "--list-submodules"]) .stdout( " Available recipes: bar: [BAZ] baz [FOO] foo ", ) .run(); } #[test] fn list_displays_recipes_in_submodules() { Test::new() .write("foo.just", "bar:\n @echo FOO") .justfile( " mod foo ", ) .args(["--list", "--list-submodules"]) .stdout( " Available recipes: foo: bar ", ) .run(); } #[test] fn modules_are_space_separated_in_output() { Test::new() .write("foo.just", "foo:") .write("bar.just", "bar:") .justfile( " mod foo mod bar ", ) .args(["--list", "--list-submodules"]) .stdout( " Available recipes: bar: bar foo: foo ", ) .run(); } #[test] fn module_recipe_list_alignment_ignores_private_recipes() { Test::new() .write( "foo.just", " # foos foo: @echo FOO [private] barbarbar: @echo BAR @_bazbazbaz: @echo BAZ ", ) .justfile("mod foo") .args(["--list", "--list-submodules"]) .stdout( " Available recipes: foo: foo # foos ", ) .run(); } #[test] fn nested_modules_are_properly_indented() { Test::new() .write("foo.just", "mod bar") .write("bar.just", "baz:\n @echo FOO") .justfile( " mod foo ", ) .args(["--list", "--list-submodules"]) .stdout( " Available recipes: foo: bar: baz ", ) .run(); } #[test] fn module_doc_rendered() { Test::new() .write("foo.just", "") .justfile( " # Module foo mod foo ", ) .args(["--list"]) .stdout( " Available recipes: foo ... # Module foo ", ) .run(); } #[test] fn module_doc_aligned() { Test::new() .write("foo.just", "") .write("bar.just", "") .justfile( " # Module foo mod foo # comment mod very_long_name_for_module \"bar.just\" # comment # will change your world recipe: @echo Hi ", ) .args(["--list"]) .stdout( " Available recipes: recipe # will change your world foo ... # Module foo very_long_name_for_module ... # comment ", ) .run(); } #[test] fn submodules_without_groups() { Test::new() .write("foo.just", "") .justfile( " mod foo [group: 'baz'] bar: ", ) .args(["--list"]) .stdout( " Available recipes: foo ... [baz] bar ", ) .run(); } #[test] fn no_space_before_submodules_not_following_groups() { Test::new() .write("foo.just", "") .justfile( " mod foo ", ) .args(["--list"]) .stdout( " Available recipes: foo ... ", ) .run(); } #[test] fn backticks_highlighted() { Test::new() .justfile( " # Comment `` `with backticks` and trailing text recipe: ", ) .args(["--list", "--color=always"]) .stdout( " Available recipes: recipe \u{1b}[34m#\u{1b}[0m \u{1b}[34mComment \u{1b}[0m\u{1b}[36m``\u{1b}[0m\u{1b}[34m \u{1b}[0m\u{1b}[36m`with backticks`\u{1b}[0m\u{1b}[34m and trailing text\u{1b}[0m ") .run(); } #[test] fn unclosed_backticks() { Test::new() .justfile( " # Comment `with unclosed backick recipe: ", ) .args(["--list", "--color=always"]) .stdout( " Available recipes: recipe \u{1b}[34m#\u{1b}[0m \u{1b}[34mComment \u{1b}[0m\u{1b}[36m`with unclosed backick\u{1b}[0m ") .run(); } #[test] fn list_submodules_requires_list() { Test::new() .arg("--list-submodules") .stderr_regex("error: the following required arguments were not provided:\n --list .*") .status(2) .run(); } just-1.40.0/tests/logical_operators.rs000064400000000000000000000036431046102023000161210ustar 00000000000000use super::*; #[track_caller] fn evaluate(expression: &str, expected: &str) { Test::new() .justfile(format!("x := {expression}")) .env("JUST_UNSTABLE", "1") .args(["--evaluate", "x"]) .stdout(expected) .run(); } #[test] fn logical_operators_are_unstable() { Test::new() .justfile("x := 'foo' && 'bar'") .args(["--evaluate", "x"]) .stderr_regex(r"error: The logical operators `&&` and `\|\|` are currently unstable. .*") .status(EXIT_FAILURE) .run(); Test::new() .justfile("x := 'foo' || 'bar'") .args(["--evaluate", "x"]) .stderr_regex(r"error: The logical operators `&&` and `\|\|` are currently unstable. .*") .status(EXIT_FAILURE) .run(); } #[test] fn and_returns_empty_string_if_lhs_is_empty() { evaluate("'' && 'hello'", ""); } #[test] fn and_returns_rhs_if_lhs_is_non_empty() { evaluate("'hello' && 'goodbye'", "goodbye"); } #[test] fn and_has_lower_precedence_than_plus() { evaluate("'' && 'goodbye' + 'foo'", ""); evaluate("'foo' + 'hello' && 'goodbye'", "goodbye"); evaluate("'foo' + '' && 'goodbye'", "goodbye"); evaluate("'foo' + 'hello' && 'goodbye' + 'bar'", "goodbyebar"); } #[test] fn or_returns_rhs_if_lhs_is_empty() { evaluate("'' || 'hello'", "hello"); } #[test] fn or_returns_lhs_if_lhs_is_non_empty() { evaluate("'hello' || 'goodbye'", "hello"); } #[test] fn or_has_lower_precedence_than_plus() { evaluate("'' || 'goodbye' + 'foo'", "goodbyefoo"); evaluate("'foo' + 'hello' || 'goodbye'", "foohello"); evaluate("'foo' + '' || 'goodbye'", "foo"); evaluate("'foo' + 'hello' || 'goodbye' + 'bar'", "foohello"); } #[test] fn and_has_higher_precedence_than_or() { evaluate("('' && 'foo') || 'bar'", "bar"); evaluate("'' && 'foo' || 'bar'", "bar"); evaluate("'a' && 'b' || 'c'", "b"); } #[test] fn nesting() { evaluate("'' || '' || '' || '' || 'foo'", "foo"); evaluate("'foo' && 'foo' && 'foo' && 'foo' && 'bar'", "bar"); } just-1.40.0/tests/man.rs000064400000000000000000000001731046102023000131570ustar 00000000000000use super::*; #[test] fn output() { Test::new() .arg("--man") .stdout_regex("(?s).*.TH just 1.*") .run(); } just-1.40.0/tests/misc.rs000064400000000000000000001246551046102023000133530ustar 00000000000000use super::*; #[test] fn alias_listing() { Test::new() .arg("--list") .justfile( " foo: echo foo alias f := foo ", ) .stdout( " Available recipes: foo # [alias: f] ", ) .run(); } #[test] fn alias_listing_with_doc() { Test::new() .justfile( " # foo command foo: echo foo alias f := foo ", ) .arg("--list") .stdout( " Available recipes: foo # foo command [alias: f] ", ) .run(); } #[test] fn alias_listing_multiple_aliases() { Test::new() .arg("--list") .justfile("foo:\n echo foo\nalias f := foo\nalias fo := foo") .stdout( " Available recipes: foo # [aliases: f, fo] ", ) .run(); } #[test] fn alias_listing_parameters() { Test::new() .args(["--list"]) .justfile("foo PARAM='foo':\n echo {{PARAM}}\nalias f := foo") .stdout( " Available recipes: foo PARAM='foo' # [alias: f] ", ) .run(); } #[test] fn alias_listing_private() { Test::new() .arg("--list") .justfile("foo PARAM='foo':\n echo {{PARAM}}\nalias _f := foo") .stdout( " Available recipes: foo PARAM='foo' ", ) .run(); } #[test] fn alias() { Test::new() .arg("f") .justfile("foo:\n echo foo\nalias f := foo") .stdout("foo\n") .stderr("echo foo\n") .run(); } #[test] fn alias_with_parameters() { Test::new() .arg("f") .arg("bar") .justfile("foo value='foo':\n echo {{value}}\nalias f := foo") .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn bad_setting() { Test::new() .justfile( " set foo ", ) .stderr( " error: Unknown setting `foo` ——▶ justfile:1:5 │ 1 │ set foo │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn bad_setting_with_keyword_name() { Test::new() .justfile( " set if := 'foo' ", ) .stderr( " error: Unknown setting `if` ——▶ justfile:1:5 │ 1 │ set if := 'foo' │ ^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn alias_with_dependencies() { Test::new() .arg("b") .justfile("foo:\n echo foo\nbar: foo\nalias b := bar") .stdout("foo\n") .stderr("echo foo\n") .run(); } #[test] fn duplicate_alias() { Test::new() .justfile("alias foo := bar\nalias foo := baz\n") .stderr( " error: Alias `foo` first defined on line 1 is redefined on line 2 ——▶ justfile:2:7 │ 2 │ alias foo := baz │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_alias_target() { Test::new() .justfile("alias foo := bar\n") .stderr( " error: Alias `foo` has an unknown target `bar` ——▶ justfile:1:7 │ 1 │ alias foo := bar │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn alias_shadows_recipe() { Test::new() .justfile("bar:\n echo bar\nalias foo := bar\nfoo:\n echo foo") .stderr( " error: Alias `foo` defined on line 3 is redefined as a recipe on line 4 ——▶ justfile:4:1 │ 4 │ foo: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn default() { Test::new() .justfile("default:\n echo hello\nother: \n echo bar") .stdout("hello\n") .stderr("echo hello\n") .run(); } #[test] fn quiet() { Test::new() .justfile("default:\n @echo hello") .stdout("hello\n") .run(); } #[test] fn verbose() { Test::new() .arg("--verbose") .justfile("default:\n @echo hello") .stdout("hello\n") .stderr("===> Running recipe `default`...\necho hello\n") .run(); } #[test] fn order() { Test::new() .arg("a") .arg("d") .justfile( " b: a echo b @mv a b a: echo a @touch F @touch a d: c echo d @rm c c: b echo c @mv b c", ) .stdout("a\nb\nc\nd\n") .stderr("echo a\necho b\necho c\necho d\n") .run(); } #[test] fn select() { Test::new() .arg("d") .arg("c") .justfile("b:\n @echo b\na:\n @echo a\nd:\n @echo d\nc:\n @echo c") .stdout("d\nc\n") .run(); } #[test] fn print() { Test::new() .arg("d") .arg("c") .justfile("b:\n echo b\na:\n echo a\nd:\n echo d\nc:\n echo c") .stdout("d\nc\n") .stderr("echo d\necho c\n") .run(); } #[test] fn status_passthrough() { Test::new() .arg("recipe") .justfile( " hello: recipe: @exit 100", ) .stderr("error: Recipe `recipe` failed on line 5 with exit code 100\n") .status(100) .run(); } #[test] fn unknown_dependency() { Test::new() .justfile("bar:\nhello:\nfoo: bar baaaaaaaz hello") .stderr( " error: Recipe `foo` has unknown dependency `baaaaaaaz` ——▶ justfile:3:10 │ 3 │ foo: bar baaaaaaaz hello │ ^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn backtick_success() { Test::new() .justfile("a := `printf Hello,`\nbar:\n printf '{{a + `printf ' world.'`}}'") .stdout("Hello, world.") .stderr("printf 'Hello, world.'\n") .run(); } #[test] fn backtick_trimming() { Test::new() .justfile("a := `echo Hello,`\nbar:\n echo '{{a + `echo ' world.'`}}'") .stdout("Hello, world.\n") .stderr("echo 'Hello, world.'\n") .run(); } #[test] fn backtick_code_assignment() { Test::new() .justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'") .stderr( " error: Backtick failed with exit code 100 ——▶ justfile:2:6 │ 2 │ a := `exit 100` │ ^^^^^^^^^^ ", ) .status(100) .run(); } #[test] fn backtick_code_interpolation() { Test::new() .justfile("b := a\na := `echo hello`\nbar:\n echo '{{`exit 200`}}'") .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:4:10 │ 4 │ echo '{{`exit 200`}}' │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_mod() { Test::new() .justfile("f:\n 無{{`exit 200`}}") .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:2:7 │ 2 │ 無{{`exit 200`}} │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_tab() { Test::new() .justfile( " backtick-fail: \techo {{`exit 200`}} ", ) .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:2:9 │ 2 │ echo {{`exit 200`}} │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_tabs() { Test::new() .justfile( " backtick-fail: \techo {{\t`exit 200`}} ", ) .stderr( "error: Backtick failed with exit code 200 ——▶ justfile:2:10 │ 2 │ echo {{ `exit 200`}} │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_inner_tab() { Test::new() .justfile( " backtick-fail: \techo {{\t`exit\t\t200`}} ", ) .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:2:10 │ 2 │ echo {{ `exit 200`}} │ ^^^^^^^^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_leading_emoji() { Test::new() .justfile( " backtick-fail: \techo 😬{{`exit 200`}} ", ) .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:2:13 │ 2 │ echo 😬{{`exit 200`}} │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_interpolation_unicode_hell() { Test::new() .justfile( " backtick-fail: \techo \t\t\t😬鎌鼬{{\t\t`exit 200 # \t\t\tabc`}}\t\t\t😬鎌鼬 ", ) .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:2:24 │ 2 │ echo 😬鎌鼬{{ `exit 200 # abc`}} 😬鎌鼬 │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn backtick_code_long() { Test::new() .justfile( " b := a a := `echo hello` bar: echo '{{`exit 200`}}' ", ) .stderr( " error: Backtick failed with exit code 200 ——▶ justfile:10:10 │ 10 │ echo '{{`exit 200`}}' │ ^^^^^^^^^^ ", ) .status(200) .run(); } #[test] fn shebang_backtick_failure() { Test::new() .justfile( "foo: #!/bin/sh echo hello echo {{`exit 123`}}", ) .stderr( " error: Backtick failed with exit code 123 ——▶ justfile:4:9 │ 4 │ echo {{`exit 123`}} │ ^^^^^^^^^^ ", ) .status(123) .run(); } #[test] fn command_backtick_failure() { Test::new() .justfile( "foo: echo hello echo {{`exit 123`}}", ) .stdout("hello\n") .stderr( " echo hello error: Backtick failed with exit code 123 ——▶ justfile:3:9 │ 3 │ echo {{`exit 123`}} │ ^^^^^^^^^^ ", ) .status(123) .run(); } #[test] fn assignment_backtick_failure() { Test::new() .justfile( "foo: echo hello echo {{`exit 111`}} a := `exit 222`", ) .stderr( " error: Backtick failed with exit code 222 ——▶ justfile:4:6 │ 4 │ a := `exit 222` │ ^^^^^^^^^^ ", ) .status(222) .run(); } #[test] fn unknown_override_options() { Test::new() .arg("--set") .arg("foo") .arg("bar") .arg("--set") .arg("baz") .arg("bob") .arg("--set") .arg("a") .arg("b") .arg("a") .arg("b") .justfile( "foo: echo hello echo {{`exit 111`}} a := `exit 222`", ) .status(EXIT_FAILURE) .stderr( "error: Variables `baz` and `foo` overridden on the command line but not present \ in justfile\n", ) .run(); } #[test] fn unknown_override_args() { Test::new() .arg("foo=bar") .arg("baz=bob") .arg("a=b") .arg("a") .arg("b") .justfile( "foo: echo hello echo {{`exit 111`}} a := `exit 222`", ) .stderr( "error: Variables `baz` and `foo` overridden on the command line but not present \ in justfile\n", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_override_arg() { Test::new() .arg("foo=bar") .arg("a=b") .arg("a") .arg("b") .justfile( "foo: echo hello echo {{`exit 111`}} a := `exit 222`", ) .stderr("error: Variable `foo` overridden on the command line but not present in justfile\n") .status(EXIT_FAILURE) .run(); } #[test] fn overrides_first() { Test::new() .arg("foo=bar") .arg("a=b") .arg("recipe") .arg("baz=bar") .justfile( r#" foo := "foo" a := "a" baz := "baz" recipe arg: echo arg={{arg}} echo {{foo + a + baz}}"#, ) .stdout("arg=baz=bar\nbarbbaz\n") .stderr("echo arg=baz=bar\necho barbbaz\n") .run(); } #[test] fn overrides_not_evaluated() { Test::new() .arg("foo=bar") .arg("a=b") .arg("recipe") .arg("baz=bar") .justfile( r#" foo := `exit 1` a := "a" baz := "baz" recipe arg: echo arg={{arg}} echo {{foo + a + baz}}"#, ) .stdout("arg=baz=bar\nbarbbaz\n") .stderr("echo arg=baz=bar\necho barbbaz\n") .run(); } #[test] fn dry_run() { Test::new() .arg("--dry-run") .arg("shebang") .arg("command") .justfile( r" var := `echo stderr 1>&2; echo backtick` command: @touch /this/is/not/a/file {{var}} echo {{`echo command interpolation`}} shebang: #!/bin/sh touch /this/is/not/a/file {{var}} echo {{`echo shebang interpolation`}}", ) .stderr( "#!/bin/sh touch /this/is/not/a/file `echo stderr 1>&2; echo backtick` echo `echo shebang interpolation` touch /this/is/not/a/file `echo stderr 1>&2; echo backtick` echo `echo command interpolation` ", ) .run(); } #[test] fn line_error_spacing() { Test::new() .justfile( r" ^^^ ", ) .stderr( "error: Unknown start of token '^' ——▶ justfile:10:1 │ 10 │ ^^^ │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn argument_single() { Test::new() .arg("foo") .arg("ARGUMENT") .justfile( " foo A: echo {{A}} ", ) .stdout("ARGUMENT\n") .stderr("echo ARGUMENT\n") .run(); } #[test] fn argument_multiple() { Test::new() .arg("foo") .arg("ONE") .arg("TWO") .justfile( " foo A B: echo A:{{A}} B:{{B}} ", ) .stdout("A:ONE B:TWO\n") .stderr("echo A:ONE B:TWO\n") .run(); } #[test] fn argument_mismatch_more() { Test::new() .arg("foo") .arg("ONE") .arg("TWO") .arg("THREE") .stderr("error: Justfile does not contain recipe `THREE`\n") .status(EXIT_FAILURE) .justfile( " foo A B: echo A:{{A}} B:{{B}} ", ) .run(); } #[test] fn argument_mismatch_fewer() { Test::new() .arg("foo") .arg("ONE") .justfile( " foo A B: echo A:{{A}} B:{{B}} ", ) .stderr("error: Recipe `foo` got 1 argument but takes 2\nusage:\n just foo A B\n") .status(EXIT_FAILURE) .run(); } #[test] fn argument_mismatch_more_with_default() { Test::new() .arg("foo") .arg("ONE") .arg("TWO") .arg("THREE") .justfile( " foo A B='B': echo A:{{A}} B:{{B}} ", ) .stderr("error: Justfile does not contain recipe `THREE`\n") .status(EXIT_FAILURE) .run(); } #[test] fn argument_mismatch_fewer_with_default() { Test::new() .arg("foo") .arg("bar") .justfile( " foo A B C='C': echo A:{{A}} B:{{B}} C:{{C}} ", ) .stderr( " error: Recipe `foo` got 1 argument but takes at least 2 usage: just foo A B C='C' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_recipe() { Test::new() .arg("foo") .justfile("hello:") .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn unknown_recipes() { Test::new() .arg("foo") .arg("bar") .justfile("hello:") .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn color_always() { Test::new() .arg("--color") .arg("always") .justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'") .status(100) .stderr("\u{1b}[1;31merror\u{1b}[0m: \u{1b}[1mBacktick failed with exit code 100\u{1b}[0m\n \u{1b}[1;34m——▶\u{1b}[0m justfile:2:6\n \u{1b}[1;34m│\u{1b}[0m\n\u{1b}[1;34m2 │\u{1b}[0m a := `exit 100`\n \u{1b}[1;34m│\u{1b}[0m \u{1b}[1;31m^^^^^^^^^^\u{1b}[0m\n") .run(); } #[test] fn color_never() { Test::new() .arg("--color") .arg("never") .justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'") .stderr( "error: Backtick failed with exit code 100 ——▶ justfile:2:6 │ 2 │ a := `exit 100` │ ^^^^^^^^^^ ", ) .status(100) .run(); } #[test] fn color_auto() { Test::new() .arg("--color") .arg("auto") .justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'") .stderr( "error: Backtick failed with exit code 100 ——▶ justfile:2:6 │ 2 │ a := `exit 100` │ ^^^^^^^^^^ ", ) .status(100) .run(); } #[test] fn colors_no_context() { Test::new() .arg("--color=always") .stderr( "\u{1b}[1;31merror\u{1b}[0m: \u{1b}[1m\ Recipe `recipe` failed on line 2 with exit code 100\u{1b}[0m\n", ) .status(100) .justfile( " recipe: @exit 100", ) .run(); } #[test] fn dump() { Test::new() .arg("--dump") .justfile( r" # this recipe does something recipe a b +d: @exit 100", ) .stdout( "# this recipe does something recipe a b +d: @exit 100 ", ) .run(); } #[test] fn mixed_whitespace() { Test::new() .justfile("bar:\n\t echo hello") .stderr( "error: Found a mix of tabs and spaces in leading whitespace: `␉␠` Leading whitespace may consist of tabs or spaces, but not both ——▶ justfile:2:1 │ 2 │ echo hello │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn extra_leading_whitespace() { Test::new() .justfile("bar:\n\t\techo hello\n\t\t\techo goodbye") .stderr( "error: Recipe line has extra leading whitespace ——▶ justfile:3:3 │ 3 │ echo goodbye │ ^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn inconsistent_leading_whitespace() { Test::new() .justfile("bar:\n\t\techo hello\n\t echo goodbye") .stderr( "error: Recipe line has inconsistent leading whitespace. \ Recipe started with `␉␉` but found line with `␉␠` ——▶ justfile:3:1 │ 3 │ echo goodbye │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn required_after_default() { Test::new() .justfile("bar:\nhello baz arg='foo' bar:") .stderr( "error: Non-default parameter `bar` follows default parameter ——▶ justfile:2:21 │ 2 │ hello baz arg='foo' bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn required_after_plus_variadic() { Test::new() .justfile("bar:\nhello baz +arg bar:") .stderr( "error: Parameter `bar` follows variadic parameter ——▶ justfile:2:16 │ 2 │ hello baz +arg bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn required_after_star_variadic() { Test::new() .justfile("bar:\nhello baz *arg bar:") .stderr( "error: Parameter `bar` follows variadic parameter ——▶ justfile:2:16 │ 2 │ hello baz *arg bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn use_string_default() { Test::new() .arg("hello") .arg("ABC") .justfile( r#" bar: hello baz arg="XYZ\t\" ": echo '{{baz}}...{{arg}}' "#, ) .stdout("ABC...XYZ\t\"\t\n") .stderr("echo 'ABC...XYZ\t\"\t'\n") .run(); } #[test] fn use_raw_string_default() { Test::new() .arg("hello") .arg("ABC") .justfile( r#" bar: hello baz arg='XYZ" ': printf '{{baz}}...{{arg}}' "#, ) .stdout("ABC...XYZ\"\t") .stderr("printf 'ABC...XYZ\"\t'\n") .run(); } #[test] fn supply_use_default() { Test::new() .arg("hello") .arg("0") .arg("1") .justfile( r" hello a b='B' c='C': echo {{a}} {{b}} {{c}} ", ) .stdout("0 1 C\n") .stderr("echo 0 1 C\n") .run(); } #[test] fn supply_defaults() { Test::new() .arg("hello") .arg("0") .arg("1") .arg("2") .justfile( r" hello a b='B' c='C': echo {{a}} {{b}} {{c}} ", ) .stdout("0 1 2\n") .stderr("echo 0 1 2\n") .run(); } #[test] fn list() { Test::new() .arg("--list") .justfile( r#" # this does a thing hello a b='B ' c='C': echo {{a}} {{b}} {{c}} # this comment will be ignored a Z="\t z": # this recipe will not appear _private-recipe: "#, ) .stdout( r#" Available recipes: a Z="\t z" hello a b='B ' c='C' # this does a thing "#, ) .run(); } #[test] fn list_alignment() { Test::new() .arg("--list") .justfile( r#" # this does a thing hello a b='B ' c='C': echo {{a}} {{b}} {{c}} # something else a Z="\t z": # this recipe will not appear _private-recipe: "#, ) .stdout( r#" Available recipes: a Z="\t z" # something else hello a b='B ' c='C' # this does a thing "#, ) .run(); } #[test] fn list_alignment_long() { Test::new() .arg("--list") .justfile( r#" # this does a thing hello a b='B ' c='C': echo {{a}} {{b}} {{c}} # this does another thing x a b='B ' c='C': echo {{a}} {{b}} {{c}} # something else this-recipe-is-very-very-very-very-very-very-very-very-important Z="\t z": # this recipe will not appear _private-recipe: "#, ) .stdout( r#" Available recipes: hello a b='B ' c='C' # this does a thing this-recipe-is-very-very-very-very-very-very-very-very-important Z="\t z" # something else x a b='B ' c='C' # this does another thing "#, ) .run(); } #[test] fn list_sorted() { Test::new() .arg("--list") .justfile( r" alias c := b b: a: ", ) .stdout( r" Available recipes: a b # [alias: c] ", ) .run(); } #[test] fn list_unsorted() { Test::new() .arg("--list") .arg("--unsorted") .justfile( r" alias c := b b: a: ", ) .stdout( r" Available recipes: b # [alias: c] a ", ) .run(); } #[test] fn list_heading() { Test::new() .arg("--list") .arg("--list-heading") .arg("Cool stuff…\n") .justfile( r" a: b: ", ) .stdout( r" Cool stuff… a b ", ) .run(); } #[test] fn list_prefix() { Test::new() .arg("--list") .arg("--list-prefix") .arg("····") .justfile( r" a: b: ", ) .stdout( r" Available recipes: ····a ····b ", ) .run(); } #[test] fn list_empty_prefix_and_heading() { Test::new() .arg("--list") .arg("--list-heading") .arg("") .arg("--list-prefix") .arg("") .justfile( r" a: b: ", ) .stdout( r" a b ", ) .run(); } #[test] fn run_suggestion() { Test::new() .arg("hell") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `hell`\nDid you mean `hello`?\n") .status(EXIT_FAILURE) .run(); } #[test] fn line_continuation_with_space() { Test::new() .justfile( r" foo: echo a\ b \ c ", ) .stdout("ab c\n") .stderr("echo ab c\n") .run(); } #[test] fn line_continuation_with_quoted_space() { Test::new() .justfile( r" foo: echo 'a\ b \ c' ", ) .stdout("ab c\n") .stderr("echo 'ab c'\n") .run(); } #[test] fn line_continuation_no_space() { Test::new() .justfile( r" foo: echo a\ b\ c ", ) .stdout("abc\n") .stderr("echo abc\n") .run(); } #[test] fn infallible_command() { Test::new() .justfile( r" infallible: -exit 101 ", ) .stderr("exit 101\n") .status(EXIT_SUCCESS) .run(); } #[test] fn infallible_with_failing() { Test::new() .justfile( r" infallible: -exit 101 exit 202 ", ) .stderr( r"exit 101 exit 202 error: Recipe `infallible` failed on line 3 with exit code 202 ", ) .status(202) .run(); } #[test] fn quiet_recipe() { Test::new() .justfile( r" @quiet: # a # b @echo c ", ) .stdout("c\n") .stderr("echo c\n") .run(); } #[test] fn quiet_shebang_recipe() { Test::new() .justfile( r" @quiet: #!/bin/sh echo hello ", ) .stdout("hello\n") .stderr("#!/bin/sh\necho hello\n") .run(); } #[test] fn complex_dependencies() { Test::new() .arg("b") .justfile( r" a: b b: c: b a ", ) .run(); } #[test] fn unknown_function_in_assignment() { Test::new() .arg("bar") .justfile( r#"foo := foo() + "hello" bar:"#, ) .stderr( r#"error: Call to unknown function `foo` ——▶ justfile:1:8 │ 1 │ foo := foo() + "hello" │ ^^^ "#, ) .status(EXIT_FAILURE) .run(); } #[test] fn dependency_takes_arguments_exact() { Test::new() .arg("b") .justfile( " a FOO: b: a ", ) .stderr( "error: Dependency `a` got 0 arguments but takes 1 argument ——▶ justfile:2:4 │ 2 │ b: a │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dependency_takes_arguments_at_least() { Test::new() .arg("b") .justfile( " a FOO LUZ='hello': b: a ", ) .stderr( "error: Dependency `a` got 0 arguments but takes at least 1 argument ——▶ justfile:2:4 │ 2 │ b: a │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dependency_takes_arguments_at_most() { Test::new() .arg("b") .justfile( " a FOO LUZ='hello': b: (a '0' '1' '2') ", ) .stderr( "error: Dependency `a` got 3 arguments but takes at most 2 arguments ——▶ justfile:2:5 │ 2 │ b: (a '0' '1' '2') │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_parameter() { Test::new() .arg("a") .justfile("a foo foo:") .stderr( "error: Recipe `a` has duplicate parameter `foo` ——▶ justfile:1:7 │ 1 │ a foo foo: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_recipe() { Test::new() .arg("b") .justfile("b:\nb:") .stderr( "error: Recipe `b` first defined on line 1 is redefined on line 2 ——▶ justfile:2:1 │ 2 │ b: │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_variable() { Test::new() .arg("foo") .justfile("a := 'hello'\na := 'hello'\nfoo:") .status(EXIT_FAILURE) .stderr( "error: Variable `a` has multiple definitions ——▶ justfile:2:1 │ 2 │ a := 'hello' │ ^ ", ) .run(); } #[test] fn unexpected_token_in_dependency_position() { Test::new() .arg("foo") .justfile("foo: 'bar'") .stderr( "error: Expected '&&', comment, end of file, end of line, \ identifier, or '(', but found string ——▶ justfile:1:6 │ 1 │ foo: 'bar' │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unexpected_token_after_name() { Test::new() .arg("foo") .justfile("foo 'bar'") .stderr( "error: Expected '*', ':', '$', identifier, or '+', but found string ——▶ justfile:1:5 │ 1 │ foo 'bar' │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn self_dependency() { Test::new() .arg("a") .justfile("a: a") .stderr( "error: Recipe `a` depends on itself ——▶ justfile:1:4 │ 1 │ a: a │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn long_circular_recipe_dependency() { Test::new() .arg("a") .justfile("a: b\nb: c\nc: d\nd: a") .stderr( "error: Recipe `d` has circular dependency `a -> b -> c -> d -> a` ——▶ justfile:4:4 │ 4 │ d: a │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn variable_self_dependency() { Test::new() .arg("a") .justfile("z := z\na:") .stderr( "error: Variable `z` is defined in terms of itself ——▶ justfile:1:1 │ 1 │ z := z │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn variable_circular_dependency() { Test::new() .arg("a") .justfile("x := y\ny := z\nz := x\na:") .status(EXIT_FAILURE) .stderr( "error: Variable `x` depends on its own value: `x -> y -> z -> x` ——▶ justfile:1:1 │ 1 │ x := y │ ^ ", ) .run(); } #[test] fn variable_circular_dependency_with_additional_variable() { Test::new() .arg("a") .justfile( " a := '' x := y y := x a: ", ) .stderr( "error: Variable `x` depends on its own value: `x -> y -> x` ——▶ justfile:2:1 │ 2 │ x := y │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn plus_variadic_recipe() { Test::new() .arg("a") .arg("0") .arg("1") .arg("2") .arg("3") .arg(" 4 ") .justfile( " a x y +z: echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 2 3 4\n") .stderr("echo 0 1 2 3 4 \n") .run(); } #[test] fn plus_variadic_ignore_default() { Test::new() .arg("a") .arg("0") .arg("1") .arg("2") .arg("3") .arg(" 4 ") .justfile( " a x y +z='HELLO': echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 2 3 4\n") .stderr("echo 0 1 2 3 4 \n") .run(); } #[test] fn plus_variadic_use_default() { Test::new() .arg("a") .arg("0") .arg("1") .justfile( " a x y +z='HELLO': echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 HELLO\n") .stderr("echo 0 1 HELLO\n") .run(); } #[test] fn plus_variadic_too_few() { Test::new() .arg("a") .arg("0") .arg("1") .justfile( " a x y +z: echo {{x}} {{y}} {{z}} ", ) .stderr("error: Recipe `a` got 2 arguments but takes at least 3\nusage:\n just a x y +z\n") .status(EXIT_FAILURE) .run(); } #[test] fn star_variadic_recipe() { Test::new() .arg("a") .arg("0") .arg("1") .arg("2") .arg("3") .arg(" 4 ") .justfile( " a x y *z: echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 2 3 4\n") .stderr("echo 0 1 2 3 4 \n") .run(); } #[test] fn star_variadic_none() { Test::new() .arg("a") .arg("0") .arg("1") .justfile( " a x y *z: echo {{x}} {{y}} {{z}} ", ) .stdout("0 1\n") .stderr("echo 0 1 \n") .run(); } #[test] fn star_variadic_ignore_default() { Test::new() .arg("a") .arg("0") .arg("1") .arg("2") .arg("3") .arg(" 4 ") .justfile( " a x y *z='HELLO': echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 2 3 4\n") .stderr("echo 0 1 2 3 4 \n") .run(); } #[test] fn star_variadic_use_default() { Test::new() .arg("a") .arg("0") .arg("1") .justfile( " a x y *z='HELLO': echo {{x}} {{y}} {{z}} ", ) .stdout("0 1 HELLO\n") .stderr("echo 0 1 HELLO\n") .run(); } #[test] fn star_then_plus_variadic() { Test::new() .justfile( " foo *a +b: echo {{a}} {{b}} ", ) .stderr( "error: Expected \':\' or \'=\', but found \'+\' ——▶ justfile:1:8 │ 1 │ foo *a +b: │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn plus_then_star_variadic() { Test::new() .justfile( " foo +a *b: echo {{a}} {{b}} ", ) .stderr( "error: Expected \':\' or \'=\', but found \'*\' ——▶ justfile:1:8 │ 1 │ foo +a *b: │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn argument_grouping() { Test::new() .arg("BAR") .arg("0") .arg("FOO") .arg("1") .arg("2") .arg("BAZ") .arg("3") .arg("4") .arg("5") .justfile( " FOO A B='blarg': echo foo: {{A}} {{B}} BAR X: echo bar: {{X}} BAZ +Z: echo baz: {{Z}} ", ) .stdout("bar: 0\nfoo: 1 2\nbaz: 3 4 5\n") .stderr("echo bar: 0\necho foo: 1 2\necho baz: 3 4 5\n") .run(); } #[test] fn missing_second_dependency() { Test::new() .justfile( " x: a: x y ", ) .stderr( "error: Recipe `a` has unknown dependency `y` ——▶ justfile:3:6 │ 3 │ a: x y │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn list_colors() { Test::new() .arg("--color") .arg("always") .arg("--list") .justfile( " # comment a B C +D='hello': echo {{B}} {{C}} {{D}} ", ) .stdout( " Available recipes: a \ \u{1b}[36mB\u{1b}[0m \u{1b}[36mC\u{1b}[0m \u{1b}[35m+\ \u{1b}[0m\u{1b}[36mD\u{1b}[0m=\u{1b}[32m'hello'\u{1b}[0m \ \u{1b}[34m#\u{1b}[0m \u{1b}[34mcomment\u{1b}[0m ", ) .run(); } #[test] fn run_colors() { Test::new() .arg("--color") .arg("always") .arg("--highlight") .arg("--verbose") .justfile( " # comment a: echo hi ", ) .stdout("hi\n") .stderr("\u{1b}[1;36m===> Running recipe `a`...\u{1b}[0m\n\u{1b}[1mecho hi\u{1b}[0m\n") .run(); } #[test] fn no_highlight() { Test::new() .arg("--color") .arg("always") .arg("--highlight") .arg("--no-highlight") .arg("--verbose") .justfile( " # comment a: echo hi ", ) .stdout("hi\n") .stderr("\u{1b}[1;36m===> Running recipe `a`...\u{1b}[0m\necho hi\n") .run(); } #[test] fn trailing_flags() { Test::new() .arg("echo") .arg("--some") .arg("--awesome") .arg("--flags") .justfile( " echo A B C: echo {{A}} {{B}} {{C}} ", ) .stdout("--some --awesome --flags\n") .stderr("echo --some --awesome --flags\n") .run(); } #[test] fn comment_before_variable() { Test::new() .arg("echo") .justfile( " # A:='1' echo: echo {{A}} ", ) .stdout("1\n") .stderr("echo 1\n") .run(); } #[test] fn invalid_escape_sequence_message() { Test::new() .justfile( r#" X := "\'" "#, ) .stderr( r#"error: `\'` is not a valid escape sequence ——▶ justfile:1:6 │ 1 │ X := "\'" │ ^^^^ "#, ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_variable_in_default() { Test::new() .justfile( " foo x=bar: ", ) .stderr( r"error: Variable `bar` not defined ——▶ justfile:1:7 │ 1 │ foo x=bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_function_in_default() { Test::new() .justfile( " foo x=bar(): ", ) .stderr( r"error: Call to unknown function `bar` ——▶ justfile:1:7 │ 1 │ foo x=bar(): │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn default_string() { Test::new() .justfile( " foo x='bar': echo {{x}} ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn default_concatenation() { Test::new() .justfile( " foo x=(`echo foo` + 'bar'): echo {{x}} ", ) .stdout("foobar\n") .stderr("echo foobar\n") .run(); } #[test] fn default_backtick() { Test::new() .justfile( " foo x=`echo foo`: echo {{x}} ", ) .stdout("foo\n") .stderr("echo foo\n") .run(); } #[test] fn default_variable() { Test::new() .justfile( " y := 'foo' foo x=y: echo {{x}} ", ) .stdout("foo\n") .stderr("echo foo\n") .run(); } #[test] fn unterminated_interpolation_eol() { Test::new() .justfile( " foo: echo {{ ", ) .stderr( r" error: Unterminated interpolation ——▶ justfile:2:8 │ 2 │ echo {{ │ ^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_interpolation_eof() { Test::new() .justfile( " foo: echo {{ ", ) .stderr( r" error: Unterminated interpolation ——▶ justfile:2:8 │ 2 │ echo {{ │ ^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_start_of_token() { Test::new() .justfile( " assembly_source_files = %(wildcard src/arch/$(arch)/*.s) ", ) .stderr( r" error: Unknown start of token '%' ——▶ justfile:1:25 │ 1 │ assembly_source_files = %(wildcard src/arch/$(arch)/*.s) │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_start_of_token_invisible_unicode() { Test::new() .justfile( " \u{200b}foo := 'bar' ", ) .stderr( " error: Unknown start of token '\u{200b}' (U+200B) ——▶ justfile:1:1 │ 1 │ \u{200b}foo := 'bar' │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_start_of_token_ascii_control_char() { Test::new() .justfile( " \0foo := 'bar' ", ) .stderr( " error: Unknown start of token '\0' (U+0000) ——▶ justfile:1:1 │ 1 │ \0foo := 'bar' │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn backtick_variable_cat() { Test::new() .justfile( " stdin := `cat` default: echo {{stdin}} ", ) .stdin("STDIN") .stdout("STDIN\n") .stderr("echo STDIN\n") .run(); } #[test] fn backtick_default_cat_stdin() { Test::new() .justfile( " default stdin = `cat`: echo {{stdin}} ", ) .stdin("STDIN") .stdout("STDIN\n") .stderr("echo STDIN\n") .run(); } #[test] fn backtick_default_cat_justfile() { Test::new() .justfile( " default stdin = `cat justfile`: echo '{{stdin}}' ", ) .stdout( " default stdin = `cat justfile`: echo {{stdin}} ", ) .stderr( " echo 'default stdin = `cat justfile`: echo '{{stdin}}'' ", ) .run(); } #[test] fn backtick_variable_read_single() { Test::new() .justfile( " password := `read PW && echo $PW` default: echo {{password}} ", ) .stdin("foobar\n") .stdout("foobar\n") .stderr("echo foobar\n") .run(); } #[test] fn backtick_variable_read_multiple() { Test::new() .justfile( " a := `read A && echo $A` b := `read B && echo $B` default: echo {{a}} echo {{b}} ", ) .stdin("foo\nbar\n") .stdout("foo\nbar\n") .stderr("echo foo\necho bar\n") .run(); } #[test] fn backtick_default_read_multiple() { Test::new() .justfile( " default a=`read A && echo $A` b=`read B && echo $B`: echo {{a}} echo {{b}} ", ) .stdin("foo\nbar\n") .stdout("foo\nbar\n") .stderr("echo foo\necho bar\n") .run(); } #[test] fn old_equals_assignment_syntax_produces_error() { Test::new() .justfile( " foo = 'bar' default: echo {{foo}} ", ) .stderr( " error: Expected '*', ':', '$', identifier, or '+', but found '=' ——▶ justfile:1:5 │ 1 │ foo = 'bar' │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dependency_argument_string() { Test::new() .justfile( " release: (build 'foo') (build 'bar') build target: echo 'Building {{target}}...' ", ) .stdout("Building foo...\nBuilding bar...\n") .stderr("echo 'Building foo...'\necho 'Building bar...'\n") .shell(false) .run(); } #[test] fn dependency_argument_parameter() { Test::new() .justfile( " default: (release '1.0') release version: (build 'foo' version) (build 'bar' version) build target version: echo 'Building {{target}}@{{version}}...' ", ) .stdout("Building foo@1.0...\nBuilding bar@1.0...\n") .stderr("echo 'Building foo@1.0...'\necho 'Building bar@1.0...'\n") .shell(false) .run(); } #[test] fn dependency_argument_function() { Test::new() .justfile( " foo: (bar env_var_or_default('x', 'y')) bar arg: echo {{arg}} ", ) .stdout("y\n") .stderr("echo y\n") .shell(false) .run(); } #[test] fn env_function_as_env_var() { Test::new() .env("x", "z") .justfile( " foo: (bar env('x')) bar arg: echo {{arg}} ", ) .stdout("z\n") .stderr("echo z\n") .shell(false) .run(); } #[test] fn env_function_as_env_var_or_default() { Test::new() .env("x", "z") .justfile( " foo: (bar env('x', 'y')) bar arg: echo {{arg}} ", ) .stdout("z\n") .stderr("echo z\n") .shell(false) .run(); } #[test] fn env_function_as_env_var_with_existing_env_var() { Test::new() .env("x", "z") .justfile( " foo: (bar env('x')) bar arg: echo {{arg}} ", ) .stdout("z\n") .stderr("echo z\n") .shell(false) .run(); } #[test] fn env_function_as_env_var_or_default_with_existing_env_var() { Test::new() .env("x", "z") .justfile( " foo: (bar env('x', 'y')) bar arg: echo {{arg}} ", ) .stdout("z\n") .stderr("echo z\n") .shell(false) .run(); } #[test] fn dependency_argument_backtick() { Test::new() .justfile( " export X := 'X' foo: (bar `echo $X`) bar arg: echo {{arg}} echo $X ", ) .stdout("X\nX\n") .stderr("echo X\necho $X\n") .shell(false) .run(); } #[test] fn dependency_argument_assignment() { Test::new() .justfile( " v := '1.0' default: (release v) release version: echo Release {{version}}... ", ) .stdout("Release 1.0...\n") .stderr("echo Release 1.0...\n") .shell(false) .run(); } #[test] fn dependency_argument_plus_variadic() { Test::new() .justfile( " foo: (bar 'A' 'B' 'C') bar +args: echo {{args}} ", ) .stdout("A B C\n") .stderr("echo A B C\n") .shell(false) .run(); } #[test] fn duplicate_dependency_no_args() { Test::new() .justfile( " foo: bar bar bar bar bar: echo BAR ", ) .stdout("BAR\n") .stderr("echo BAR\n") .shell(false) .run(); } #[test] fn duplicate_dependency_argument() { Test::new() .justfile( " foo: (bar 'BAR') (bar `echo BAR`) bar bar: echo {{bar}} ", ) .stdout("BAR\n") .stderr("echo BAR\n") .shell(false) .run(); } #[cfg(windows)] #[test] fn pwsh_invocation_directory() { Test::new() .justfile( r#" set shell := ["pwsh", "-NoProfile", "-c"] pwd: @Test-Path {{invocation_directory()}} > result.txt "#, ) .status(EXIT_SUCCESS) .shell(false) .run(); } #[test] fn variables() { Test::new() .arg("--variables") .justfile( " z := 'a' a := 'z' ", ) .stdout("a z\n") .shell(false) .run(); } #[test] fn interpolation_evaluation_ignore_quiet() { Test::new() .justfile( r#" foo: {{"@echo foo 2>/dev/null"}} "#, ) .stderr( " @echo foo 2>/dev/null error: Recipe `foo` failed on line 2 with exit code 127 ", ) .status(127) .shell(false) .run(); } #[test] fn interpolation_evaluation_ignore_quiet_continuation() { Test::new() .justfile( r#" foo: {{""}}\ @echo foo 2>/dev/null "#, ) .stderr( " @echo foo 2>/dev/null error: Recipe `foo` failed on line 3 with exit code 127 ", ) .status(127) .shell(false) .run(); } #[test] fn brace_escape() { Test::new() .justfile( " foo: echo '{{{{' ", ) .stdout("{{\n") .stderr( " echo '{{' ", ) .run(); } #[test] fn brace_escape_extra() { Test::new() .justfile( " foo: echo '{{{{{' ", ) .stdout("{{{\n") .stderr( " echo '{{{' ", ) .run(); } #[test] fn multi_line_string_in_interpolation() { Test::new() .justfile( " foo: echo {{'a echo b echo c'}}z echo baz ", ) .stdout("a\nb\ncz\nbaz\n") .stderr("echo a\n echo b\n echo cz\necho baz\n") .run(); } #[cfg(windows)] #[test] fn windows_interpreter_path_no_base() { Test::new() .justfile( r#" foo: #!powershell exit 0 "#, ) .run(); } just-1.40.0/tests/modules.rs000064400000000000000000000413061046102023000140570ustar 00000000000000use super::*; #[test] fn modules_are_stable() { Test::new() .justfile( " mod foo ", ) .write("foo.just", "@bar:\n echo ok") .args(["foo", "bar"]) .stdout("ok\n") .run(); } #[test] fn default_recipe_in_submodule_must_have_no_arguments() { Test::new() .write("foo.just", "foo bar:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .stderr("error: Recipe `foo` cannot be used as default recipe since it requires at least 1 argument.\n") .status(EXIT_FAILURE) .run(); } #[test] fn module_recipes_can_be_run_as_subcommands() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn module_recipes_can_be_run_with_path_syntax() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo::foo") .stdout("FOO\n") .run(); } #[test] fn nested_module_recipes_can_be_run_with_path_syntax() { Test::new() .write("foo.just", "mod bar") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo ", ) .arg("foo::bar::baz") .stdout("BAZ\n") .run(); } #[test] fn invalid_path_syntax() { Test::new() .arg(":foo::foo") .stderr("error: Justfile does not contain recipe `:foo::foo`\n") .status(EXIT_FAILURE) .run(); Test::new() .arg("foo::foo:") .stderr("error: Justfile does not contain recipe `foo::foo:`\n") .status(EXIT_FAILURE) .run(); Test::new() .arg("foo:::foo") .stderr("error: Justfile does not contain recipe `foo:::foo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn missing_recipe_after_invalid_path() { Test::new() .arg(":foo::foo") .arg("bar") .stderr("error: Justfile does not contain recipe `:foo::foo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn assignments_are_evaluated_in_modules() { Test::new() .write("foo.just", "bar := 'CHILD'\nfoo:\n @echo {{bar}}") .justfile( " mod foo bar := 'PARENT' ", ) .arg("foo") .arg("foo") .stdout("CHILD\n") .run(); } #[test] fn module_subcommand_runs_default_recipe() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_can_contain_other_modules() { Test::new() .write("bar.just", "baz:\n @echo BAZ") .write("foo.just", "mod bar") .justfile( " mod foo ", ) .arg("foo") .arg("bar") .arg("baz") .stdout("BAZ\n") .run(); } #[test] fn circular_module_imports_are_detected() { Test::new() .write("bar.just", "mod foo") .write("foo.just", "mod bar") .justfile( " mod foo ", ) .arg("foo") .arg("bar") .arg("baz") .stderr_regex(path_for_regex( "error: Import `.*/foo.just` in `.*/bar.just` is circular\n", )) .status(EXIT_FAILURE) .run(); } #[test] fn modules_use_module_settings() { Test::new() .write( "foo.just", "set allow-duplicate-recipes foo: foo: @echo FOO ", ) .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); Test::new() .write( "foo.just", "foo: foo: @echo FOO ", ) .justfile( " mod foo set allow-duplicate-recipes ", ) .status(EXIT_FAILURE) .arg("foo") .arg("foo") .stderr( " error: Recipe `foo` first defined on line 1 is redefined on line 2 ——▶ foo.just:2:1 │ 2 │ foo: │ ^^^ ", ) .run(); } #[test] fn modules_conflict_with_recipes() { Test::new() .write("foo.just", "") .justfile( " mod foo foo: ", ) .stderr( " error: Module `foo` defined on line 1 is redefined as a recipe on line 2 ——▶ justfile:2:1 │ 2 │ foo: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn modules_conflict_with_aliases() { Test::new() .write("foo.just", "") .justfile( " mod foo bar: alias foo := bar ", ) .stderr( " error: Module `foo` defined on line 1 is redefined as an alias on line 3 ——▶ justfile:3:7 │ 3 │ alias foo := bar │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn modules_conflict_with_other_modules() { Test::new() .write("foo.just", "") .justfile( " mod foo mod foo bar: ", ) .status(EXIT_FAILURE) .stderr( " error: Module `foo` first defined on line 1 is redefined on line 2 ——▶ justfile:2:5 │ 2 │ mod foo │ ^^^ ", ) .run(); } #[test] fn modules_are_dumped_correctly() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("--dump") .stdout("mod foo\n") .run(); } #[test] fn optional_modules_are_dumped_correctly() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod? foo ", ) .arg("--dump") .stdout("mod? foo\n") .run(); } #[test] fn modules_can_be_in_subdirectory() { Test::new() .write("foo/mod.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_in_subdirectory_can_be_named_justfile() { Test::new() .write("foo/justfile", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_in_subdirectory_can_be_named_justfile_with_any_case() { Test::new() .write("foo/JUSTFILE", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_in_subdirectory_can_have_leading_dot() { Test::new() .write("foo/.justfile", "foo:\n @echo FOO") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_require_unambiguous_file() { Test::new() .write("foo/justfile", "foo:\n @echo FOO") .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo ", ) .status(EXIT_FAILURE) .stderr( " error: Found multiple source files for module `foo`: `foo/justfile` and `foo.just` ——▶ justfile:1:5 │ 1 │ mod foo │ ^^^ " .replace('/', MAIN_SEPARATOR_STR), ) .run(); } #[test] fn missing_module_file_error() { Test::new() .justfile( " mod foo ", ) .status(EXIT_FAILURE) .stderr( " error: Could not find source file for module `foo`. ——▶ justfile:1:5 │ 1 │ mod foo │ ^^^ ", ) .run(); } #[test] fn missing_optional_modules_do_not_trigger_error() { Test::new() .justfile( " mod? foo bar: @echo BAR ", ) .stdout("BAR\n") .run(); } #[test] fn missing_optional_modules_do_not_conflict() { Test::new() .justfile( " mod? foo mod? foo mod foo 'baz.just' ", ) .write("baz.just", "baz:\n @echo BAZ") .arg("foo") .arg("baz") .stdout("BAZ\n") .run(); } #[test] fn root_dotenv_is_available_to_submodules() { Test::new() .justfile( " set dotenv-load mod foo ", ) .write("foo.just", "foo:\n @echo $DOTENV_KEY") .write(".env", "DOTENV_KEY=dotenv-value") .args(["foo", "foo"]) .stdout("dotenv-value\n") .run(); } #[test] fn dotenv_settings_in_submodule_are_ignored() { Test::new() .justfile( " set dotenv-load mod foo ", ) .write( "foo.just", "set dotenv-load := false\nfoo:\n @echo $DOTENV_KEY", ) .write(".env", "DOTENV_KEY=dotenv-value") .args(["foo", "foo"]) .stdout("dotenv-value\n") .run(); } #[test] fn modules_may_specify_path() { Test::new() .write("commands/foo.just", "foo:\n @echo FOO") .justfile( " mod foo 'commands/foo.just' ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_may_specify_path_to_directory() { Test::new() .write("commands/bar/mod.just", "foo:\n @echo FOO") .justfile( " mod foo 'commands/bar' ", ) .arg("foo") .arg("foo") .stdout("FOO\n") .run(); } #[test] fn modules_with_paths_are_dumped_correctly() { Test::new() .write("commands/foo.just", "foo:\n @echo FOO") .justfile( " mod foo 'commands/foo.just' ", ) .arg("--dump") .stdout("mod foo 'commands/foo.just'\n") .run(); } #[test] fn optional_modules_with_paths_are_dumped_correctly() { Test::new() .write("commands/foo.just", "foo:\n @echo FOO") .justfile( " mod? foo 'commands/foo.just' ", ) .arg("--dump") .stdout("mod? foo 'commands/foo.just'\n") .run(); } #[test] fn recipes_may_be_named_mod() { Test::new() .justfile( " mod foo: @echo FOO ", ) .arg("mod") .arg("bar") .stdout("FOO\n") .run(); } #[test] fn submodule_linewise_recipes_run_in_submodule_directory() { Test::new() .write("foo/bar", "BAR") .write("foo/mod.just", "foo:\n @cat bar") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("BAR") .run(); } #[test] fn submodule_shebang_recipes_run_in_submodule_directory() { Test::new() .write("foo/bar", "BAR") .write("foo/mod.just", "foo:\n #!/bin/sh\n cat bar") .justfile( " mod foo ", ) .arg("foo") .arg("foo") .stdout("BAR") .run(); } #[cfg(not(windows))] #[test] fn module_paths_beginning_with_tilde_are_expanded_to_homdir() { Test::new() .write("foobar/mod.just", "foo:\n @echo FOOBAR") .justfile( " mod foo '~/mod.just' ", ) .arg("foo") .arg("foo") .stdout("FOOBAR\n") .env("HOME", "foobar") .run(); } #[test] fn recipes_with_same_name_are_both_run() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo bar: @echo ROOT ", ) .arg("foo::bar") .arg("bar") .stdout("MODULE\nROOT\n") .run(); } #[test] fn submodule_recipe_not_found_error_message() { Test::new() .args(["foo::bar"]) .stderr("error: Justfile does not contain submodule `foo`\n") .status(1) .run(); } #[test] fn submodule_recipe_not_found_spaced_error_message() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["foo", "baz"]) .stderr("error: Justfile does not contain recipe `foo baz`\nDid you mean `bar`?\n") .status(1) .run(); } #[test] fn submodule_recipe_not_found_colon_separated_error_message() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["foo::baz"]) .stderr("error: Justfile does not contain recipe `foo::baz`\nDid you mean `bar`?\n") .status(1) .run(); } #[test] fn colon_separated_path_does_not_run_recipes() { Test::new() .justfile( " foo: @echo FOO bar: @echo BAR ", ) .args(["foo::bar"]) .stderr("error: Expected submodule at `foo` but found recipe.\n") .status(1) .run(); } #[test] fn expected_submodule_but_found_recipe_in_root_error() { Test::new() .justfile("foo:") .arg("foo::baz") .stderr("error: Expected submodule at `foo` but found recipe.\n") .status(1) .run(); } #[test] fn expected_submodule_but_found_recipe_in_submodule_error() { Test::new() .justfile("mod foo") .write("foo.just", "bar:") .args(["foo::bar::baz"]) .stderr("error: Expected submodule at `foo::bar` but found recipe.\n") .status(1) .run(); } #[test] fn colon_separated_path_components_are_not_used_as_arguments() { Test::new() .justfile("foo bar:") .args(["foo::bar"]) .stderr("error: Expected submodule at `foo` but found recipe.\n") .status(1) .run(); } #[test] fn comments_can_follow_modules() { Test::new() .write("foo.just", "foo:\n @echo FOO") .justfile( " mod foo # this is foo ", ) .args(["foo", "foo"]) .stdout("FOO\n") .run(); } #[test] fn doc_comment_on_module() { Test::new() .write("foo.just", "") .justfile( " # Comment mod foo ", ) .test_round_trip(false) .arg("--list") .stdout("Available recipes:\n foo ... # Comment\n") .run(); } #[test] fn doc_attribute_on_module() { Test::new() .write("foo.just", "") .justfile( r#" # Suppressed comment [doc: "Comment"] mod foo "#, ) .test_round_trip(false) .arg("--list") .stdout("Available recipes:\n foo ... # Comment\n") .run(); } #[test] fn group_attribute_on_module() { Test::new() .write("foo.just", "") .write("bar.just", "") .write("zee.just", "") .justfile( r" [group('alpha')] mod zee [group('alpha')] mod foo [group('alpha')] a: [group('beta')] b: [group('beta')] mod bar c: ", ) .test_round_trip(false) .arg("--list") .stdout( " Available recipes: c [alpha] a foo ... zee ... [beta] b bar ... ", ) .run(); } #[test] fn group_attribute_on_module_unsorted() { Test::new() .write("foo.just", "") .write("bar.just", "") .write("zee.just", "") .justfile( r" [group('alpha')] mod zee [group('alpha')] mod foo [group('alpha')] a: [group('beta')] b: [group('beta')] mod bar c: ", ) .test_round_trip(false) .arg("--list") .arg("--unsorted") .stdout( " Available recipes: c [alpha] a zee ... foo ... [beta] b bar ... ", ) .run(); } #[test] fn group_attribute_on_module_list_submodule() { Test::new() .write("foo.just", "d:") .write("bar.just", "e:") .write("zee.just", "f:") .justfile( r" [group('alpha')] mod zee [group('alpha')] mod foo [group('alpha')] a: [group('beta')] b: [group('beta')] mod bar c: ", ) .test_round_trip(false) .arg("--list") .arg("--list-submodules") .stdout( " Available recipes: c [alpha] a foo: d zee: f [beta] b bar: e ", ) .run(); } #[test] fn group_attribute_on_module_list_submodule_unsorted() { Test::new() .write("foo.just", "d:") .write("bar.just", "e:") .write("zee.just", "f:") .justfile( r" [group('alpha')] mod zee [group('alpha')] mod foo [group('alpha')] a: [group('beta')] b: [group('beta')] mod bar c: ", ) .test_round_trip(false) .arg("--list") .arg("--list-submodules") .arg("--unsorted") .stdout( " Available recipes: c [alpha] a zee: f foo: d [beta] b bar: e ", ) .run(); } #[test] fn bad_module_attribute_fails() { Test::new() .write("foo.just", "") .justfile( r" [no-cd] mod foo ", ) .test_round_trip(false) .arg("--list") .stderr("error: Module `foo` has invalid attribute `no-cd`\n ——▶ justfile:2:5\n │\n2 │ mod foo\n │ ^^^\n") .status(EXIT_FAILURE) .run(); } #[test] fn empty_doc_attribute_on_module() { Test::new() .write("foo.just", "") .justfile( r" # Suppressed comment [doc] mod foo ", ) .test_round_trip(false) .arg("--list") .stdout("Available recipes:\n foo ...\n") .run(); } just-1.40.0/tests/multibyte_char.rs000064400000000000000000000001341046102023000154140ustar 00000000000000use super::*; #[test] fn bugfix() { Test::new().justfile("foo:\nx := '''ǩ'''").run(); } just-1.40.0/tests/newline_escape.rs000064400000000000000000000027731046102023000153750ustar 00000000000000use super::*; #[test] fn newline_escape_deps() { Test::new() .justfile( " default: a \\ b \\ c a: echo a b: echo b c: echo c ", ) .stdout("a\nb\nc\n") .stderr("echo a\necho b\necho c\n") .run(); } #[test] fn newline_escape_deps_no_indent() { Test::new() .justfile( " default: a\\ b\\ c a: echo a b: echo b c: echo c ", ) .stdout("a\nb\nc\n") .stderr("echo a\necho b\necho c\n") .run(); } #[test] fn newline_escape_deps_linefeed() { Test::new() .justfile( " default: a\\\r b a: echo a b: echo b ", ) .stdout("a\nb\n") .stderr("echo a\necho b\n") .run(); } #[test] fn newline_escape_deps_invalid_esc() { Test::new() .justfile( " default: a\\ b ", ) .stderr( " error: `\\ ` is not a valid escape sequence ——▶ justfile:1:11 │ 1 │ default: a\\ b │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn newline_escape_unpaired_linefeed() { Test::new() .justfile( " default:\\\ra", ) .stderr( " error: Unpaired carriage return ——▶ justfile:1:9 │ 1 │ default:\\\ra │ ^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/no_aliases.rs000064400000000000000000000004521046102023000145210ustar 00000000000000use super::*; #[test] fn skip_alias() { Test::new() .justfile( " alias t := test1 test1: @echo 'test1' test2: @echo 'test2' ", ) .args(["--no-aliases", "--list"]) .stdout("Available recipes:\n test1\n test2\n") .run(); } just-1.40.0/tests/no_cd.rs000064400000000000000000000010361046102023000134650ustar 00000000000000use super::*; #[test] fn linewise() { Test::new() .justfile( " [no-cd] foo: cat bar ", ) .current_dir("foo") .tree(tree! { foo: { bar: "hello", } }) .stderr("cat bar\n") .stdout("hello") .run(); } #[test] fn shebang() { Test::new() .justfile( " [no-cd] foo: #!/bin/sh cat bar ", ) .current_dir("foo") .tree(tree! { foo: { bar: "hello", } }) .stdout("hello") .run(); } just-1.40.0/tests/no_dependencies.rs000064400000000000000000000013001046102023000155170ustar 00000000000000use super::*; #[test] fn skip_normal_dependency() { Test::new() .justfile( " a: @echo 'a' b: a @echo 'b' ", ) .args(["--no-deps", "b"]) .stdout("b\n") .run(); } #[test] fn skip_prior_dependency() { Test::new() .justfile( " a: @echo 'a' b: && a @echo 'b' ", ) .args(["--no-deps", "b"]) .stdout("b\n") .run(); } #[test] fn skip_dependency_multi() { Test::new() .justfile( " a: @echo 'a' b: && a @echo 'b' ", ) .args(["--no-deps", "b", "a"]) .stdout("b\na\n") .run(); } just-1.40.0/tests/no_exit_message.rs000064400000000000000000000105151046102023000155560ustar 00000000000000use super::*; #[test] fn recipe_exit_message_suppressed() { Test::new() .justfile( " # This is a doc comment [no-exit-message] hello: @echo 'Hello, World!' @exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn silent_recipe_exit_message_suppressed() { Test::new() .justfile( " # This is a doc comment [no-exit-message] @hello: echo 'Hello, World!' exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn recipe_has_doc_comment() { Test::new() .justfile( " # This is a doc comment [no-exit-message] hello: @exit 100 ", ) .arg("--list") .stdout( " Available recipes: hello # This is a doc comment ", ) .run(); } #[test] fn unknown_attribute() { Test::new() .justfile( " # This is a doc comment [unknown-attribute] hello: @exit 100 ", ) .stderr( " error: Unknown attribute `unknown-attribute` ——▶ justfile:2:2 │ 2 │ [unknown-attribute] │ ^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn empty_attribute() { Test::new() .justfile( " # This is a doc comment [] hello: @exit 100 ", ) .stderr( " error: Expected identifier, but found ']' ——▶ justfile:2:2 │ 2 │ [] │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn extraneous_attribute_before_comment() { Test::new() .justfile( " [no-exit-message] # This is a doc comment hello: @exit 100 ", ) .stderr( " error: Extraneous attribute ——▶ justfile:1:1 │ 1 │ [no-exit-message] │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn extraneous_attribute_before_empty_line() { Test::new() .justfile( " [no-exit-message] hello: @exit 100 ", ) .stderr( " error: Extraneous attribute ——▶ justfile:1:1 │ 1 │ [no-exit-message] │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn shebang_exit_message_suppressed() { Test::new() .justfile( " [no-exit-message] hello: #!/usr/bin/env bash echo 'Hello, World!' exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn no_exit_message() { Test::new() .justfile( " [no-exit-message] @hello: echo 'Hello, World!' exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn exit_message() { Test::new() .justfile( " [exit-message] @hello: echo 'Hello, World!' exit 100 ", ) .stdout("Hello, World!\n") .status(100) .stderr("error: Recipe `hello` failed on line 4 with exit code 100\n") .run(); } #[test] fn recipe_exit_message_setting_suppressed() { Test::new() .justfile( " set no-exit-message # This is a doc comment hello: @echo 'Hello, World!' @exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn shebang_exit_message_setting_suppressed() { Test::new() .justfile( " set no-exit-message hello: #!/usr/bin/env bash echo 'Hello, World!' exit 100 ", ) .stdout("Hello, World!\n") .status(100) .run(); } #[test] fn exit_message_override_no_exit_setting() { Test::new() .justfile( " set no-exit-message [exit-message] fail: @exit 100 ", ) .status(100) .stderr("error: Recipe `fail` failed on line 5 with exit code 100\n") .run(); } #[test] fn exit_message_and_no_exit_message_compile_forbidden() { Test::new() .justfile( " [exit-message, no-exit-message] bar: ", ) .stderr( " error: Recipe `bar` has both `[exit-message]` and `[no-exit-message]` attributes ——▶ justfile:2:1 │ 2 │ bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/os_attributes.rs000064400000000000000000000032471046102023000153000ustar 00000000000000use super::*; #[test] fn os_family() { Test::new() .justfile( " [unix] foo: echo bar [windows] foo: echo baz ", ) .stdout(if cfg!(unix) { "bar\n" } else if cfg!(windows) { "baz\n" } else { panic!("unexpected os family") }) .stderr(if cfg!(unix) { "echo bar\n" } else if cfg!(windows) { "echo baz\n" } else { panic!("unexpected os family") }) .run(); } #[test] fn os() { Test::new() .justfile( " [macos] foo: echo bar [windows] foo: echo baz [linux] foo: echo quxx [openbsd] foo: echo bob ", ) .stdout(if cfg!(target_os = "macos") { "bar\n" } else if cfg!(windows) { "baz\n" } else if cfg!(target_os = "linux") { "quxx\n" } else if cfg!(target_os = "openbsd") { "bob\n" } else { panic!("unexpected os family") }) .stderr(if cfg!(target_os = "macos") { "echo bar\n" } else if cfg!(windows) { "echo baz\n" } else if cfg!(target_os = "linux") { "echo quxx\n" } else if cfg!(target_os = "openbsd") { "echo bob\n" } else { panic!("unexpected os family") }) .run(); } #[test] fn all() { Test::new() .justfile( " [linux] [macos] [openbsd] [unix] [windows] foo: echo bar ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn none() { Test::new() .justfile( " foo: echo bar ", ) .stdout("bar\n") .stderr("echo bar\n") .run(); } just-1.40.0/tests/parameters.rs000064400000000000000000000015711046102023000145520ustar 00000000000000use super::*; #[test] fn parameter_default_values_may_use_earlier_parameters() { Test::new() .justfile( " @foo a b=a: echo {{ b }} ", ) .args(["foo", "bar"]) .stdout("bar\n") .run(); } #[test] fn parameter_default_values_may_not_use_later_parameters() { Test::new() .justfile( " @foo a b=c c='': echo {{ b }} ", ) .args(["foo", "bar"]) .stderr( " error: Variable `c` not defined ——▶ justfile:1:10 │ 1 │ @foo a b=c c='': │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn star_may_follow_default() { Test::new() .justfile( " foo bar='baz' *bob: @echo {{bar}} {{bob}} ", ) .args(["foo", "hello", "goodbye"]) .stdout("hello goodbye\n") .run(); } just-1.40.0/tests/parser.rs000064400000000000000000000013651046102023000137040ustar 00000000000000use super::*; #[test] fn dont_run_duplicate_recipes() { Test::new() .justfile( " set dotenv-load # foo bar: ", ) .run(); } #[test] fn invalid_bang_operator() { Test::new() .justfile( " x := if '' !! '' { '' } else { '' } ", ) .status(1) .stderr( r" error: Expected character `=` or `~` ——▶ justfile:1:13 │ 1 │ x := if '' !! '' { '' } else { '' } │ ^ ", ) .run(); } #[test] fn truncated_bang_operator() { Test::new() .justfile("x := if '' !") .status(1) .stderr( r" error: Expected character `=` or `~` but found end-of-file ——▶ justfile:1:13 │ 1 │ x := if '' ! │ ^ ", ) .run(); } just-1.40.0/tests/positional_arguments.rs000064400000000000000000000051451046102023000166560ustar 00000000000000use super::*; #[test] fn linewise() { Test::new() .arg("foo") .arg("hello") .arg("goodbye") .justfile( r#" set positional-arguments foo bar baz: echo $0 echo $1 echo $2 echo "$@" "#, ) .stdout( " foo hello goodbye hello goodbye ", ) .stderr( r#" echo $0 echo $1 echo $2 echo "$@" "#, ) .run(); } #[test] fn linewise_with_attribute() { Test::new() .arg("foo") .arg("hello") .arg("goodbye") .justfile( r#" [positional-arguments] foo bar baz: echo $0 echo $1 echo $2 echo "$@" "#, ) .stdout( " foo hello goodbye hello goodbye ", ) .stderr( r#" echo $0 echo $1 echo $2 echo "$@" "#, ) .run(); } #[test] fn variadic_linewise() { Test::new() .args(["foo", "a", "b", "c"]) .justfile( r#" set positional-arguments foo *bar: echo $1 echo "$@" "#, ) .stdout("a\na b c\n") .stderr("echo $1\necho \"$@\"\n") .run(); } #[test] fn shebang() { Test::new() .arg("foo") .arg("hello") .justfile( " set positional-arguments foo bar: #!/bin/sh echo $1 ", ) .stdout("hello\n") .run(); } #[test] fn shebang_with_attribute() { Test::new() .arg("foo") .arg("hello") .justfile( " [positional-arguments] foo bar: #!/bin/sh echo $1 ", ) .stdout("hello\n") .run(); } #[test] fn variadic_shebang() { Test::new() .arg("foo") .arg("a") .arg("b") .arg("c") .justfile( r#" set positional-arguments foo *bar: #!/bin/sh echo $1 echo "$@" "#, ) .stdout("a\na b c\n") .run(); } #[test] fn default_arguments() { Test::new() .justfile( r" set positional-arguments foo bar='baz': echo $1 ", ) .stdout("baz\n") .stderr("echo $1\n") .run(); } #[test] fn empty_variadic_is_undefined() { Test::new() .justfile( r#" set positional-arguments foo *bar: if [ -n "${1+1}" ]; then echo defined; else echo undefined; fi "#, ) .stdout("undefined\n") .stderr("if [ -n \"${1+1}\" ]; then echo defined; else echo undefined; fi\n") .run(); } #[test] fn variadic_arguments_are_separate() { Test::new() .arg("foo") .arg("a") .arg("b") .justfile( r" set positional-arguments foo *bar: echo $1 echo $2 ", ) .stdout("a\nb\n") .stderr("echo $1\necho $2\n") .run(); } just-1.40.0/tests/private.rs000064400000000000000000000013321046102023000140540ustar 00000000000000use super::*; #[test] fn private_attribute_for_recipe() { Test::new() .justfile( " [private] foo: ", ) .args(["--list"]) .stdout( " Available recipes: ", ) .run(); } #[test] fn private_attribute_for_alias() { Test::new() .justfile( " [private] alias f := foo foo: ", ) .args(["--list"]) .stdout( " Available recipes: foo ", ) .run(); } #[test] fn private_variables_are_not_listed() { Test::new() .justfile( " [private] foo := 'one' bar := 'two' _baz := 'three' ", ) .args(["--variables"]) .stdout("bar\n") .run(); } just-1.40.0/tests/quiet.rs000064400000000000000000000071231046102023000135350ustar 00000000000000use super::*; #[test] fn no_stdout() { Test::new() .arg("--quiet") .justfile( r" default: @echo hello ", ) .run(); } #[test] fn stderr() { Test::new() .arg("--quiet") .justfile( r" default: @echo hello 1>&2 ", ) .run(); } #[test] fn command_echoing() { Test::new() .arg("--quiet") .justfile( r" default: exit ", ) .run(); } #[test] fn error_messages() { Test::new() .arg("--quiet") .justfile( r" default: exit 100 ", ) .status(100) .run(); } #[test] fn assignment_backtick_stderr() { Test::new() .arg("--quiet") .justfile( r" a := `echo hello 1>&2` default: exit 100 ", ) .status(100) .run(); } #[test] fn interpolation_backtick_stderr() { Test::new() .arg("--quiet") .justfile( r" default: echo `echo hello 1>&2` exit 100 ", ) .status(100) .run(); } #[test] fn choose_none() { Test::new() .arg("--choose") .arg("--quiet") .justfile("") .status(EXIT_FAILURE) .run(); } #[test] fn choose_invocation() { Test::new() .arg("--choose") .arg("--quiet") .arg("--shell") .arg("asdfasdfasfdasdfasdfadsf") .justfile("foo:") .shell(false) .status(EXIT_FAILURE) .run(); } #[test] fn choose_status() { Test::new() .arg("--choose") .arg("--quiet") .arg("--chooser") .arg("/usr/bin/env false") .justfile("foo:") .status(EXIT_FAILURE) .run(); } #[test] fn edit_invocation() { Test::new() .arg("--edit") .arg("--quiet") .env("VISUAL", "adsfasdfasdfadsfadfsaf") .justfile("foo:") .status(EXIT_FAILURE) .run(); } #[test] fn edit_status() { Test::new() .arg("--edit") .arg("--quiet") .env("VISUAL", "false") .justfile("foo:") .status(EXIT_FAILURE) .run(); } #[test] fn init_exists() { Test::new() .arg("--init") .arg("--quiet") .justfile("foo:") .status(EXIT_FAILURE) .run(); } #[test] fn show_missing() { Test::new() .arg("--show") .arg("bar") .arg("--quiet") .justfile("foo:") .status(EXIT_FAILURE) .run(); } #[test] fn quiet_shebang() { Test::new() .arg("--quiet") .justfile( " @foo: #!/bin/sh ", ) .run(); } #[test] fn no_quiet_setting() { Test::new() .justfile( " foo: echo FOO ", ) .stdout("FOO\n") .stderr("echo FOO\n") .run(); } #[test] fn quiet_setting() { Test::new() .justfile( " set quiet foo: echo FOO ", ) .stdout("FOO\n") .run(); } #[test] fn quiet_setting_with_no_quiet_attribute() { Test::new() .justfile( " set quiet [no-quiet] foo: echo FOO ", ) .stdout("FOO\n") .stderr("echo FOO\n") .run(); } #[test] fn quiet_setting_with_quiet_recipe() { Test::new() .justfile( " set quiet @foo: echo FOO ", ) .stdout("FOO\n") .run(); } #[test] fn quiet_setting_with_quiet_line() { Test::new() .justfile( " set quiet foo: @echo FOO ", ) .stdout("FOO\n") .run(); } #[test] fn quiet_setting_with_no_quiet_attribute_and_quiet_recipe() { Test::new() .justfile( " set quiet [no-quiet] @foo: echo FOO ", ) .stdout("FOO\n") .run(); } #[test] fn quiet_setting_with_no_quiet_attribute_and_quiet_line() { Test::new() .justfile( " set quiet [no-quiet] foo: @echo FOO ", ) .stdout("FOO\n") .run(); } just-1.40.0/tests/quote.rs000064400000000000000000000011721046102023000135410ustar 00000000000000use super::*; #[test] fn single_quotes_are_prepended_and_appended() { Test::new() .justfile( " x := quote('abc') ", ) .args(["--evaluate", "x"]) .stdout("'abc'") .run(); } #[test] fn quotes_are_escaped() { Test::new() .justfile( r#" x := quote("'") "#, ) .args(["--evaluate", "x"]) .stdout(r"''\'''") .run(); } #[test] fn quoted_strings_can_be_used_as_arguments() { Test::new() .justfile( r#" file := quote("foo ' bar") @foo: touch {{ file }} ls -1 "#, ) .stdout("foo ' bar\njustfile\n") .run(); } just-1.40.0/tests/readme.rs000064400000000000000000000014351046102023000136430ustar 00000000000000use super::*; #[test] fn readme() { let mut justfiles = Vec::new(); let mut current = None; for line in fs::read_to_string("README.md").unwrap().lines() { if let Some(mut justfile) = current { if line == "```" { justfiles.push(justfile); current = None; } else { justfile += line; justfile += "\n"; current = Some(justfile); } } else if line == "```just" { current = Some(String::new()); } } for justfile in justfiles { let tmp = tempdir(); let path = tmp.path().join("justfile"); fs::write(path, justfile).unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--dump") .output() .unwrap(); assert_success(&output); } } just-1.40.0/tests/recursion_limit.rs000064400000000000000000000035321046102023000156150ustar 00000000000000use super::*; #[test] fn bugfix() { let mut justfile = String::from("foo: (x "); for _ in 0..500 { justfile.push('('); } Test::new() .justfile(&justfile) .stderr(RECURSION_LIMIT_REACHED) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] const RECURSION_LIMIT_REACHED: &str = " error: Parsing recursion depth exceeded ——▶ justfile:1:265 │ 1 │ foo: (x (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( │ ^ "; #[cfg(windows)] const RECURSION_LIMIT_REACHED: &str = " error: Parsing recursion depth exceeded ——▶ justfile:1:57 │ 1 │ foo: (x (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( │ ^ "; just-1.40.0/tests/regexes.rs000064400000000000000000000025401046102023000140460ustar 00000000000000use super::*; #[test] fn match_succeeds_evaluates_to_first_branch() { Test::new() .justfile( " foo := if 'abbbc' =~ 'ab+c' { 'yes' } else { 'no' } default: echo {{ foo }} ", ) .stderr("echo yes\n") .stdout("yes\n") .run(); } #[test] fn match_fails_evaluates_to_second_branch() { Test::new() .justfile( " foo := if 'abbbc' =~ 'ab{4}c' { 'yes' } else { 'no' } default: echo {{ foo }} ", ) .stderr("echo no\n") .stdout("no\n") .run(); } #[test] fn bad_regex_fails_at_runtime() { Test::new() .justfile( " default: echo before echo {{ if '' =~ '(' { 'a' } else { 'b' } }} echo after ", ) .stderr( " echo before error: regex parse error: ( ^ error: unclosed group ", ) .stdout("before\n") .status(EXIT_FAILURE) .run(); } #[test] fn mismatch() { Test::new() .justfile( " foo := if 'Foo' !~ '^ab+c' { 'mismatch' } else { 'match' } bar := if 'Foo' !~ 'Foo' { 'mismatch' } else { 'match' } @default: echo {{ foo }} {{ bar }} ", ) .stdout("mismatch match\n") .run(); } just-1.40.0/tests/request.rs000064400000000000000000000010611046102023000140710ustar 00000000000000use super::*; #[test] fn environment_variable_set() { Test::new() .justfile( r#" export BAR := 'baz' @foo: '{{just_executable()}}' --request '{"environment-variable": "BAR"}' "#, ) .response(Response::EnvironmentVariable(Some("baz".into()))) .run(); } #[test] fn environment_variable_missing() { Test::new() .justfile( r#" @foo: '{{just_executable()}}' --request '{"environment-variable": "FOO_BAR_BAZ"}' "#, ) .response(Response::EnvironmentVariable(None)) .run(); } just-1.40.0/tests/run.rs000064400000000000000000000012301046102023000132030ustar 00000000000000use super::*; #[test] fn dont_run_duplicate_recipes() { Test::new() .justfile( " @foo: echo foo ", ) .args(["foo", "foo"]) .stdout("foo\n") .run(); } #[test] fn one_flag_only_allows_one_invocation() { Test::new() .justfile( " @foo: echo foo ", ) .args(["--one", "foo"]) .stdout("foo\n") .run(); Test::new() .justfile( " @foo: echo foo @bar: echo bar ", ) .args(["--one", "foo", "bar"]) .stderr("error: Expected 1 command-line recipe invocation but found 2.\n") .status(1) .run(); } just-1.40.0/tests/script.rs000064400000000000000000000076141046102023000137170ustar 00000000000000use super::*; #[test] fn unstable() { Test::new() .justfile( " [script('sh', '-u')] foo: echo FOO ", ) .stderr_regex(r"error: The `\[script\]` attribute is currently unstable\..*") .status(EXIT_FAILURE) .run(); } #[test] fn script_interpreter_setting_is_unstable() { Test::new() .justfile("set script-interpreter := ['sh']") .status(EXIT_FAILURE) .stderr_regex(r"error: The `script-interpreter` setting is currently unstable\..*") .run(); } #[test] fn runs_with_command() { Test::new() .justfile( " set unstable [script('cat')] foo: FOO ", ) .stdout( " FOO ", ) .run(); } #[test] fn no_arguments() { Test::new() .justfile( " set unstable [script('sh')] foo: echo foo ", ) .stdout("foo\n") .run(); } #[test] fn with_arguments() { Test::new() .justfile( " set unstable [script('sh', '-x')] foo: echo foo ", ) .stdout("foo\n") .stderr("+ echo foo\n") .run(); } #[test] fn not_allowed_with_shebang() { Test::new() .justfile( " set unstable [script('sh', '-u')] foo: #!/bin/sh ", ) .stderr( " error: Recipe `foo` has both shebang line and `[script]` attribute ——▶ justfile:4:1 │ 4 │ foo: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn script_line_numbers() { Test::new() .justfile( " set unstable [script('cat')] foo: FOO BAR ", ) .stdout( " FOO BAR ", ) .run(); } #[test] fn script_line_numbers_with_multi_line_recipe_signature() { Test::new() .justfile( r" set unstable [script('cat')] foo bar='baz' \ : FOO BAR {{ \ bar \ }} BAZ ", ) .stdout( " FOO BAR baz BAZ ", ) .run(); } #[cfg(not(windows))] #[test] fn shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat a b c ", ) .stdout( "#!/usr/bin/env cat a b c ", ) .run(); } #[cfg(not(windows))] #[test] fn shebang_line_numbers_with_multiline_constructs() { Test::new() .justfile( r"foo b='b'\ : #!/usr/bin/env cat a {{ \ b \ }} c ", ) .stdout( "#!/usr/bin/env cat a b c ", ) .run(); } #[cfg(not(windows))] #[test] fn multiline_shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat #!shebang #!shebang a b c ", ) .stdout( "#!/usr/bin/env cat #!shebang #!shebang a b c ", ) .run(); } #[cfg(windows)] #[test] fn shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat a b c ", ) .stdout( " a b c ", ) .run(); } #[test] fn no_arguments_with_default_script_interpreter() { Test::new() .justfile( " set unstable [script] foo: case $- in *e*) echo '-e is set';; esac case $- in *u*) echo '-u is set';; esac ", ) .stdout( " -e is set -u is set ", ) .run(); } #[test] fn no_arguments_with_non_default_script_interpreter() { Test::new() .justfile( " set unstable set script-interpreter := ['sh'] [script] foo: case $- in *e*) echo '-e is set';; esac case $- in *u*) echo '-u is set';; esac ", ) .run(); } just-1.40.0/tests/search.rs000064400000000000000000000070771046102023000136630ustar 00000000000000use super::*; fn search_test>(path: P, args: &[&str]) { let binary = executable_path("just"); let output = Command::new(binary) .current_dir(path) .args(args) .output() .expect("just invocation failed"); assert_eq!(output.status.code().unwrap(), 0); let stdout = str::from_utf8(&output.stdout).unwrap(); assert_eq!(stdout, "ok\n"); let stderr = str::from_utf8(&output.stderr).unwrap(); assert_eq!(stderr, "echo ok\n"); } #[test] fn test_justfile_search() { let tmp = temptree! { justfile: "default:\n\techo ok", a: { b: { c: { d: {}, }, }, }, }; search_test(tmp.path().join("a/b/c/d"), &[]); } #[test] fn test_capitalized_justfile_search() { let tmp = temptree! { Justfile: "default:\n\techo ok", a: { b: { c: { d: {}, }, }, }, }; search_test(tmp.path().join("a/b/c/d"), &[]); } #[test] fn test_upwards_path_argument() { let tmp = temptree! { justfile: "default:\n\techo ok", a: { justfile: "default:\n\techo bad", }, }; search_test(tmp.path().join("a"), &["../"]); search_test(tmp.path().join("a"), &["../default"]); } #[test] fn test_downwards_path_argument() { let tmp = temptree! { justfile: "default:\n\techo bad", a: { justfile: "default:\n\techo ok", }, }; let path = tmp.path(); search_test(path, &["a/"]); search_test(path, &["a/default"]); search_test(path, &["./a/"]); search_test(path, &["./a/default"]); search_test(path, &["./a/"]); search_test(path, &["./a/default"]); } #[test] fn test_upwards_multiple_path_argument() { let tmp = temptree! { justfile: "default:\n\techo ok", a: { b: { justfile: "default:\n\techo bad", }, }, }; let path = tmp.path().join("a").join("b"); search_test(&path, &["../../"]); search_test(&path, &["../../default"]); } #[test] fn test_downwards_multiple_path_argument() { let tmp = temptree! { justfile: "default:\n\techo bad", a: { b: { justfile: "default:\n\techo ok", }, }, }; let path = tmp.path(); search_test(path, &["a/b/"]); search_test(path, &["a/b/default"]); search_test(path, &["./a/b/"]); search_test(path, &["./a/b/default"]); search_test(path, &["./a/b/"]); search_test(path, &["./a/b/default"]); } #[test] fn single_downwards() { let tmp = temptree! { justfile: "default:\n\techo ok", child: {}, }; let path = tmp.path(); search_test(path, &["child/"]); } #[test] fn single_upwards() { let tmp = temptree! { justfile: "default:\n\techo ok", child: {}, }; let path = tmp.path().join("child"); search_test(path, &["../"]); } #[test] fn double_upwards() { let tmp = temptree! { justfile: "default:\n\techo ok", foo: { bar: { justfile: "default:\n\techo foo", }, }, }; let path = tmp.path().join("foo/bar"); search_test(path, &["../default"]); } #[test] fn find_dot_justfile() { Test::new() .justfile( " foo: echo bad ", ) .tree(tree! { dir: { ".justfile": " foo: echo ok " } }) .current_dir("dir") .stderr("echo ok\n") .stdout("ok\n") .run(); } #[test] fn dot_justfile_conflicts_with_justfile() { Test::new() .justfile( " foo: ", ) .tree(tree! { ".justfile": " foo: ", }) .stderr_regex("error: Multiple candidate justfiles found in `.*`: `.justfile` and `justfile`\n") .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/search_arguments.rs000064400000000000000000000010261046102023000157340ustar 00000000000000use super::*; #[test] fn argument_with_different_path_prefix_is_allowed() { Test::new() .justfile("foo bar:") .args(["./foo", "../bar"]) .run(); } #[test] fn passing_dot_as_argument_is_allowed() { Test::new() .justfile( " say ARG: echo {{ARG}} ", ) .write( "child/justfile", "say ARG:\n '{{just_executable()}}' ../say {{ARG}}", ) .current_dir("child") .args(["say", "."]) .stdout(".\n") .stderr_regex("'.*' ../say .\necho .\n") .run(); } just-1.40.0/tests/shadowing_parameters.rs000064400000000000000000000012651046102023000166150ustar 00000000000000use super::*; #[test] fn parameter_may_shadow_variable() { Test::new() .arg("a") .arg("bar") .justfile("FOO := 'hello'\na FOO:\n echo {{FOO}}\n") .stdout("bar\n") .stderr("echo bar\n") .run(); } #[test] fn shadowing_parameters_do_not_change_environment() { Test::new() .arg("a") .arg("bar") .justfile("export FOO := 'hello'\na FOO:\n echo $FOO\n") .stdout("hello\n") .stderr("echo $FOO\n") .run(); } #[test] fn exporting_shadowing_parameters_does_change_environment() { Test::new() .arg("a") .arg("bar") .justfile("export FOO := 'hello'\na $FOO:\n echo $FOO\n") .stdout("bar\n") .stderr("echo $FOO\n") .run(); } just-1.40.0/tests/shebang.rs000064400000000000000000000043261046102023000140170ustar 00000000000000use super::*; #[cfg(windows)] #[test] fn powershell() { Test::new() .justfile( r#" default: #!powershell Write-Host Hello-World "#, ) .stdout("Hello-World\n") .run(); } #[cfg(windows)] #[test] fn powershell_exe() { Test::new() .justfile( r#" default: #!powershell.exe Write-Host Hello-World "#, ) .stdout("Hello-World\n") .run(); } #[cfg(windows)] #[test] fn cmd() { Test::new() .justfile( r#" default: #!cmd /c @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[cfg(windows)] #[test] fn cmd_exe() { Test::new() .justfile( r#" default: #!cmd.exe /c @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[cfg(windows)] #[test] fn multi_line_cmd_shebangs_are_removed() { Test::new() .justfile( r#" default: #!cmd.exe /c #!foo @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[test] fn simple() { Test::new() .justfile( " foo: #!/bin/sh echo bar ", ) .stdout("bar\n") .run(); } #[test] fn echo() { Test::new() .justfile( " @baz: #!/bin/sh echo fizz ", ) .stdout("fizz\n") .stderr("#!/bin/sh\necho fizz\n") .run(); } #[test] fn echo_with_command_color() { Test::new() .justfile( " @baz: #!/bin/sh echo fizz ", ) .args(["--color", "always", "--command-color", "purple"]) .stdout("fizz\n") .stderr("\u{1b}[1;35m#!/bin/sh\u{1b}[0m\n\u{1b}[1;35mecho fizz\u{1b}[0m\n") .run(); } // This test exists to make sure that shebang recipes run correctly. Although // this script is still executed by a shell its behavior depends on the value of // a variable and continuing even though a command fails, whereas in plain // recipes variables are not available in subsequent lines and execution stops // when a line fails. #[test] fn run_shebang() { Test::new() .justfile( " a: #!/usr/bin/env sh code=200 x() { return $code; } x x ", ) .status(200) .stderr("error: Recipe `a` failed with exit code 200\n") .run(); } just-1.40.0/tests/shell.rs000064400000000000000000000070101046102023000135100ustar 00000000000000use super::*; const JUSTFILE: &str = " expression := `EXPRESSION` recipe default=`DEFAULT`: {{expression}} {{default}} RECIPE "; /// Test that --shell correctly sets the shell #[test] #[cfg_attr(windows, ignore)] fn flag() { let tmp = temptree! { justfile: JUSTFILE, shell: "#!/usr/bin/env bash\necho \"$@\"", }; let shell = tmp.path().join("shell"); #[cfg(not(windows))] { let permissions = std::os::unix::fs::PermissionsExt::from_mode(0o700); fs::set_permissions(&shell, permissions).unwrap(); } let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--shell") .arg(shell) .output() .unwrap(); let stdout = "-cu -cu EXPRESSION\n-cu -cu DEFAULT\n-cu RECIPE\n"; assert_stdout(&output, stdout); } const JUSTFILE_CMD: &str = r#" set shell := ["cmd.exe", "/C"] x := `Echo` recipe: REM foo Echo "{{x}}" "#; /// Test that we can use `set shell` to use cmd.exe on windows #[test] #[cfg_attr(unix, ignore)] fn cmd() { let tmp = temptree! { justfile: JUSTFILE_CMD, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); let stdout = "\\\"ECHO is on.\\\"\r\n"; assert_stdout(&output, stdout); } const JUSTFILE_POWERSHELL: &str = r#" set shell := ["powershell.exe", "-c"] x := `Write-Host "Hello, world!"` recipe: For ($i=0; $i -le 10; $i++) { Write-Host $i } Write-Host "{{x}}" "#; /// Test that we can use `set shell` to use cmd.exe on windows #[test] #[cfg_attr(unix, ignore)] fn powershell() { let tmp = temptree! { justfile: JUSTFILE_POWERSHELL, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); let stdout = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\nHello, world!\n"; assert_stdout(&output, stdout); } #[test] fn shell_args() { Test::new() .arg("--shell-arg") .arg("-c") .justfile( " default: echo A${foo}A ", ) .shell(false) .stdout("AA\n") .stderr("echo A${foo}A\n") .run(); } #[test] fn shell_override() { Test::new() .arg("--shell") .arg("bash") .justfile( " set shell := ['foo-bar-baz'] default: echo hello ", ) .shell(false) .stdout("hello\n") .stderr("echo hello\n") .run(); } #[test] fn shell_arg_override() { Test::new() .arg("--shell-arg") .arg("-cu") .justfile( " set shell := ['foo-bar-baz'] default: echo hello ", ) .stdout("hello\n") .stderr("echo hello\n") .shell(false) .run(); } #[test] fn set_shell() { Test::new() .justfile( " set shell := ['echo', '-n'] x := `bar` foo: echo {{x}} echo foo ", ) .stdout("echo barecho foo") .stderr("echo bar\necho foo\n") .shell(false) .run(); } #[test] fn recipe_shell_not_found_error_message() { Test::new() .justfile( " foo: @echo bar ", ) .shell(false) .args(["--shell", "NOT_A_REAL_SHELL"]) .stderr_regex( "error: Recipe `foo` could not be run because just could not find the shell: .*\n", ) .status(1) .run(); } #[test] fn backtick_recipe_shell_not_found_error_message() { Test::new() .justfile( " bar := `echo bar` foo: echo {{bar}} ", ) .shell(false) .args(["--shell", "NOT_A_REAL_SHELL"]) .stderr_regex("(?s)error: Backtick could not be run because just could not find the shell:.*") .status(1) .run(); } just-1.40.0/tests/shell_expansion.rs000064400000000000000000000060501046102023000155770ustar 00000000000000use super::*; #[test] fn strings_are_shell_expanded() { Test::new() .justfile( " x := x'$JUST_TEST_VARIABLE' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--evaluate", "x"]) .stdout("FOO") .run(); } #[test] fn shell_expanded_strings_must_not_have_whitespace() { Test::new() .justfile( " x := x '$JUST_TEST_VARIABLE' ", ) .status(1) .stderr( " error: Expected '&&', '||', comment, end of file, end of line, '(', '+', or '/', but found string ——▶ justfile:1:8 │ 1 │ x := x '$JUST_TEST_VARIABLE' │ ^^^^^^^^^^^^^^^^^^^^^ ", ) .run(); } #[test] fn shell_expanded_error_messages_highlight_string_token() { Test::new() .justfile( " x := x'$FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--evaluate", "x"]) .status(1) .stderr( " error: Shell expansion failed: error looking key 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' up: environment variable not found ——▶ justfile:1:7 │ 1 │ x := x'$FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ") .run(); } #[test] fn shell_expanded_strings_are_dumped_correctly() { Test::new() .justfile( " x := x'$JUST_TEST_VARIABLE' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--dump"]) .stdout("x := x'$JUST_TEST_VARIABLE'\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_settings() { Test::new() .justfile( " set dotenv-filename := x'$JUST_TEST_VARIABLE' @foo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .env("JUST_TEST_VARIABLE", ".env") .stdout("dotenv-value\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_import_paths() { Test::new() .justfile( " import x'$JUST_TEST_VARIABLE' foo: bar ", ) .write("import.just", "@bar:\n echo BAR") .env("JUST_TEST_VARIABLE", "import.just") .stdout("BAR\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_mod_paths() { Test::new() .justfile( " mod foo x'$JUST_TEST_VARIABLE' ", ) .write("mod.just", "@bar:\n echo BAR") .env("JUST_TEST_VARIABLE", "mod.just") .args(["foo", "bar"]) .stdout("BAR\n") .run(); } #[test] fn shell_expanded_strings_do_not_conflict_with_dependencies() { Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar a b: (foo a 'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar a b: (foo a'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar x b: (foo x 'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); } just-1.40.0/tests/show.rs000064400000000000000000000052721046102023000133710ustar 00000000000000use super::*; #[test] fn show() { Test::new() .arg("--show") .arg("recipe") .justfile( r#"hello := "foo" bar := hello + hello recipe: echo {{hello + "bar" + bar}}"#, ) .stdout( r#" recipe: echo {{ hello + "bar" + bar }} "#, ) .run(); } #[test] fn alias_show() { Test::new() .arg("--show") .arg("f") .justfile("foo:\n bar\nalias f := foo") .stdout( " alias f := foo foo: bar ", ) .run(); } #[test] fn alias_show_missing_target() { Test::new() .arg("--show") .arg("f") .justfile("alias f := foo") .status(EXIT_FAILURE) .stderr( " error: Alias `f` has an unknown target `foo` ——▶ justfile:1:7 │ 1 │ alias f := foo │ ^ ", ) .run(); } #[test] fn show_suggestion() { Test::new() .arg("--show") .arg("hell") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `hell`\nDid you mean `hello`?\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_alias_suggestion() { Test::new() .arg("--show") .arg("fo") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} alias foo := hello a Z="\t z": "#, ) .stderr( " error: Justfile does not contain recipe `fo` Did you mean `foo`, an alias for `hello`? ", ) .status(EXIT_FAILURE) .run(); } #[test] fn show_no_suggestion() { Test::new() .arg("--show") .arg("hell") .justfile( r#" helloooooo a b='B ' c='C': echo {{a}} {{b}} {{c}} a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `hell`\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_no_alias_suggestion() { Test::new() .arg("--show") .arg("fooooooo") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} alias foo := hello a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `fooooooo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_recipe_at_path() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["--show", "foo::bar"]) .stdout("bar:\n @echo MODULE\n") .run(); } #[test] fn show_invalid_path() { Test::new() .args(["--show", "$hello"]) .stderr("error: Invalid module path `$hello`\n") .status(1) .run(); } #[test] fn show_space_separated_path() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["--show", "foo bar"]) .stdout("bar:\n @echo MODULE\n") .run(); } just-1.40.0/tests/slash_operator.rs000064400000000000000000000041141046102023000154300ustar 00000000000000use super::*; #[test] fn once() { Test::new() .justfile("x := 'a' / 'b'") .args(["--evaluate", "x"]) .stdout("a/b") .run(); } #[test] fn twice() { Test::new() .justfile("x := 'a' / 'b' / 'c'") .args(["--evaluate", "x"]) .stdout("a/b/c") .run(); } #[test] fn no_lhs_once() { Test::new() .justfile("x := / 'a'") .args(["--evaluate", "x"]) .stdout("/a") .run(); } #[test] fn no_lhs_twice() { Test::new() .justfile("x := / 'a' / 'b'") .args(["--evaluate", "x"]) .stdout("/a/b") .run(); Test::new() .justfile("x := // 'a'") .args(["--evaluate", "x"]) .stdout("//a") .run(); } #[test] fn no_rhs_once() { Test::new() .justfile("x := 'a' /") .stderr( " error: Expected backtick, identifier, '(', '/', or string, but found end of file ——▶ justfile:1:11 │ 1 │ x := 'a' / │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn default_un_parenthesized() { Test::new() .justfile( " foo x='a' / 'b': echo {{x}} ", ) .stderr( " error: Expected '*', ':', '$', identifier, or '+', but found '/' ——▶ justfile:1:11 │ 1 │ foo x='a' / 'b': │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn no_lhs_un_parenthesized() { Test::new() .justfile( " foo x=/ 'a' / 'b': echo {{x}} ", ) .stderr( " error: Expected backtick, identifier, '(', or string, but found '/' ——▶ justfile:1:7 │ 1 │ foo x=/ 'a' / 'b': │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn default_parenthesized() { Test::new() .justfile( " foo x=('a' / 'b'): echo {{x}} ", ) .stderr("echo a/b\n") .stdout("a/b\n") .run(); } #[test] fn no_lhs_parenthesized() { Test::new() .justfile( " foo x=(/ 'a' / 'b'): echo {{x}} ", ) .stderr("echo /a/b\n") .stdout("/a/b\n") .run(); } just-1.40.0/tests/string.rs000064400000000000000000000223511046102023000137140ustar 00000000000000use super::*; #[test] fn raw_string() { Test::new() .justfile( r#" export EXPORTED_VARIABLE := '\z' recipe: printf "$EXPORTED_VARIABLE" "#, ) .stdout("\\z") .stderr("printf \"$EXPORTED_VARIABLE\"\n") .run(); } #[test] fn multiline_raw_string() { Test::new() .arg("a") .justfile( " string := 'hello whatever' a: echo '{{string}}' ", ) .stdout( "hello whatever ", ) .stderr( "echo 'hello whatever' ", ) .run(); } #[test] fn multiline_backtick() { Test::new() .arg("a") .justfile( " string := `echo hello echo goodbye ` a: echo '{{string}}' ", ) .stdout("hello\ngoodbye\n") .stderr( "echo 'hello goodbye' ", ) .run(); } #[test] fn multiline_cooked_string() { Test::new() .arg("a") .justfile( r#" string := "hello whatever" a: echo '{{string}}' "#, ) .stdout( "hello whatever ", ) .stderr( "echo 'hello whatever' ", ) .run(); } #[test] fn cooked_string_suppress_newline() { Test::new() .justfile( r#" a := """ foo\ bar """ @default: printf %s '{{a}}' "#, ) .stdout( " foobar ", ) .run(); } #[test] fn invalid_escape_sequence() { Test::new() .arg("a") .justfile( r#"x := "\q" a:"#, ) .stderr( "error: `\\q` is not a valid escape sequence ——▶ justfile:1:6 │ 1 │ x := \"\\q\" │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn error_line_after_multiline_raw_string() { Test::new() .arg("a") .justfile( " string := 'hello whatever' + 'yo' a: echo '{{foo}}' ", ) .stderr( "error: Variable `foo` not defined ——▶ justfile:6:11 │ 6 │ echo '{{foo}}' │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn error_column_after_multiline_raw_string() { Test::new() .arg("a") .justfile( " string := 'hello whatever' + bar a: echo '{{string}}' ", ) .stderr( "error: Variable `bar` not defined ——▶ justfile:3:13 │ 3 │ whatever' + bar │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn multiline_raw_string_in_interpolation() { Test::new() .arg("a") .justfile( r#" a: echo '{{"a" + ' ' + "b"}}' "#, ) .stdout( " a b ", ) .stderr( " echo 'a b' ", ) .run(); } #[test] fn error_line_after_multiline_raw_string_in_interpolation() { Test::new() .arg("a") .justfile( r#" a: echo '{{"a" + ' ' + "b"}}' echo {{b}} "#, ) .stderr( "error: Variable `b` not defined ——▶ justfile:5:10 │ 5 │ echo {{b}} │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_raw_string() { Test::new() .arg("a") .justfile( " a b= ': ", ) .stderr( " error: Unterminated string ——▶ justfile:1:6 │ 1 │ a b= ': │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_string() { Test::new() .arg("a") .justfile( r#" a b= ": "#, ) .stderr( r#" error: Unterminated string ——▶ justfile:1:6 │ 1 │ a b= ": │ ^ "#, ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_backtick() { Test::new() .justfile( " foo a=\t`echo blaaaaaah: echo {{a}} ", ) .stderr( r" error: Unterminated backtick ——▶ justfile:1:8 │ 1 │ foo a= `echo blaaaaaah: │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_indented_raw_string() { Test::new() .arg("a") .justfile( " a b= ''': ", ) .stderr( " error: Unterminated string ——▶ justfile:1:6 │ 1 │ a b= ''': │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_indented_string() { Test::new() .arg("a") .justfile( r#" a b= """: "#, ) .stderr( r#" error: Unterminated string ——▶ justfile:1:6 │ 1 │ a b= """: │ ^^^ "#, ) .status(EXIT_FAILURE) .run(); } #[test] fn unterminated_indented_backtick() { Test::new() .justfile( " foo a=\t```echo blaaaaaah: echo {{a}} ", ) .stderr( r" error: Unterminated backtick ——▶ justfile:1:8 │ 1 │ foo a= ```echo blaaaaaah: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn indented_raw_string_contents_indentation_removed() { Test::new() .justfile( " a := ''' foo bar ''' @default: printf '{{a}}' ", ) .stdout( " foo bar ", ) .run(); } #[test] fn indented_cooked_string_contents_indentation_removed() { Test::new() .justfile( r#" a := """ foo bar """ @default: printf '{{a}}' "#, ) .stdout( " foo bar ", ) .run(); } #[test] fn indented_backtick_string_contents_indentation_removed() { Test::new() .justfile( r" a := ``` printf ' foo bar ' ``` @default: printf '{{a}}' ", ) .stdout("\n\nfoo\nbar") .run(); } #[test] fn indented_raw_string_escapes() { Test::new() .justfile( r" a := ''' foo\n bar ''' @default: printf %s '{{a}}' ", ) .stdout( r" foo\n bar ", ) .run(); } #[test] fn indented_cooked_string_escapes() { Test::new() .justfile( r#" a := """ foo\n bar """ @default: printf %s '{{a}}' "#, ) .stdout( " foo bar ", ) .run(); } #[test] fn indented_backtick_string_escapes() { Test::new() .justfile( r" a := ``` printf %s ' foo\n bar ' ``` @default: printf %s '{{a}}' ", ) .stdout("\n\nfoo\\n\nbar") .run(); } #[test] fn shebang_backtick() { Test::new() .justfile( " x := `#!/usr/bin/env sh` ", ) .stderr( " error: Backticks may not start with `#!` ——▶ justfile:1:6 │ 1 │ x := `#!/usr/bin/env sh` │ ^^^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn valid_unicode_escape() { Test::new() .justfile(r#"x := "\u{1f916}\u{1F916}""#) .args(["--evaluate", "x"]) .stdout("🤖🤖") .run(); } #[test] fn unicode_escapes_with_all_hex_digits() { Test::new() .justfile(r#"x := "\u{012345}\u{6789a}\u{bcdef}\u{ABCDE}\u{F}""#) .args(["--evaluate", "x"]) .stdout("\u{012345}\u{6789a}\u{bcdef}\u{ABCDE}\u{F}") .run(); } #[test] fn maximum_valid_unicode_escape() { Test::new() .justfile(r#"x := "\u{10FFFF}""#) .args(["--evaluate", "x"]) .stdout("\u{10FFFF}") .run(); } #[test] fn unicode_escape_no_braces() { Test::new() .justfile("x := \"\\u1234\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: expected unicode escape sequence delimiter `{` but found `1` ——▶ justfile:1:6 │ 1 │ x := "\u1234" │ ^^^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_empty() { Test::new() .justfile("x := \"\\u{}\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: unicode escape sequences must not be empty ——▶ justfile:1:6 │ 1 │ x := "\u{}" │ ^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_requires_immediate_opening_brace() { Test::new() .justfile("x := \"\\u {1f916}\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: expected unicode escape sequence delimiter `{` but found ` ` ——▶ justfile:1:6 │ 1 │ x := "\u {1f916}" │ ^^^^^^^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_non_hex() { Test::new() .justfile("x := \"\\u{foo}\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: expected hex digit [0-9A-Fa-f] but found `o` ——▶ justfile:1:6 │ 1 │ x := "\u{foo}" │ ^^^^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_invalid_character() { Test::new() .justfile("x := \"\\u{BadBad}\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: unicode escape sequence value `BadBad` greater than maximum valid code point `10FFFF` ——▶ justfile:1:6 │ 1 │ x := "\u{BadBad}" │ ^^^^^^^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_too_long() { Test::new() .justfile("x := \"\\u{FFFFFFFFFF}\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: unicode escape sequence starting with `\u{FFFFFFF` longer than six hex digits ——▶ justfile:1:6 │ 1 │ x := "\u{FFFFFFFFFF}" │ ^^^^^^^^^^^^^^^^ "#, ) .run(); } #[test] fn unicode_escape_unterminated() { Test::new() .justfile("x := \"\\u{1f917\"") .args(["--evaluate", "x"]) .status(1) .stderr( r#" error: unterminated unicode escape sequence ——▶ justfile:1:6 │ 1 │ x := "\u{1f917" │ ^^^^^^^^^^ "#, ) .run(); } just-1.40.0/tests/subsequents.rs000064400000000000000000000044571046102023000147760ustar 00000000000000use super::*; #[test] fn success() { Test::new() .justfile( " foo: && bar echo foo bar: echo bar ", ) .stdout( " foo bar ", ) .stderr( " echo foo echo bar ", ) .run(); } #[test] fn failure() { Test::new() .justfile( " foo: && bar echo foo false bar: echo bar ", ) .stdout( " foo ", ) .stderr( " echo foo false error: Recipe `foo` failed on line 3 with exit code 1 ", ) .status(EXIT_FAILURE) .run(); } #[test] fn circular_dependency() { Test::new() .justfile( " foo: && foo ", ) .stderr( " error: Recipe `foo` depends on itself ——▶ justfile:1:9 │ 1 │ foo: && foo │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown() { Test::new() .justfile( " foo: && bar ", ) .stderr( " error: Recipe `foo` has unknown dependency `bar` ——▶ justfile:1:9 │ 1 │ foo: && bar │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_argument() { Test::new() .justfile( " bar x: foo: && (bar y) ", ) .stderr( " error: Variable `y` not defined ——▶ justfile:3:14 │ 3 │ foo: && (bar y) │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn argument() { Test::new() .justfile( " foo: && (bar 'hello') bar x: echo {{ x }} ", ) .stdout( " hello ", ) .stderr( " echo hello ", ) .run(); } #[test] fn duplicate_subsequents_dont_run() { Test::new() .justfile( " a: && b c echo a b: d echo b c: d echo c d: echo d ", ) .stdout( " a d b c ", ) .stderr( " echo a echo d echo b echo c ", ) .run(); } #[test] fn subsequents_run_even_if_already_ran_as_prior() { Test::new() .justfile( " a: b && b echo a b: echo b ", ) .stdout( " b a b ", ) .stderr( " echo b echo a echo b ", ) .run(); } just-1.40.0/tests/summary.rs000064400000000000000000000025251046102023000141040ustar 00000000000000use super::*; #[test] fn summary() { Test::new() .arg("--summary") .justfile( "b: a a: d: c c: b _z: _y _y: ", ) .stdout("a b c d\n") .run(); } #[test] fn summary_sorted() { Test::new() .arg("--summary") .justfile( " b: c: a: ", ) .stdout("a b c\n") .run(); } #[test] fn summary_unsorted() { Test::new() .arg("--summary") .arg("--unsorted") .justfile( " b: c: a: ", ) .stdout("b c a\n") .run(); } #[test] fn summary_none() { Test::new() .arg("--summary") .arg("--quiet") .justfile("") .stdout("\n\n\n") .run(); } #[test] fn no_recipes() { Test::new() .arg("--summary") .stderr("Justfile contains no recipes.\n") .stdout("\n\n\n") .run(); } #[test] fn submodule_recipes() { Test::new() .write("foo.just", "mod bar\nfoo:") .write("bar.just", "mod baz\nbar:") .write("baz.just", "mod biz\nbaz:") .write("biz.just", "biz:") .justfile( " mod foo bar: ", ) .arg("--summary") .stdout("bar foo::foo foo::bar::bar foo::bar::baz::baz foo::bar::baz::biz::biz\n") .run(); } #[test] fn summary_implies_unstable() { Test::new() .write("foo.just", "foo:") .justfile( " mod foo ", ) .arg("--summary") .stdout("foo::foo\n") .run(); } just-1.40.0/tests/tempdir.rs000064400000000000000000000014671046102023000140570ustar 00000000000000use super::*; pub(crate) fn tempdir() -> TempDir { let mut builder = tempfile::Builder::new(); builder.prefix("just-test-tempdir"); if let Some(runtime_dir) = dirs::runtime_dir() { let path = runtime_dir.join("just"); fs::create_dir_all(&path).unwrap(); builder.tempdir_in(path) } else { builder.tempdir() } .expect("failed to create temporary directory") } #[test] fn test_tempdir_is_set() { Test::new() .justfile( " set tempdir := '.' foo: #!/usr/bin/env bash cat just*/foo ", ) .shell(false) .tree(tree! { foo: { } }) .current_dir("foo") .stdout(if cfg!(windows) { " cat just*/foo " } else { " #!/usr/bin/env bash cat just*/foo " }) .run(); } just-1.40.0/tests/test.rs000064400000000000000000000230071046102023000133640ustar 00000000000000use { super::*, pretty_assertions::{assert_eq, StrComparison}, }; pub(crate) struct Output { pub(crate) pid: u32, pub(crate) stdout: String, pub(crate) tempdir: TempDir, } #[must_use] pub(crate) struct Test { pub(crate) args: Vec, pub(crate) current_dir: PathBuf, pub(crate) env: BTreeMap, pub(crate) expected_files: BTreeMap>, pub(crate) justfile: Option, pub(crate) response: Option, pub(crate) shell: bool, pub(crate) status: i32, pub(crate) stderr: String, pub(crate) stderr_regex: Option, pub(crate) stdin: String, pub(crate) stdout: String, pub(crate) stdout_regex: Option, pub(crate) tempdir: TempDir, pub(crate) test_round_trip: bool, pub(crate) unindent_stdout: bool, } impl Test { pub(crate) fn new() -> Self { Self::with_tempdir(tempdir()) } pub(crate) fn with_tempdir(tempdir: TempDir) -> Self { Self { args: Vec::new(), current_dir: PathBuf::new(), env: BTreeMap::new(), expected_files: BTreeMap::new(), justfile: Some(String::new()), response: None, shell: true, status: EXIT_SUCCESS, stderr: String::new(), stderr_regex: None, stdin: String::new(), stdout: String::new(), stdout_regex: None, tempdir, test_round_trip: true, unindent_stdout: true, } } pub(crate) fn arg(mut self, val: &str) -> Self { self.args.push(val.to_owned()); self } pub(crate) fn args<'a>(mut self, args: impl AsRef<[&'a str]>) -> Self { for arg in args.as_ref() { self = self.arg(arg); } self } pub(crate) fn create_dir(self, path: impl AsRef) -> Self { fs::create_dir_all(self.tempdir.path().join(path)).unwrap(); self } pub(crate) fn current_dir(mut self, path: impl AsRef) -> Self { path.as_ref().clone_into(&mut self.current_dir); self } pub(crate) fn env(mut self, key: &str, val: &str) -> Self { self.env.insert(key.to_string(), val.to_string()); self } pub(crate) fn justfile(mut self, justfile: impl Into) -> Self { self.justfile = Some(justfile.into()); self } pub(crate) fn justfile_path(&self) -> PathBuf { self.tempdir.path().join("justfile") } #[cfg(unix)] #[track_caller] pub(crate) fn symlink(self, original: &str, link: &str) -> Self { std::os::unix::fs::symlink( self.tempdir.path().join(original), self.tempdir.path().join(link), ) .unwrap(); self } pub(crate) fn no_justfile(mut self) -> Self { self.justfile = None; self } pub(crate) fn response(mut self, response: Response) -> Self { self.response = Some(response); self.stdout_regex(".*") } pub(crate) fn shell(mut self, shell: bool) -> Self { self.shell = shell; self } pub(crate) fn status(mut self, exit_status: i32) -> Self { self.status = exit_status; self } pub(crate) fn stderr(mut self, stderr: impl Into) -> Self { self.stderr = stderr.into(); self } pub(crate) fn stderr_regex(mut self, stderr_regex: impl AsRef) -> Self { self.stderr_regex = Some(Regex::new(&format!("^(?s){}$", stderr_regex.as_ref())).unwrap()); self } pub(crate) fn stdin(mut self, stdin: impl Into) -> Self { self.stdin = stdin.into(); self } pub(crate) fn stdout(mut self, stdout: impl Into) -> Self { self.stdout = stdout.into(); self } pub(crate) fn stdout_regex(mut self, stdout_regex: impl AsRef) -> Self { self.stdout_regex = Some(Regex::new(&format!("(?s)^{}$", stdout_regex.as_ref())).unwrap()); self } #[allow(unused)] pub(crate) fn test_round_trip(mut self, test_round_trip: bool) -> Self { self.test_round_trip = test_round_trip; self } pub(crate) fn tree(self, mut tree: Tree) -> Self { tree.map(|_name, content| unindent(content)); tree.instantiate(self.tempdir.path()).unwrap(); self } pub(crate) fn unindent_stdout(mut self, unindent_stdout: bool) -> Self { self.unindent_stdout = unindent_stdout; self } pub(crate) fn write(self, path: impl AsRef, content: impl AsRef<[u8]>) -> Self { let path = self.tempdir.path().join(path); fs::create_dir_all(path.parent().unwrap()).unwrap(); fs::write(path, content).unwrap(); self } pub(crate) fn make_executable(self, path: impl AsRef) -> Self { let file = self.tempdir.path().join(path); // Make sure it exists first, as a sanity check. assert!(file.exists(), "file does not exist: {}", file.display()); // Windows uses file extensions to determine whether a file is executable. // Other systems don't care. To keep these tests cross-platform, just make // sure all executables end with ".exe" suffix. assert!( file.extension() == Some("exe".as_ref()), "executable file does not end with .exe: {}", file.display() ); #[cfg(unix)] { let perms = std::os::unix::fs::PermissionsExt::from_mode(0o755); fs::set_permissions(file, perms).unwrap(); } self } pub(crate) fn expect_file(mut self, path: impl AsRef, content: impl AsRef<[u8]>) -> Self { let path = path.as_ref(); self .expected_files .insert(path.into(), content.as_ref().into()); self } } impl Test { #[track_caller] pub(crate) fn run(self) -> Output { fn compare(name: &str, have: T, want: T) -> bool { let equal = have == want; if !equal { eprintln!("Bad {name}: {}", Comparison::new(&have, &want)); } equal } fn compare_string(name: &str, have: &str, want: &str) -> bool { let equal = have == want; if !equal { eprintln!("Bad {name}: {}", StrComparison::new(&have, &want)); } equal } if let Some(justfile) = &self.justfile { let justfile = unindent(justfile); fs::write(self.justfile_path(), justfile).unwrap(); } let stdout = if self.unindent_stdout { unindent(&self.stdout) } else { self.stdout.clone() }; let stderr = unindent(&self.stderr); let mut command = Command::new(executable_path("just")); if self.shell { command.args(["--shell", "bash"]); } let mut child = command .args(&self.args) .envs(&self.env) .current_dir(self.tempdir.path().join(&self.current_dir)) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("just invocation failed"); let pid = child.id(); { let mut stdin_handle = child.stdin.take().expect("failed to unwrap stdin handle"); stdin_handle .write_all(self.stdin.as_bytes()) .expect("failed to write stdin to just process"); } let output = child .wait_with_output() .expect("failed to wait for just process"); let output_stdout = str::from_utf8(&output.stdout).unwrap(); let output_stderr = str::from_utf8(&output.stderr).unwrap(); if let Some(ref stdout_regex) = self.stdout_regex { assert!( stdout_regex.is_match(output_stdout), "Stdout regex mismatch:\n{output_stdout:?}\n!~=\n/{stdout_regex:?}/", ); } if let Some(ref stderr_regex) = self.stderr_regex { assert!( stderr_regex.is_match(output_stderr), "Stderr regex mismatch:\n{output_stderr:?}\n!~=\n/{stderr_regex:?}/", ); } if !compare("status", output.status.code(), Some(self.status)) | (self.stdout_regex.is_none() && !compare_string("stdout", output_stdout, &stdout)) | (self.stderr_regex.is_none() && !compare_string("stderr", output_stderr, &stderr)) { panic!("Output mismatch."); } if let Some(ref response) = self.response { assert_eq!( &serde_json::from_str::(output_stdout) .expect("failed to deserialize stdout as response"), response, "response mismatch" ); } for (path, expected) in &self.expected_files { let actual = fs::read(self.tempdir.path().join(path)).unwrap(); assert_eq!( actual, expected.as_slice(), "mismatch for expected file at path {}", path.display(), ); } if self.test_round_trip && self.status == EXIT_SUCCESS { self.round_trip(); } Output { pid, stdout: output_stdout.into(), tempdir: self.tempdir, } } fn round_trip(&self) { println!("Reparsing..."); let output = Command::new(executable_path("just")) .current_dir(self.tempdir.path()) .arg("--dump") .envs(&self.env) .output() .expect("just invocation failed"); assert!( output.status.success(), "dump failed: {} {:?}", output.status, output, ); let dumped = String::from_utf8(output.stdout).unwrap(); let reparsed_path = self.tempdir.path().join("reparsed.just"); fs::write(&reparsed_path, &dumped).unwrap(); let output = Command::new(executable_path("just")) .current_dir(self.tempdir.path()) .arg("--justfile") .arg(&reparsed_path) .arg("--dump") .envs(&self.env) .output() .expect("just invocation failed"); assert!(output.status.success(), "reparse failed: {}", output.status); let reparsed = String::from_utf8(output.stdout).unwrap(); assert_eq!(reparsed, dumped, "reparse mismatch"); } } pub fn assert_eval_eq(expression: &str, result: &str) { Test::new() .justfile(format!("x := {expression}")) .args(["--evaluate", "x"]) .stdout(result) .unindent_stdout(false) .run(); } just-1.40.0/tests/timestamps.rs000064400000000000000000000010631046102023000145710ustar 00000000000000use super::*; #[test] fn print_timestamps() { Test::new() .justfile( " recipe: echo 'one' ", ) .arg("--timestamp") .stderr_regex(concat!(r"\[\d\d:\d\d:\d\d\] echo 'one'", "\n")) .stdout("one\n") .run(); } #[test] fn print_timestamps_with_format_string() { Test::new() .justfile( " recipe: echo 'one' ", ) .args(["--timestamp", "--timestamp-format", "%H:%M:%S.%3f"]) .stderr_regex(concat!(r"\[\d\d:\d\d:\d\d\.\d\d\d] echo 'one'", "\n")) .stdout("one\n") .run(); } just-1.40.0/tests/undefined_variables.rs000064400000000000000000000033461046102023000164020ustar 00000000000000use super::*; #[test] fn parameter_default_unknown_variable_in_expression() { Test::new() .justfile("foo a=(b+''):") .stderr( " error: Variable `b` not defined ——▶ justfile:1:8 │ 1 │ foo a=(b+''): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_variable_in_unary_call() { Test::new() .justfile( " foo x=env_var(a): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:15 │ 1 │ foo x=env_var(a): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_first_variable_in_binary_call() { Test::new() .justfile( " foo x=env_var_or_default(a, b): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:26 │ 1 │ foo x=env_var_or_default(a, b): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_second_variable_in_binary_call() { Test::new() .justfile( " foo x=env_var_or_default('', b): ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:30 │ 1 │ foo x=env_var_or_default('', b): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_variable_in_ternary_call() { Test::new() .justfile( " foo x=replace(a, b, c): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:15 │ 1 │ foo x=replace(a, b, c): │ ^ ", ) .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/unexport.rs000064400000000000000000000044401046102023000142710ustar 00000000000000use super::*; #[test] fn unexport_environment_variable_linewise() { Test::new() .justfile( " unexport JUST_TEST_VARIABLE @recipe: echo ${JUST_TEST_VARIABLE:-unset} ", ) .env("JUST_TEST_VARIABLE", "foo") .stdout("unset\n") .run(); } #[test] fn unexport_environment_variable_shebang() { Test::new() .justfile( " unexport JUST_TEST_VARIABLE recipe: #!/usr/bin/env bash echo ${JUST_TEST_VARIABLE:-unset} ", ) .env("JUST_TEST_VARIABLE", "foo") .stdout("unset\n") .run(); } #[test] fn duplicate_unexport_fails() { Test::new() .justfile( " unexport JUST_TEST_VARIABLE recipe: echo \"variable: $JUST_TEST_VARIABLE\" unexport JUST_TEST_VARIABLE ", ) .env("JUST_TEST_VARIABLE", "foo") .stderr( " error: Variable `JUST_TEST_VARIABLE` is unexported multiple times ——▶ justfile:6:10 │ 6 │ unexport JUST_TEST_VARIABLE │ ^^^^^^^^^^^^^^^^^^ ", ) .status(1) .run(); } #[test] fn export_unexport_conflict() { Test::new() .justfile( " unexport JUST_TEST_VARIABLE recipe: echo variable: $JUST_TEST_VARIABLE export JUST_TEST_VARIABLE := 'foo' ", ) .stderr( " error: Variable JUST_TEST_VARIABLE is both exported and unexported ——▶ justfile:6:8 │ 6 │ export JUST_TEST_VARIABLE := 'foo' │ ^^^^^^^^^^^^^^^^^^ ", ) .status(1) .run(); } #[test] fn unexport_doesnt_override_local_recipe_export() { Test::new() .justfile( " unexport JUST_TEST_VARIABLE recipe $JUST_TEST_VARIABLE: @echo \"variable: $JUST_TEST_VARIABLE\" ", ) .args(["recipe", "value"]) .stdout("variable: value\n") .run(); } #[test] fn unexport_does_not_conflict_with_recipe_syntax() { Test::new() .justfile( " unexport foo: @echo {{foo}} ", ) .args(["unexport", "bar"]) .stdout("bar\n") .run(); } #[test] fn unexport_does_not_conflict_with_assignment_syntax() { Test::new() .justfile("unexport := 'foo'") .args(["--evaluate", "unexport"]) .stdout("foo") .run(); } just-1.40.0/tests/unstable.rs000064400000000000000000000030351046102023000142210ustar 00000000000000use super::*; #[test] fn set_unstable_true_with_env_var() { for val in ["true", "some-arbitrary-string"] { Test::new() .justfile("# hello") .args(["--fmt"]) .env("JUST_UNSTABLE", val) .status(EXIT_SUCCESS) .stderr_regex("Wrote justfile to `.*`\n") .run(); } } #[test] fn set_unstable_false_with_env_var() { for val in ["0", "", "false"] { Test::new() .justfile("") .args(["--fmt"]) .env("JUST_UNSTABLE", val) .status(EXIT_FAILURE) .stderr_regex("error: The `--fmt` command is currently unstable.*") .run(); } } #[test] fn set_unstable_false_with_env_var_unset() { Test::new() .justfile("") .args(["--fmt"]) .status(EXIT_FAILURE) .stderr_regex("error: The `--fmt` command is currently unstable.*") .run(); } #[test] fn set_unstable_with_setting() { Test::new() .justfile("set unstable") .arg("--fmt") .stderr_regex("Wrote justfile to .*") .run(); } // This test should be re-enabled if we get a new unstable feature which is // encountered in source files. (As opposed to, for example, the unstable // `--fmt` subcommand, which is encountered on the command line.) #[cfg(any())] #[test] fn unstable_setting_does_not_affect_submodules() { Test::new() .justfile( " set unstable mod foo ", ) .write("foo.just", "mod bar") .write("bar.just", "baz:\n echo hello") .args(["foo", "bar"]) .stderr_regex("error: Modules are currently unstable.*") .status(EXIT_FAILURE) .run(); } just-1.40.0/tests/which_function.rs000064400000000000000000000163141046102023000154170ustar 00000000000000use super::*; const HELLO_SCRIPT: &str = "#!/usr/bin/env bash echo hello "; #[test] fn finds_executable() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); Test::with_tempdir(tmp) .justfile("p := which('hello.exe')") .args(["--evaluate", "p"]) .write("hello.exe", HELLO_SCRIPT) .make_executable("hello.exe") .env("PATH", path.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(path.join("hello.exe").display().to_string()) .run(); } #[test] fn prints_empty_string_for_missing_executable() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); Test::with_tempdir(tmp) .justfile("p := which('goodbye.exe')") .args(["--evaluate", "p"]) .write("hello.exe", HELLO_SCRIPT) .make_executable("hello.exe") .env("PATH", path.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .run(); } #[test] fn skips_non_executable_files() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); Test::with_tempdir(tmp) .justfile("p := which('hi')") .args(["--evaluate", "p"]) .write("hello.exe", HELLO_SCRIPT) .make_executable("hello.exe") .write("hi", "just some regular file") .env("PATH", path.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .run(); } #[test] fn supports_multiple_paths() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); let path_var = env::join_paths([ path.join("subdir1").to_str().unwrap(), path.join("subdir2").to_str().unwrap(), ]) .unwrap(); Test::with_tempdir(tmp) .justfile("p := which('hello1.exe') + '+' + which('hello2.exe')") .args(["--evaluate", "p"]) .write("subdir1/hello1.exe", HELLO_SCRIPT) .make_executable("subdir1/hello1.exe") .write("subdir2/hello2.exe", HELLO_SCRIPT) .make_executable("subdir2/hello2.exe") .env("PATH", path_var.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(format!( "{}+{}", path.join("subdir1").join("hello1.exe").display(), path.join("subdir2").join("hello2.exe").display(), )) .run(); } #[test] fn supports_shadowed_executables() { enum Variation { Dir1Dir2, // PATH=/tmp/.../dir1:/tmp/.../dir2 Dir2Dir1, // PATH=/tmp/.../dir2:/tmp/.../dir1 } for variation in [Variation::Dir1Dir2, Variation::Dir2Dir1] { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); let path_var = match variation { Variation::Dir1Dir2 => env::join_paths([ path.join("dir1").to_str().unwrap(), path.join("dir2").to_str().unwrap(), ]), Variation::Dir2Dir1 => env::join_paths([ path.join("dir2").to_str().unwrap(), path.join("dir1").to_str().unwrap(), ]), } .unwrap(); let stdout = match variation { Variation::Dir1Dir2 => format!("{}", path.join("dir1").join("shadowed.exe").display()), Variation::Dir2Dir1 => format!("{}", path.join("dir2").join("shadowed.exe").display()), }; Test::with_tempdir(tmp) .justfile("p := which('shadowed.exe')") .args(["--evaluate", "p"]) .write("dir1/shadowed.exe", HELLO_SCRIPT) .make_executable("dir1/shadowed.exe") .write("dir2/shadowed.exe", HELLO_SCRIPT) .make_executable("dir2/shadowed.exe") .env("PATH", path_var.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(stdout) .run(); } } #[test] fn ignores_nonexecutable_candidates() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); let path_var = env::join_paths([ path.join("dummy").to_str().unwrap(), path.join("subdir").to_str().unwrap(), path.join("dummy").to_str().unwrap(), ]) .unwrap(); let dummy_exe = if cfg!(windows) { "dummy/foo" } else { "dummy/foo.exe" }; Test::with_tempdir(tmp) .justfile("p := which('foo.exe')") .args(["--evaluate", "p"]) .write("subdir/foo.exe", HELLO_SCRIPT) .make_executable("subdir/foo.exe") .write(dummy_exe, HELLO_SCRIPT) .env("PATH", path_var.to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(path.join("subdir").join("foo.exe").display().to_string()) .run(); } #[test] fn handles_absolute_path() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); let abspath = path.join("subdir").join("foo.exe"); Test::with_tempdir(tmp) .justfile(format!("p := which('{}')", abspath.display())) .write("subdir/foo.exe", HELLO_SCRIPT) .make_executable("subdir/foo.exe") .write("pathdir/foo.exe", HELLO_SCRIPT) .make_executable("pathdir/foo.exe") .env("PATH", path.join("pathdir").to_str().unwrap()) .env("JUST_UNSTABLE", "1") .args(["--evaluate", "p"]) .stdout(abspath.display().to_string()) .run(); } #[test] fn handles_dotslash() { let tmp = tempdir(); let path = if cfg!(windows) { tmp.path().into() } else { // canonicalize() is necessary here to account for the justfile prepending // the canonicalized working directory to 'subdir/foo.exe'. tmp.path().canonicalize().unwrap() }; Test::with_tempdir(tmp) .justfile("p := which('./foo.exe')") .args(["--evaluate", "p"]) .write("foo.exe", HELLO_SCRIPT) .make_executable("foo.exe") .write("pathdir/foo.exe", HELLO_SCRIPT) .make_executable("pathdir/foo.exe") .env("PATH", path.join("pathdir").to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(path.join("foo.exe").display().to_string()) .run(); } #[test] fn handles_dir_slash() { let tmp = tempdir(); let path = if cfg!(windows) { tmp.path().into() } else { // canonicalize() is necessary here to account for the justfile prepending // the canonicalized working directory to 'subdir/foo.exe'. tmp.path().canonicalize().unwrap() }; Test::with_tempdir(tmp) .justfile("p := which('subdir/foo.exe')") .args(["--evaluate", "p"]) .write("subdir/foo.exe", HELLO_SCRIPT) .make_executable("subdir/foo.exe") .write("pathdir/foo.exe", HELLO_SCRIPT) .make_executable("pathdir/foo.exe") .env("PATH", path.join("pathdir").to_str().unwrap()) .env("JUST_UNSTABLE", "1") .stdout(path.join("subdir").join("foo.exe").display().to_string()) .run(); } #[test] fn is_unstable() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); Test::with_tempdir(tmp) .justfile("p := which('hello.exe')") .args(["--evaluate", "p"]) .write("hello.exe", HELLO_SCRIPT) .make_executable("hello.exe") .env("PATH", path.to_str().unwrap()) .stderr_regex(r".*The `which\(\)` function is currently unstable\..*") .status(EXIT_FAILURE) .run(); } #[test] fn require_error() { Test::new() .justfile("p := require('asdfasdf')") .args(["--evaluate", "p"]) .stderr( " error: Call to function `require` failed: could not find executable `asdfasdf` ——▶ justfile:1:6 │ 1 │ p := require('asdfasdf') │ ^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn require_success() { let tmp = tempdir(); let path = PathBuf::from(tmp.path()); Test::with_tempdir(tmp) .justfile("p := require('hello.exe')") .args(["--evaluate", "p"]) .write("hello.exe", HELLO_SCRIPT) .make_executable("hello.exe") .env("PATH", path.to_str().unwrap()) .stdout(path.join("hello.exe").display().to_string()) .run(); } just-1.40.0/tests/windows.rs000064400000000000000000000003031046102023000140710ustar 00000000000000use super::*; #[test] fn bare_bash_in_shebang() { Test::new() .justfile( " default: #!bash echo FOO ", ) .stdout("FOO\n") .run(); } just-1.40.0/tests/windows_shell.rs000064400000000000000000000016261046102023000152710ustar 00000000000000use super::*; #[test] fn windows_shell_setting() { Test::new() .justfile( r#" set windows-shell := ["pwsh.exe", "-NoLogo", "-Command"] set shell := ["asdfasdfasdfasdf"] foo: Write-Output bar "#, ) .shell(false) .stdout("bar\r\n") .stderr("Write-Output bar\n") .run(); } #[test] fn windows_powershell_setting_uses_powershell_set_shell() { Test::new() .justfile( r#" set windows-powershell set shell := ["asdfasdfasdfasdf"] foo: Write-Output bar "#, ) .shell(false) .stdout("bar\r\n") .stderr("Write-Output bar\n") .run(); } #[test] fn windows_powershell_setting_uses_powershell() { Test::new() .justfile( r#" set windows-powershell foo: Write-Output bar "#, ) .shell(false) .stdout("bar\r\n") .stderr("Write-Output bar\n") .run(); } just-1.40.0/tests/working_directory.rs000064400000000000000000000172261046102023000161570ustar 00000000000000use super::*; const JUSTFILE: &str = r#" foo := `cat data` linewise bar=`cat data`: shebang echo expression: {{foo}} echo default: {{bar}} echo linewise: `cat data` shebang: #!/usr/bin/env sh echo "shebang:" `cat data` "#; const DATA: &str = "OK"; const WANT: &str = "shebang: OK\nexpression: OK\ndefault: OK\nlinewise: OK\n"; /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn justfile_without_working_directory() -> Result<(), Box> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .arg("--justfile") .arg(tmp.path().join("justfile")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory`, and justfile path has no parent #[test] fn justfile_without_working_directory_relative() -> Result<(), Box> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--justfile") .arg("justfile") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just invokes commands from the directory in which the justfile is /// found #[test] fn change_working_directory_to_search_justfile_parent() -> Result<(), Box> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, subdir: {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("subdir")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8_lossy(&output.stdout); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn justfile_and_working_directory() -> Result<(), Box> { let tmp = temptree! { justfile: JUSTFILE, sub: { data: DATA, }, }; let output = Command::new(executable_path("just")) .arg("--justfile") .arg(tmp.path().join("justfile")) .arg("--working-directory") .arg(tmp.path().join("sub")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn search_dir_child() -> Result<(), Box> { let tmp = temptree! { child: { justfile: JUSTFILE, data: DATA, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("child/") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn search_dir_parent() -> Result<(), Box> { let tmp = temptree! { child: { }, justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("child")) .arg("../") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } #[test] fn setting() { Test::new() .justfile( r#" set working-directory := 'bar' print1: echo "$(basename "$PWD")" [no-cd] print2: echo "$(basename "$PWD")" "#, ) .current_dir("foo") .tree(tree! { foo: {}, bar: {} }) .args(["print1", "print2"]) .stderr( r#"echo "$(basename "$PWD")" echo "$(basename "$PWD")" "#, ) .stdout("bar\nfoo\n") .run(); } #[test] fn no_cd_overrides_setting() { Test::new() .justfile( " set working-directory := 'bar' [no-cd] foo: cat bar ", ) .current_dir("foo") .tree(tree! { foo: { bar: "hello", } }) .stderr("cat bar\n") .stdout("hello") .run(); } #[test] fn working_dir_in_submodule_is_relative_to_module_path() { Test::new() .write( "foo/mod.just", " set working-directory := 'bar' @foo: cat file.txt ", ) .justfile("mod foo") .write("foo/bar/file.txt", "FILE") .arg("foo") .stdout("FILE") .run(); } #[test] fn working_dir_applies_to_backticks() { Test::new() .justfile( " set working-directory := 'foo' file := `cat file.txt` @foo: echo {{ file }} ", ) .write("foo/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_shell_function() { Test::new() .justfile( " set working-directory := 'foo' file := shell('cat file.txt') @foo: echo {{ file }} ", ) .write("foo/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_backticks_in_submodules() { Test::new() .justfile("mod foo") .write( "foo/mod.just", " set working-directory := 'bar' file := `cat file.txt` @foo: echo {{ file }} ", ) .arg("foo") .write("foo/bar/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_shell_function_in_submodules() { Test::new() .justfile("mod foo") .write( "foo/mod.just", " set working-directory := 'bar' file := shell('cat file.txt') @foo: echo {{ file }} ", ) .arg("foo") .write("foo/bar/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn attribute_duplicate() { Test::new() .justfile( " [working-directory('bar')] [working-directory('baz')] foo: ", ) .stderr( "error: Recipe attribute `working-directory` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [working-directory('baz')] │ ^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn attribute() { Test::new() .justfile( " [working-directory('foo')] @qux: echo baz > bar ", ) .create_dir("foo") .expect_file("foo/bar", "baz\n") .run(); } #[test] fn attribute_with_nocd_is_forbidden() { Test::new() .justfile( " [working-directory('foo')] [no-cd] bar: ", ) .stderr( " error: Recipe `bar` has both `[no-cd]` and `[working-directory]` attributes ——▶ justfile:3:1 │ 3 │ bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn setting_and_attribute() { Test::new() .justfile( " set working-directory := 'foo' [working-directory('bar')] @baz: echo bob > fred ", ) .create_dir("foo/bar") .expect_file("foo/bar/fred", "bob\n") .run(); }