#!/bin/bash # SPDX-License-Identifier: MPL-2.0 set -e # --- Help message --- show_help() { cat << EOF Usage: $0 [OPTION] Format all Rust code in the workspace, including excluded crates and special files. OPTIONS: --check Check if code is formatted (do not modify files) --help Display this help message and exit EXAMPLES: $0 # Format all applicable Rust code $0 --check # Check formatting without modifying files EOF } WORKSPACE_ROOT="$(dirname "$(readlink -f "$0")")/.." EXCLUDED_CRATES=$(sed -n -e 's/#.*//; /^\s*$/d' -e '/^\[workspace\]/,/^\[.*\]/{/exclude = \[/,/\]/p}' "$WORKSPACE_ROOT/Cargo.toml" | grep -v "exclude = \[" | tr -d '", \]') CHECK_MODE=false if [ "$#" -eq 1 ]; then case "$1" in --help) show_help exit 0 ;; --check) CHECK_MODE=true ;; *) echo "Error: Invalid argument '$1'." echo "Run '$0 --help' for usage." exit 1 ;; esac elif [ "$#" -gt 1 ]; then echo "Error: Too many arguments." echo "Run '$0 --help' for usage." exit 1 fi cd $WORKSPACE_ROOT if [ "$CHECK_MODE" = true ]; then cargo fmt --check else cargo fmt fi # Format the 100-line kernel demo as well KERNEL_DEMO_FILE="$WORKSPACE_ROOT/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs" if [ "$CHECK_MODE" = true ]; then rustfmt --check $KERNEL_DEMO_FILE else rustfmt $KERNEL_DEMO_FILE fi for CRATE in $EXCLUDED_CRATES; do CRATE_DIR="$WORKSPACE_ROOT/$CRATE" # Here temporarily skip processing this crate for now considering that this crate # is not currently in use or under development. case "$CRATE" in # `cargo-component` crate currently is pinned to use Rust nightly-2023-02-05 version, # and when using this script in the current Docker environment, it will # additionally download this version of Rust. *cargo-component*) continue ;; # `target/osdk/base` and `target/osdk/test-base` are generated by OSDK and does not need to be formatted. # The directories do not exist before running `make kernel` or `make test`. *target/osdk/base*) continue ;; *target/osdk/test-base*) continue ;; esac if [ -d "$CRATE_DIR" ]; then if [ "$CHECK_MODE" = true ]; then (cd "$CRATE_DIR" && cargo fmt --check) else (cd "$CRATE_DIR" && cargo fmt) fi else echo "Directory for crate $CRATE does not exist" fi done