和 make 一样,just 是构建工具的一种,可以通过和 make 类似的语法自由构建 justfile,而后完成 build、run、test 等等各种任务。但与 make 不同的是,just 专注于作为命令运行器(command runner),而非文件构建系统,因此它不关心文件的时间戳和依赖关系,语法也更加简洁直观。
just 的主要优势:
语法比 Makefile 更简洁,错误信息更友好
支持 Linux、macOS、Windows 跨平台使用
可以加载 .env 文件中的环境变量
支持列出可用的 recipes(任务)
支持参数、默认值、条件表达式等特性
支持选择不同的 shell(bash、powershell、python 等)
安装
macOS
brew install just
Windows
# 使用 scoop scoop install just
# 使用 winget winget install Casey.Just
# 使用 cargo cargo install just
Linux
# Debian/Ubuntu sudo apt install just
# Arch Linux sudo pacman -S just
# 使用 cargo(通用方式) cargo install just
安装完成后验证:
$ just --version just 1.40.0
快速开始
在项目根目录创建一个名为 justfile(无扩展名)的文件:
# 构建项目 build: cargo build --release
# 运行项目 run: cargo run
# 运行测试 test: cargo test
然后在终端中运行:
$ just build # 执行 build 任务 $ just run # 执行 run 任务 $ just test# 执行 test 任务 $ just # 执行第一个任务(build)
just 不带参数时会执行 justfile 中的第一个 recipe。
基础语法
Recipe(任务)
Recipe 是 just 中的基本单位,类似于 Makefile 中的 target。格式为 recipe 名称后跟一个冒号,下面缩进的每一行都是要执行的命令:
hello: echo "Hello, World!"
注意:justfile 中的缩进必须使用4个空格或者Tab,不能混用。默认情况下推荐使用4个空格。
每一行命令默认都会先打印命令本身,然后再执行。如果不想打印命令,可以在命令前加 @:
hello: @echo "Hello, World!"
也可以反过来,在 recipe 名称前加 @ 使整个 recipe 静默:
@hello: echo "Hello, World!"
如果想全局静默,可以在文件开头设置:
set quiet
hello: echo "Hello, World!"
依赖
一个 recipe 可以依赖其他 recipe,依赖会在当前 recipe 之前执行:
build: clean cargo build --release
clean: rm -rf target
执行 just build 时,会先执行 clean,再执行 build。
多个依赖用空格分隔:
all: clean build test echo "All done!"
clean: rm -rf target
build: cargo build
test: cargo test
依赖也可以传递参数:
default: (build "release")
build mode: echo "Building in {{mode}} mode"
参数
Recipe 可以接受参数:
greet name: echo "Hello, {{name}}!"
$ just greet World Hello, World!
参数可以设置默认值:
greet name="World": echo "Hello, {{name}}!"
$ just greet # Hello, World! $ just greet Alice # Hello, Alice!
使用 + 表示接受一个或多个参数(可变参数):
test +files: cargo test {{files}}
$ just test test_a test_b test_c
使用 * 表示接受零个或多个参数:
run *args: cargo run {{args}}
变量
可以在 justfile 顶层定义变量:
version := "1.0.0" build_dir := "target"
build: echo "Building version {{version}}" cargo build --release --target-dir {{build_dir}}
变量也支持通过反引号执行命令来赋值:
git_hash := `git rev-parse --short HEAD` date := `date +%Y-%m-%d`