diff --git a/.lintstagedrc.js b/.lintstagedrc.js --- a/.lintstagedrc.js +++ b/.lintstagedrc.js @@ -1,5 +1,6 @@ const { CLIEngine } = require('eslint'); const { getClangPaths } = require('./scripts/get_clang_paths'); +const { findRustProjectPath } = require('./scripts/get_cargo_path'); const cli = new CLIEngine({}); @@ -58,8 +59,9 @@ }); return 'clang-format -i ' + files.join(' '); }, - 'services/commtest/**/*.rs': function rustFormat(files) { - return 'yarn rust-pre-commit'; + '*.rs': function rustFormat(files) { + const paths = new Set(files.map(findRustProjectPath).filter(Boolean)); + return `yarn rust-pre-commit ${Array.from(paths).join(' ')}`; }, 'services/terraform/*.tf': function checkTerraform(files) { return 'yarn terraform-pre-commit'; diff --git a/scripts/get_cargo_path.js b/scripts/get_cargo_path.js new file mode 100644 --- /dev/null +++ b/scripts/get_cargo_path.js @@ -0,0 +1,12 @@ +// @flow + +const findUp = require('find-up'); + +// finds the path to the parent directory containing a Cargo.toml file for the +// given path. Returns null if no Cargo.toml file is found. +function findRustProjectPath(path) { + const cargoTomlPath = findUp.sync('Cargo.toml', { cwd: path }); + return cargoTomlPath ? cargoTomlPath.replace('/Cargo.toml', '') : null; +} + +module.exports = { findRustProjectPath }; diff --git a/scripts/rust_pre_commit.sh b/scripts/rust_pre_commit.sh --- a/scripts/rust_pre_commit.sh +++ b/scripts/rust_pre_commit.sh @@ -5,17 +5,21 @@ # shellcheck source=/dev/null [[ -r "$HOME"/.cargo/env ]] && source "$HOME"/.cargo/env -PATHS="services/commtest" +if [[ "$#" -eq 0 ]]; then + echo "no Cargo project paths provided" + exit 1 +fi command -v cargo > /dev/null -for directory in $PATHS; do - pushd "$directory" +# iterate over all provided Cargo project paths +for directory in "$@"; do + pushd "$directory" > /dev/null echo "formatting ${directory}..." cargo fmt --all -- --check echo "checking ${directory}..." cargo check - popd # $directory + popd > /dev/null # $directory done echo "done formatting"