$ ls ~yifei/notes/

`just`,一个现代版的 `make`

Posted on:

Last modified:

我们知道 make 包含了两个主要功能:

  • 构建 C 工程
  • 运行具有依赖关系的任务

而由于 make 的时代太过久远,导致现在用起来会有几个坑爹之处:

  • 声明变量语法奇怪
  • 每次都加 .PHONY 很麻烦
  • 配置 SHELL 也很反直觉
  • 多行命令不在同一个 shell 中运行
  • 必须用 \t 缩进

另一方面,我也只需要运行任务的功能,并不需要编译 c 代码这部分功能。所以就想找一个现代版的 任务执行工具。

Just

Justfile 的语法和 Makefile 基本类似,下面是主要功能的介绍

# 加载 .env 文件
set dotenv-load  #
# 所有变量导出为环境变量,在下面的任务中使用
set export
# 指定 shell
set shell := ["fish", "-c"]

# 变量
tmpdir := `mktemp`  # 读取 shell 命令的结果
version := "0.1"    # 字符串变量
# 使用 / 可以直接组合路径,相当于 a + "/" + "b"
# 使用 + 可以连接字符串
tarball := tmpdir / "awesome" + version + ".tar.gz"
# 直接使用 export 也可以导出环境变量
export http_proxy := localhost:8080

# 函数
# 使用 env_var 函数读取外部环境变量
home_dir := env_var('HOME')
# justfile_directory 读取 justfile 所在路径
# 其他的函数还有 lower_case/trim/uppercase/extension/uuid 等

# 多行字符串
long_string := 'very
long
string
'

# alias
alias b:= build

# 依赖按照顺序执行
all: lint test build

# 命令按照顺序执行,如果一个失败,下一个不会执行
publish:
    # 使用双大括号表示变量
    rm -rf {{tarball}}
    tar cvzf {{tarball}}
    # 用前缀可以忽略该行命令的错误
    -curl -X POST {{tarball}} {{endpoint}}

# 每一行都是一个新的 shell,所以直接 cd 是没用的
foo:
    pwd    # This `pwd` will print the same directory…
    cd bar
    pwd    # …as this `pwd`!

# 不过添加 shebang 之后,就会当作一整个脚本执行
foo:
    #!/usr/bin/env bash
    set -euxo pipefail
    cd bar
    pwd

# 还可以使用 shell 之外的语言!
python:
    #!/usr/bin/env python3
    print("hello world")

echo_home:
    # 可以直接读取外部环境变量
    echo "Home is ${HOME}"

build:
    cargo build

lint:
    cargo lint

# 使用 @ 做前缀可以不打印命令本身
clean:
    @rm -rf build/

使用 just -l 可以按字母顺序列出所有任务,使用 just -u/--unsorted 可以按定义顺序列出,更秒 的是,任务上方的注释也会一并列出。

变量可以在调用的时候重载:

just name=value
just --set name value

just 命令会向上查找到包含 justfile 根目录,就像 git 一样,所以可以在子目录中运行 just.

Just 的缺点

just 不支持按照文件的修改日期来构建项目,也就是说很多时候都要从头构建,这样可用度就大幅 降低了。如果这点也支持的话,真的可以迁移到 just 了。

参考

  1. https://github.com/go-task/task
  2. https://github.com/casey/just
WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站