在 shell 脚本中获取 rust 项目目录的选项?

Option to get the rust project dir in shell script?

我正在像这样的 Rust 项目中编写一些 shell 脚本来自动生成架构和模型文件:

#!/usr/bin/env bash

set -u
set -e
set -x

diesel_ext --derive Insertable,Queryable,Debug,Serialize,Deserialize,Default \
--add-table-name \
--import-types "rocket::serde::Serialize" \
--import-types "serde::Deserialize" \
--import-types "crate::model::diesel::dolphin::dolphin_schema::*" \
--schema-file src/model/diesel/dolphin/dolphin_schema.rs --model > src/model/diesel/dolphin/dolphin_models.rs

这个脚本工作正常,但在重构项目代码时我无法轻易移动 shell 脚本。有时我需要将 shell 脚本移动到另一个文件夹,并使代码文件结构更清晰易懂。

在不知道项目目录的情况下,我无法移动 shell 脚本,因为当我移动它时,我必须更改 shell 脚本中的文件夹相对路径。

能不能弄个项目目录让这个工作更顺利?就像 Gradle project.dir.

cargo locate-project 将输出项目 Cargo.toml 文件路径的 JSON 描述,您可以通过 jq 进行管道传输并使用 dirname 进行处理找到目录。

然后您可以将其提供给例如cd 切换目录。

cd "$(dirname "$(cargo locate-project | jq -r .root)")"

(可能存在需要处理的错误情况。)