### Recommended Mise and HK Setup in `mise.toml` Source: https://github.com/jdx/hk/blob/main/docs/mise_integration.md This configuration sets `HK_MISE=1` to enable mise integration and uses a `postinstall` hook to automate HK hook installation. It also defines the necessary tools like `hk` and `pkl`. ```toml [tools] hk = "latest" pkl = "latest" # ... other tools like prettier, actionlint, etc. [env] HK_MISE = 1 [hooks] # Automatically install/update hooks when tools are installed postinstall = "hk install --mise" ``` -------------------------------- ### Install Prerequisites for Benchmarking Source: https://github.com/jdx/hk/blob/main/docs/benchmarks.md Installs necessary tools and dependencies for running the benchmarks using mise and uv. ```bash mise use hyperfine lefthook prettier eslint shfmt jq yq uv tool install pre-commit prek black ruff ``` -------------------------------- ### Install hk using mise Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Install hk using the mise package manager and verify the installation by checking the version. ```sh mise use hk hk --version ``` -------------------------------- ### Install Dependencies with mise Source: https://github.com/jdx/hk/blob/main/docs/contributing.md Install all required tools and dependencies for the hk project using mise. Ensure mise is installed and configured. ```sh mise install ``` -------------------------------- ### Setup bats integration tests Source: https://github.com/jdx/hk/blob/main/CLAUDE.md Standard setup pattern for bats integration test files. ```bash setup() { load 'test_helper/common_setup' _common_setup } ``` -------------------------------- ### Example HK Project Configuration (`hk.pkl`) Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md This example `hk.pkl` file demonstrates how to define custom linters for ESLint and Prettier, including glob patterns for file matching and extending built-in configurations. It also shows how to configure pre-commit hooks with steps like 'prelint', 'postlint', and running defined linters. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" local linters = new Mapping { // linters can be manually defined ["eslint"] { // the files to run the linter on, if no files are matched, the linter will be skipped glob = List("*.js", "*.ts") // a command that returns non-zero to fail the check check = "eslint {{files}}" } // linters can also be specified with the builtins pkl library ["prettier"] = Builtins.prettier // with pkl, builtins can also be extended: ["prettier-yaml"] = (Builtins.prettier) { glob = List("*.yaml", "*.yml") } } hooks { ["pre-commit"] { fix = true // runs the "fix" step of linters to modify files stash = "git" // stashes unstaged changes when running fix steps steps { ["prelint"] { check = "mise run prelint" exclusive = true // blocks other steps from starting until this one finishes } ...linters ["postlint"] { check = "mise run postlint" exclusive = true } } } } ``` -------------------------------- ### Install hk from source Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Install hk directly from source using cargo, the Rust package manager. ```sh cargo install hk ``` -------------------------------- ### Start Development Environment with Vagrant Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-file/README.md Use this command to spin up a new virtual machine and provision it with the necessary prerequisites for development. ```shell user@localhost:~/bats-file$ vagrant up ``` -------------------------------- ### Install pkl CLI with mise Source: https://github.com/jdx/hk/blob/main/docs/pkl_introduction.md To use the pkl CLI backend, install pkl globally using the 'mise' tool. This command ensures the pkl executable is available in your environment. ```sh mise use -g pkl ``` -------------------------------- ### Performance Timing Report Example Source: https://github.com/jdx/hk/blob/main/docs/logging.md Example JSON structure for performance timing reports, including total wall time and per-step details. ```json { "total": { "wall_time_ms": 12456 }, "steps": { "lint": { "wall_time_ms": 4321, "profiles": ["ci", "fast"] }, "fmt": { "wall_time_ms": 2100 }, "typecheck": { "wall_time_ms": 6035 } } } ``` -------------------------------- ### Example: Hiding Temporary Directory Path in Tests Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-file/README.md This setup block defines variables to hide the temporary directory path during test execution. The assertion then uses the transformed path for display on failure. ```bash setup { TEST_TEMP_DIR="$(temp_make)" BATSLIB_FILE_PATH_REM="#${TEST_TEMP_DIR}" BATSLIB_FILE_PATH_ADD='' } @test 'assert_file_exists()' { assert_file_exists "${TEST_TEMP_DIR}/path/to/non-existent-file" } teardown() { temp_del "$TEST_TEMP_DIR" } ``` -------------------------------- ### Basic hk.pkl Configuration Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Defines linters for ESLint and Prettier, and sets up pre-commit and pre-push hooks. This example demonstrates how to import base configurations and define custom steps. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" local linters = new Mapping { // linters can be manually defined ["eslint"] { // the files to run the linter on, if no files are matched, the linter will be skipped // this will filter the staged files and return the subset matching these globs glob = List("*.js", "*.ts") // the command to run that makes no changes check = "eslint {{files}}" // the command to run that fixes the files (used by default) fix = "eslint --fix {{files}}" // optional: files matching these globs will be staged after fix modifies them // defaults to the step's glob when staging is enabled, so usually not needed // stage = List("*.js", "*.ts") } // linters can also be specified with the Builtins pkl library ["prettier"] = Builtins.prettier } hooks { ["pre-commit"] { fix = true // runs the fix step to make modifications stash = "git" // stashes unstaged changes before running fix steps steps = linters } ["pre-push"] { steps = linters } // "fix" and "check" are special steps for `hk fix` and `hk check` commands ["fix"] { fix = true steps = linters } ["check"] { steps = linters // optional: run a report after the hook finishes; HK_REPORT_JSON contains timing JSON report = #"node scripts/upload-timings.js <<<"$HK_REPORT_JSON""# } } ``` -------------------------------- ### Install hk hooks per-repository Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Install hk hooks for a specific repository. This method is useful if you cannot use global installation or want hk to apply only to certain projects. ```sh hk install ``` -------------------------------- ### Install Tools with Mise Source: https://github.com/jdx/hk/blob/main/docs/mise_integration.md Use `mise use` to add project-specific tools to your `mise.toml` file. This ensures consistent tool versions across the development team. ```sh mise use hk mise use jq mise use npm:prettier ``` -------------------------------- ### Install hk hooks globally Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Install hk hooks globally into your ~/.gitconfig. This is the recommended method for Git 2.54+ and applies hooks to all repositories. ```sh hk install --global ``` -------------------------------- ### GET /config/get Source: https://github.com/jdx/hk/blob/main/docs/cli/config/get.md Retrieves the value of a specific configuration key from the HK project settings. ```APIDOC ## GET /config/get ### Description Retrieves a specific configuration value based on the provided key. ### Arguments #### Path Parameters - **KEY** (string) - Required - The configuration key to retrieve. Available keys: jobs, enabled_profiles, disabled_profiles, fail_fast, display_skip_reasons, warnings, exclude, skip_steps, skip_hooks, stage ### Request Example hk config get jobs ### Response #### Success Response (200) - **value** (string/array/boolean) - The value associated with the requested configuration key. ``` -------------------------------- ### Define a Prettier builtin in Pkl Source: https://github.com/jdx/hk/blob/main/docs/why-hk.md Example of a builtin configuration for Prettier using Pkl, defining glob patterns and command execution. ```pkl // This is an entire hk builtin. That's it. prettier = new Config.Step { glob = List("**/*.js", "**/*.ts", "**/*.css", "**/*.json", "**/*.md") check = "prettier --check {{ files }}" check_list_files = "prettier --list-different {{ files }}" fix = "prettier --write {{ files }}" } ``` -------------------------------- ### Create Custom Linter Steps Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Define a custom linter step when a suitable builtin does not exist. This example creates a 'custom-tool' step with 'glob', 'check', 'fix', and 'batch' configurations. ```pkl ["custom-tool"] { glob = List("*.custom") check = "custom-tool --check {{files}}" fix = "custom-tool --fix {{files}}" batch = true // Enable parallel processing } ``` -------------------------------- ### GET /config/dump Source: https://github.com/jdx/hk/blob/main/docs/cli/config/dump.md Retrieves the effective runtime configuration settings in the specified format. ```APIDOC ## GET /config/dump ### Description Print effective runtime settings. Shows the merged configuration from all sources including CLI flags, environment variables, git config, user config, and project config. ### Method GET ### Endpoint /config/dump ### Parameters #### Query Parameters - **format** (string) - Optional - Output format (json or toml). Default: json. ``` -------------------------------- ### Create a temporary directory for a test Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-file/README.md Use `temp_make` within `setup`, `@test`, or `teardown` to create a unique temporary directory. The path is output to stdout and should be captured. ```bash setup() { TEST_TEMP_DIR=$(temp_make) } ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/jdx/hk/blob/main/AGENTS.md Examples of the conventional commit format required for all commit messages and PR titles. Follows the '(): ' structure. ```text fix(step): resolve race condition in file locking ``` ```text feat(check): add --slow flag for expensive linters ``` ```text feat(builtins): add biome linter ``` ```text docs: update pkl configuration examples ``` ```text chore: release 0.5.0 ``` -------------------------------- ### Group Inheritance of Step Settings Source: https://github.com/jdx/hk/blob/main/docs/configuration.md This example demonstrates how a 'frontend' group defines 'dir' and 'prefix' settings that are inherited by its child steps. The 'prettier' step inherits both, while the 'eslint' step overrides the 'dir' setting but still inherits the 'prefix'. ```pkl local frontend = new Group { dir = "packages/frontend" prefix = "mise x --" steps { ["prettier"] = (Builtins.prettier) { batch = true } ["eslint"] = (Builtins.eslint) { dir = "different/path" batch = true } } } ``` -------------------------------- ### Trace Output - Text Mode Example Source: https://github.com/jdx/hk/blob/main/docs/logging.md Human-readable hierarchical output showing spans and timing information. ```text 0.123s INFO Starting check 0.456s ├─ lint::eslint 0.789s │ ├─ Running eslint on 45 files 1.234s │ └─ Complete (478ms) 1.567s └─ Complete (1.444s) ``` -------------------------------- ### Trace Output - JSON Mode Example Source: https://github.com/jdx/hk/blob/main/docs/logging.md Newline-delimited JSON (JSONL) format suitable for programmatic analysis. ```json {"type":"meta","span_schema_version":1,"hk_version":"1.12.1","pid":12345} {"type":"span_start","ts_ns":123456,"id":"span_0","name":"check","attrs":{}} {"type":"span_start","ts_ns":456789,"id":"span_1","name":"lint","attrs":{"step":"eslint"},"parent_id":"span_0"} {"type":"span_end","ts_ns":789012,"id":"span_1"} {"type":"span_end","ts_ns":1234567,"id":"span_0"} ``` -------------------------------- ### Restrict Helper to Setup, Test, or Teardown Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-support/README.md Restricts a helper function's invocation to 'setup', a test function (by name), or 'teardown', including indirect calls. ```shell log_test() { # Check caller. if ! ( batslib_is_caller --indirect 'setup' || batslib_is_caller --indirect "$BATS_TEST_NAME" || batslib_is_caller --indirect 'teardown' ) then echo "Must be called from | batslib_decorate 'ERROR: log_test' | fail return $? fi # Body goes here... } ``` -------------------------------- ### refute_regex failure example Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-assert/README.md This example demonstrates the output when refute_regex fails because the value matches the pattern. It shows the value, pattern, match, and case. ```bash @test 'refute_regex()' { refute_regex 'WhatsApp' 'What.' } -- value matches regular expression -- value : WhatsApp pattern : What. match : Whats case : sensitive -- ``` -------------------------------- ### Inspect hk Configuration Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Use `hk config` commands to view the effective configuration, get specific values, or check configuration source precedence. ```bash hk config dump ``` ```bash hk config get exclude ``` ```bash hk config get skip_steps ``` ```bash hk config sources ``` -------------------------------- ### Import and Use Built-in Linters Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Import the Builtins module and assign linters to hooks in your hk.pkl file. This example shows how to configure 'prettier' and 'eslint' for pre-commit hooks. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" hooks { ["pre-commit"] { steps { ["prettier"] = Builtins.prettier ["eslint"] = Builtins.eslint } } } ``` -------------------------------- ### Run a Specific Hook with HK Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Use `hk run` to explicitly execute a hook, which is useful for local testing. This example shows how to run the `pre-commit` hook. ```sh hk run pre-commit ``` -------------------------------- ### Profile-Based Built-in Configuration Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Configure a builtin linter to run only with specific profiles. This example restricts 'mypy' to run exclusively with the 'python' profile. ```pkl ["mypy"] = (Builtins.mypy) { // Only run with "python" profile profiles = List("python") } ``` -------------------------------- ### Adding Global Hooks via hkrc Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Extend global hooks by adding new steps to your hkrc file. This example adds 'gitleaks' to the 'pre-commit' hook, ensuring it runs on all projects. ```pkl // ~/.config/hk/config.pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" hooks { ["pre-commit"] { steps { ["gitleaks"] { check = "gitleaks git --staged" } } } } ``` -------------------------------- ### Global hkrc Configuration Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Define global hooks and linters in an hkrc file to ensure consistent behavior across all projects. This example shows how to import default configurations and define custom linters and hooks. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" local linters { ["prettier"] = Builtins.prettier ["eslint"] { glob = List("*.js", "*.ts") check = "eslint {{files}}" fix = "eslint --fix {{files}}" } } hooks { ["pre-commit"] { fix = true steps = linters } } ``` -------------------------------- ### Debug Git Hook Issues Source: https://github.com/jdx/hk/blob/main/docs/logging.md Test hooks directly with HK_LOG=debug for detailed output, and use --verbose to check hook installation status. ```bash HK_LOG=debug hk run pre-commit ``` ```bash hk install --verbose ``` -------------------------------- ### Add Dependencies to Built-in Linters Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Specify a dependency for a builtin linter using the 'depends' property. This example configures 'eslint' to run after 'prettier'. ```pkl ["eslint"] = (Builtins.eslint) { // Run after prettier depends = "prettier" } ``` -------------------------------- ### Workspace-Specific Built-in Configuration Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Configure a builtin linter for workspace-specific execution. This example uses 'workspace_indicator' to ensure 'cargo_clippy' only runs in directories with a 'Cargo.toml' and customizes the check command. ```pkl ["cargo_clippy"] = (Builtins.cargo_clippy) { // Only run in directories with Cargo.toml workspace_indicator = "Cargo.toml" // Custom command using workspace check = "cargo clippy --manifest-path {{workspace}}/Cargo.toml" } ``` -------------------------------- ### Build the project Source: https://github.com/jdx/hk/blob/main/CLAUDE.md Use this command to build the project using mise. ```bash mise run build ``` -------------------------------- ### `hk init` - Initialize Project Source: https://github.com/jdx/hk/blob/main/docs/cli/init.md Initializes a new hk.pkl file for a project. This command can be used with various flags to customize the initialization process. ```APIDOC ## `hk init` - Initialize Project ### Description Generates a new hk.pkl file for a project. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters #### Flags - **`-f --force`** (boolean) - Optional - Overwrite existing hk.pkl file. - **`-i --interactive`** (boolean) - Optional - Interactive mode: select linters and hooks manually. - **`--mise`** (boolean) - Optional - Generate a mise.toml file with hk configured. Set HK_MISE=1 to make this default behavior. ### Request Example ```bash hk init -f --interactive ``` ### Response #### Success Response (0) - **hk.pkl file** - Description: A new configuration file for the project. - **mise.toml file** - Description: Generated if the `--mise` flag is used. #### Response Example (No specific response body example provided for CLI commands, but successful execution implies file creation.) ``` -------------------------------- ### Initialize HK Project Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Run this command in your project's root directory to initialize HK and generate the `hk.pkl` configuration file. This automatically sets up the global pre-commit hook. ```sh hk init ``` -------------------------------- ### Pkl Imports Source: https://github.com/jdx/hk/blob/main/docs/pkl_introduction.md Demonstrates how to import code from local and remote Pkl files to share configurations and logic. ```pkl import "./extra.pkl" # do something with `extra` import "https://example.com/remote.pkl" # do something with `remote` ``` -------------------------------- ### Clone hk Repository Source: https://github.com/jdx/hk/blob/main/docs/contributing.md Clone the hk repository and navigate into the project directory. This is the first step in setting up your development environment. ```sh git clone https://github.com/jdx/hk.git cd hk ``` -------------------------------- ### Uninstall hk hooks globally Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Remove the globally installed hk hooks from your ~/.gitconfig. ```sh hk uninstall --global ``` -------------------------------- ### Evaluate Pkl Configuration with pkl CLI Source: https://github.com/jdx/hk/blob/main/docs/pkl_introduction.md Use the pkl CLI to evaluate pkl files and view their output. This is useful for dynamic configuration and debugging. ```sh $ pkl eval hk.pkl hooks { ["pre-commit"] { fix = true steps { ["prelint"] { command = "lint" args = ["--fix"] } } } } ``` -------------------------------- ### Define a Prettier hook in pre-commit Source: https://github.com/jdx/hk/blob/main/docs/why-hk.md Example of configuring a Prettier hook in pre-commit using an external repository. ```yaml # pre-commit: hooks are downloaded from external git repos repos: - repo: https://github.com/pre-commit/mirrors-prettier rev: v3.1.0 hooks: - id: prettier ``` -------------------------------- ### Generate and Run Benchmarks Source: https://github.com/jdx/hk/blob/main/docs/benchmarks.md Commands to generate a synthetic project for benchmarking and then run the benchmarks. The number of files and runs can be customized. ```bash # Generate a synthetic project (~700 files) benchmark/generate-project.sh /tmp/hk-bench # Run benchmarks benchmark/run.sh /tmp/hk-bench ``` ```bash # Customize NUM_JS=500 NUM_PY=500 benchmark/generate-project.sh /tmp/hk-bench RUNS=20 WARMUP=3 benchmark/run.sh /tmp/hk-bench ``` -------------------------------- ### Define Individual Steps in Pkl Source: https://github.com/jdx/hk/blob/main/docs/glossary.md Configure individual linting, formatting, or validation tasks. Specify glob patterns for files, commands for checking/fixing, and dependencies on other steps. ```pkl steps { ["eslint"] { glob = List("*.js", "*.ts") check = "eslint {{files}}" fix = "eslint --fix {{files}}" depends = List("prettier") // Run after prettier } } ``` -------------------------------- ### hk config explain Source: https://github.com/jdx/hk/blob/main/docs/cli/config/explain.md Explains the origin and precedence of a specific configuration key. ```APIDOC ## hk config explain ### Description Explain where a configuration value comes from. Shows the resolved value, its source (env/git/cli/default), and the full precedence chain showing all layers that could affect it. ### Arguments #### - **KEY** (string) - Required - Configuration key to explain ``` -------------------------------- ### Define a tool stub for builtins Source: https://github.com/jdx/hk/blob/main/CLAUDE.md Use this script format within test/builtin_tool_stubs/ to ensure the required tool version is installed via mise. ```bash #!/usr/bin/env -S mise tool-stub version = "2" tool = "aqua:golangci/golangci-lint" ``` -------------------------------- ### JavaScript/TypeScript Project Configuration Source: https://github.com/jdx/hk/blob/main/docs/reference/examples/javascript-project.md This configuration sets up environment variables, defines linters (prettier, eslint, tsc) with batch processing and dependencies, and configures pre-commit, pre-push, check, and fix hooks. ```pkl /// Example configuration for a JavaScript/TypeScript project /// * Uses prettier for formatting /// * Uses eslint for linting /// * Runs type checking with tsc /// * Enables automatic fixes in pre-commit amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" // Configure environment for all tools env { ["NODE_ENV"] = "development" } // Define linters to use across hooks local linters = new Mapping { ["prettier"] = (Builtins.prettier) { // Enable batch processing for performance batch = true // Run prettier after other formatters depends = List("eslint") } ["eslint"] = (Builtins.eslint) { batch = true } ["tsc"] = (Builtins.tsc) { // Type checking doesn't need file locking stomp = true } } hooks { ["pre-commit"] { // Enable automatic fixes fix = true // Stash unstaged changes stash = "git" steps = linters } ["pre-push"] { // Just check, don't fix steps = linters } ["check"] { steps = linters } ["fix"] { fix = true steps = linters } } ``` -------------------------------- ### Pkl List Declaration Source: https://github.com/jdx/hk/blob/main/docs/pkl_introduction.md Illustrates the creation of a simple ordered collection of strings using the List constructor. ```pkl my_list = List("a", "b", "c") ``` -------------------------------- ### Enable Tracing for Performance Analysis Source: https://github.com/jdx/hk/blob/main/docs/logging.md Use the --trace flag or HK_TRACE environment variable to enable tracing. Specify 'json' for programmatic analysis. ```bash hk check --trace ``` ```bash HK_TRACE=1 hk check ``` ```bash HK_TRACE=text hk check ``` ```bash HK_TRACE=json hk check > trace.jsonl ``` ```bash hk check --trace --json > trace.jsonl ``` -------------------------------- ### Configure hk using Git Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Use git config commands to set various hk configurations locally. Supports adding multiple values for keys like 'profile' and 'exclude' using the --add flag. ```bash git config --local hk.jobs 5 ``` ```bash git config --local hk.failFast false ``` ```bash git config --local hk.profile slow ``` ```bash git config --local --add hk.profile fast ``` ```bash git config --local hk.exclude "node_modules" ``` ```bash git config --local --add hk.exclude "**/*.min.js" ``` ```bash git config --local hk.skipSteps "slow-test,flaky-test" ``` ```bash git config --local hk.skipHook "pre-push" ``` ```bash git config --local hk.warnings "missing-profiles" ``` ```bash git config --local hk.hideWarnings "missing-profiles" ``` -------------------------------- ### Organize Steps into Groups in Pkl Source: https://github.com/jdx/hk/blob/main/docs/glossary.md Structure configuration hierarchically by grouping related steps. Use groups to create logical divisions for tasks like 'frontend' or 'backend'. ```pkl steps { ["frontend"] = new Group { steps { ["prettier"] = Builtins.prettier ["eslint"] = Builtins.eslint } } } ``` -------------------------------- ### Debug Configuration Issues Source: https://github.com/jdx/hk/blob/main/docs/logging.md Use verbose output with -v for validation or HK_LOG=debug with --dry-run to see configuration loading and step execution plans. ```bash hk validate -v ``` ```bash HK_LOG=debug hk check --dry-run ``` -------------------------------- ### Customize Built-in Linters Source: https://github.com/jdx/hk/blob/main/docs/builtins.md Customize a builtin linter by overriding its default properties. This example overrides the 'batch' setting to false and specifies 'glob' patterns for 'prettier'. ```pkl ["prettier"] = (Builtins.prettier) { batch = false // Override the default batch setting glob = List("*.js", "*.ts") // Override file patterns } ``` -------------------------------- ### Commit-msg Hook for Validation Source: https://github.com/jdx/hk/blob/main/docs/hooks.md Configures the 'commit-msg' hook to validate the commit message format using 'grep'. It ensures the message starts with 'fix', 'feat', or 'chore'. ```pkl hooks { ["commit-msg"] { steps { ["validate-commit-msg"] { check = "grep -q '^(fix|feat|chore):' {{commit_msg_file}} || exit 1" } } } } ``` -------------------------------- ### Pkl Listing Declaration Source: https://github.com/jdx/hk/blob/main/docs/pkl_introduction.md Demonstrates how to declare a listing, which is used for more complex ordered collections, such as a sequence of steps. ```pkl my_listing = new Listing { new LinterStep { check = "make lint" } new LinterStep { check = "make format" } } ``` -------------------------------- ### Run All Linters and Checks Command Source: https://github.com/jdx/hk/blob/main/AGENTS.md Command to execute all linters and checks across the project. Use this to ensure code quality and style compliance. ```bash hk check --all ``` -------------------------------- ### CLI Command: hk migrate pre-commit Source: https://github.com/jdx/hk/blob/main/docs/cli/migrate/pre-commit.md Migrates an existing pre-commit configuration to an hk.pkl file. ```APIDOC ## CLI Command: hk migrate pre-commit ### Description Migrates from pre-commit to hk. ### Usage `hk migrate pre-commit [FLAGS]` ### Parameters #### Flags - **-c, --config** (string) - Optional - Path to .pre-commit-config.yaml (Default: .pre-commit-config.yaml) - **-f, --force** (boolean) - Optional - Overwrite existing hk.pkl file - **-o, --output** (string) - Optional - Output path for hk.pkl (Default: hk.pkl) - **--hk-pkl-root** (string) - Optional - Root path for hk pkl files. If specified, will use {root}/Config.pkl and {root}/Builtins.pkl ``` -------------------------------- ### Clear Cache Directory in a Test Source: https://github.com/jdx/hk/blob/main/test/README.md Use the '_clear_test_cache' function within a Bats test file to remove the cache directory. This is useful for ensuring tests start with an empty cache. ```bash _clear_test_cache ``` -------------------------------- ### Local Project Hook Replacement Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Completely replace a project's hooks locally by creating an `hk.local.pkl` file. This file is not committed and allows for project-specific overrides. ```pkl // hk.local.pkl (add to .gitignore) amends "./hk.pkl" import "./hk.pkl" as upstream hooks = (upstream.hooks) { ["pre-commit"] { steps { // keep only the steps you want ["gitleaks"] = upstream.hooks["pre-commit"].steps["gitleaks"] } } } ``` -------------------------------- ### User Configuration with hk.pkl Source: https://github.com/jdx/hk/blob/main/docs/configuration.md Define user-specific defaults in `~/.config/hk/config.pkl` using pkl syntax. This file can amend remote configuration files. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" jobs = 4 fail_fast = false exclude = List("node_modules", "dist", "build") skip_steps = List("slow-test") skip_hooks = List("pre-push") ``` -------------------------------- ### Manually configure hk hooks in .gitconfig Source: https://github.com/jdx/hk/blob/main/docs/getting_started.md Manually add hk hook configurations to your global git configuration file (~/.gitconfig). This provides an alternative to running `hk install --global`. ```ini [hook "hk-pre-commit"] command = test "${HK:-1}" = "0" || hk run pre-commit --from-hook "$@" event = pre-commit [hook "hk-pre-push"] command = test "${HK:-1}" = "0" || hk run pre-push --from-hook "$@" event = pre-push [hook "hk-commit-msg"] command = test "${HK:-1}" = "0" || hk run commit-msg --from-hook "$@" event = commit-msg ``` -------------------------------- ### HK Timing JSON Report Structure Source: https://github.com/jdx/hk/blob/main/docs/environment_variables.md Example structure of the JSON timing report generated by HK, including total wall time and detailed step timings with optional profile information. ```json { "total": { "wall_time_ms": 12456 }, "steps": { "lint": { "wall_time_ms": 4321, "profiles": ["ci", "fast"] }, "fmt": { "wall_time_ms": 2100 } } } ``` -------------------------------- ### Aube Trust-Downgrade Error Example Source: https://github.com/jdx/hk/blob/main/pr.md This error occurs when Aube's default trustPolicy=no-downgrade rejects a package version with weaker trust evidence than a previously published version. This specific instance involves nanoid@3.3.14. ```text ERR_AUBE_TRUST_DOWNGRADE × failed to resolve dependencies ╰─▶ trust downgrade for nanoid@3.3.14 (trustPolicy=no-downgrade): earlier published version 5.1.12 had trusted publisher but this version has no trust evidence ``` -------------------------------- ### Create a temporary directory with a custom prefix Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-file/README.md Prefix the temporary directory name with a custom string using the `--prefix` option for better organization. This helps group related temporary directories. ```bash setup() { TEST_TEMP_DIR=$(temp_make --prefix 'myapp-') } ``` -------------------------------- ### Debug Performance Issues with Timing Reports Source: https://github.com/jdx/hk/blob/main/docs/logging.md Generate a timing report using HK_TIMING_JSON and use --trace for detailed timing analysis to identify slow steps. ```bash HK_TIMING_JSON=/tmp/timing.json hk check cat /tmp/timing.json | jq . ``` ```bash hk check --trace ``` -------------------------------- ### Run project tests Source: https://github.com/jdx/hk/blob/main/CLAUDE.md Commands for executing various test suites including Rust unit tests and bats integration tests. ```bash # Run all tests (Rust unit tests + bats integration tests) mise run test # Run only Rust tests mise run test:cargo # Run a single Rust test by name cargo test test_name # Run only bats tests mise run test:bats # Run a specific bats test file mise run test:bats test/check.bats ``` -------------------------------- ### Python Project Configuration Source: https://github.com/jdx/hk/blob/main/docs/reference/examples/python-project.md This snippet defines a comprehensive configuration for a Python project, integrating linters, formatters, and type checkers. It specifies steps for pre-commit hooks, pre-push checks, and general validation, with fail-fast enabled for quicker feedback. ```pkl /// Example configuration for a Python project /// * Uses ruff for fast linting /// * Uses ruff_format for fast formatting /// * Uses mypy for type checking /// * Sorts imports with isort /// * Validates with flake8 amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" local python_linters = new Mapping { // Ruff is a fast Python linter ["ruff"] = (Builtins.ruff) { // Run ruff first as it's the fastest batch = true } // Ruff formatter for code formatting ["ruff_format"] = (Builtins.ruff_format) { depends = "ruff" // Run after ruff } // Black for consistent formatting (alternative to ruff_format) ["black"] = (Builtins.black) { depends = "ruff_format" // Run after ruff_format } // isort for import sorting ["isort"] = (Builtins.isort) { depends = "black" // Run after black } // Type checking with mypy ["mypy"] = (Builtins.mypy) { // Type checking doesn't modify files stomp = true // Only run with "types" profile profiles = List("types", "full") } // Additional validation with flake8 ["flake8"] = (Builtins.flake8) { // Only run in CI profiles = List("ci") } } hooks { ["pre-commit"] { fix = true stash = "git" steps = python_linters } ["pre-push"] { // Include type checking on push steps = python_linters env { ["HK_PROFILES"] = "types" } } ["check"] { steps = python_linters } ["fix"] { fix = true steps = python_linters } } // Enable fail-fast for quicker feedback fail_fast = true ``` -------------------------------- ### Post-checkout Hook for Git LFS Source: https://github.com/jdx/hk/blob/main/docs/hooks.md Sets up the 'post-checkout' hook to run 'git lfs post-checkout' using the provided hook arguments. This is used to restore Git LFS files after a checkout. ```pkl hooks { ["post-checkout"] { steps { ["restore-lfs"] { check = "git lfs post-checkout {{ hook_args }}" } } } } ``` -------------------------------- ### Opt-in to Specific Warning Categories in HK Source: https://github.com/jdx/hk/blob/main/docs/environment_variables.md Configure specific warning categories by listing them in `hk.pkl` or `.hkrc.pkl`. If not specified, no warnings are enabled by default. ```pkl warnings = List("missing-profiles") ``` -------------------------------- ### Define Step Dependencies in Pkl Source: https://github.com/jdx/hk/blob/main/docs/glossary.md Specify that a step must wait for other steps to complete successfully before running. Ensure prerequisites are met by listing dependent steps. ```pkl steps { ["typecheck"] { depends = List("lint", "format") // Wait for lint and format to complete check = "tsc --noEmit" } } ``` -------------------------------- ### Define Custom Linters and Hooks Source: https://github.com/jdx/hk/blob/main/docs/reference/examples/custom-linters.md This configuration defines custom linters for SQL formatting, security scanning, custom build tools, and migration validation. It also sets up pre-commit hooks and a check hook that integrates these custom linters with built-in ones. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" import "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Builtins.pkl" local custom_linters = new Mapping { // Custom SQL formatter ["sql_formatter"] { glob = List("**/*.sql") exclude = List("**/migrations/**") check = "sql-formatter --check {{files}}" fix = "sql-formatter --write {{files}}" batch = true } // Platform-specific security scanner ["security_scan"] { check = new Script { linux = "security-scanner-linux --scan {{files}}" macos = "security-scanner-mac --scan {{files}}" windows = "security-scanner.exe /scan {{files}}" } // Only run if security config exists condition = "test -f .security-config.yml" // Run exclusively to avoid conflicts exclusive = true } // Custom workspace-based build tool ["custom_build"] { workspace_indicator = "build.toml" check = "cd {{workspace}} && custom-build check" fix = "cd {{workspace}} && custom-build fix" // Use check_diff for efficient patching check_diff = "cd {{workspace}} && custom-build diff" } // Interactive migration tool ["migrate"] { glob = List("**/migrations/*.sql") check = "migrate validate {{files}}" fix = "migrate apply {{files}}" // Enable interactive mode for prompts interactive = true } // Custom linter with tests ["custom_validator"] { glob = List("**/*.custom") check = "validator {{files}}" fix = "validator --fix {{files}}" // Define tests for this step tests { ["validates correct syntax"] { run = "check" write { ["{{tmp}}/test.custom"] = #"valid content"# } files = List("{{tmp}}/test.custom") expect { code = 0 } } ["fixes invalid syntax"] { run = "fix" write { ["{{tmp}}/broken.custom"] = #"broken content"# } files = List("{{tmp}}/broken.custom") expect { files { ["{{tmp}}/broken.custom"] = #"broken content"# } } } } } } // Import some builtins and mix with custom local all_linters = new Mapping { ...custom_linters ["prettier"] = Builtins.prettier ["shellcheck"] = Builtins.shellcheck } hooks { ["pre-commit"] { fix = true stash = "patch-file" // Use patch file instead of git stash steps = all_linters } ["check"] { steps = all_linters // Generate a report after checking report = #""" echo "Check completed at $(date)" echo "Results: $HK_REPORT_JSON" | jq '.' """# } } // Show additional skip reasons for debugging display_skip_reasons = List( "profile-not-enabled", "no-files-to-process", "condition-false" ) // Environment variables for all steps env { ["CUSTOM_VALIDATOR_STRICT"] = "true" ["SQL_FORMATTER_CONFIG"] = ".sql-format.yml" } ``` -------------------------------- ### Define Mise Task in HK Config Source: https://github.com/jdx/hk/blob/main/docs/mise_integration.md Integrate mise tasks directly into your HK configuration (`.pkl` file). This allows HK steps to execute mise tasks, leveraging mise's capabilities for dependency management and execution. ```pkl amends "package://github.com/jdx/hk/releases/download/v1.49.0/hk@1.49.0#/Config.pkl" `pre-commit` { ["prelint"] { check = "mise run prelint" exclusive = true // ensures this completes before the next steps } // ... more steps ... } ``` -------------------------------- ### Enable Per-Step Summaries in Text Mode Source: https://github.com/jdx/hk/blob/main/docs/environment_variables.md Set HK_SUMMARY_TEXT to '1' to force summaries to appear for every step when running 'hk' in text mode. This overrides the default behavior where only failed steps show summaries. ```bash HK_SUMMARY_TEXT=1 hk check ``` -------------------------------- ### Pre-commit Hook Configuration Source: https://github.com/jdx/hk/blob/main/docs/hooks.md Configures 'pre-commit' hook with 'cargo-fmt' and 'cargo-clippy' steps. 'check_first' is enabled for both, allowing checks before fixes. ```pkl hooks { fix = true ["pre-commit"] { steps { ["cargo-fmt"] { glob = "*.rs" check_first = true check = "cargo fmt --check" fix = "cargo fmt" } ["cargo-clippy"] { glob = "*.rs" check_first = true check = "cargo clippy" fix = "cargo clippy --fix --allow-dirty --allow-staged" } } } } ``` -------------------------------- ### Define Parallel Steps with Groups Source: https://github.com/jdx/hk/blob/main/docs/configuration.md This snippet shows how to define a 'pre-commit' hook with two parallel groups: 'build' and 'lint'. The 'build' group contains 'tsc -b' and 'cargo build' steps, while the 'lint' group contains 'prettier --check' and 'eslint' steps. These groups run in parallel after previous steps/groups complete. ```pkl hooks { ["pre-commit"] { steps { ["build"] = new Group { steps = new Mapping { ["ts"] = new Step { fix = "tsc -b" } ["rs"] = new Step { fix = "cargo build" } } } // these steps will run in parallel after the build group finishes ["lint"] = new Group { steps = new Mapping { ["prettier"] = new Step { check = "prettier --check {{files}}" } ["eslint"] = new Step { check = "eslint {{files}}" } } } } } } ``` -------------------------------- ### Run All Tests Command Source: https://github.com/jdx/hk/blob/main/AGENTS.md Command to execute all tests, including Rust unit tests and bats integration tests. Use this to ensure code integrity. ```bash mise run test ``` -------------------------------- ### hk util detect-private-key Source: https://github.com/jdx/hk/blob/main/docs/cli/util/detect-private-key.md Detects private keys in the provided files. ```APIDOC ## `hk util detect-private-key` ### Description Detect private keys in files. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters - **FILES** (string) - Required - Files to check ``` -------------------------------- ### Assert File Does Not Exist Source: https://github.com/jdx/hk/blob/main/test/test_helper/bats-file/README.md Use `assert_file_not_exists` to fail if a file exists. The path is displayed on failure. ```bash @test 'assert_file_not_exists() { assert_file_not_exists /path/to/existing-file } ``` -------------------------------- ### Configure Git Hooks in Pkl Source: https://github.com/jdx/hk/blob/main/docs/glossary.md Define custom commands or git hooks that execute a collection of steps. Supports standard git hooks and custom hooks for manual execution. ```pkl hooks { ["pre-commit"] { fix = true stash = "git" steps = linters } } ``` -------------------------------- ### Basic Bats Test Case Source: https://github.com/jdx/hk/blob/main/test/bats/README.md Demonstrates a simple Bats test file with two test cases using `bc` and `dc` for arithmetic operations. Ensure your Bash version is 3.2 or above. ```bash #!/usr/bin/env bats @test "addition using bc" { result="$(echo 2+2 | bc)" [ "$result" -eq 4 ] } @test "addition using dc" { result="$(echo 2 2+p | dc)" [ "$result" -eq 4 ] } ```