如何配置带Git子模块的R包,实现devtools自动安装?
解决方案
一、Devtools/R包层面:自动执行前置文件复制
1. 利用R包的configure脚本
在repo/pkg目录下创建无后缀的configure文件(Linux/macOS下需执行chmod +x configure赋予可执行权限),将setup脚本里的复制逻辑迁移进来:
#!/bin/bash # 从同级submodule复制指定文件到src目录 cp ../submodule/path/to/file1 src/ cp ../submodule/path/to/target_dir/* src/
用户运行devtools::install_git("你的仓库地址")时,devtools会触发R包构建流程,自动执行configure脚本完成文件复制,再进行编译安装。
2. R脚本配合DESCRIPTION配置
若偏好用R编写逻辑,在repo/pkg/inst/scripts下创建pre_install.R:
# pre_install.R source_files <- list.files("../submodule/path/to/source", full.names = TRUE) target_dir <- file.path("src", "dest_dir") dir.create(target_dir, recursive = TRUE, showWarnings = FALSE) file.copy(source_files, target_dir, overwrite = TRUE)
然后在repo/pkg/DESCRIPTION中添加:
Build: Rscript inst/scripts/pre_install.R
devtools在构建包前会自动执行该R脚本,完成文件迁移。
二、Git子模块层面:无需复制文件
1. 稀疏检出子模块指定内容
通过Git稀疏检出仅拉取submodule中需要的文件,避免克隆整个子模块,再在pkg/src创建符号链接指向目标内容(Windows下需管理员权限创建符号链接):
- 进入submodule目录:
cd repo/submodule - 启用稀疏检出:
git config core.sparseCheckout true - 在
.git/info/sparse-checkout中添加需要的路径:path/to/needed/file1 path/to/needed/dir/ - 拉取指定内容:
git read-tree -mu HEAD - 回到
pkg/src创建符号链接:ln -s ../../submodule/path/to/needed/dir dest_dir
2. 嵌套子模块到pkg目录
直接将submodule中需要的目录作为独立子模块添加到repo/pkg/src下:
cd repo/pkg/src git submodule add https://子模块仓库地址.git dest_dir # 切换到需要的版本 cd dest_dir git checkout 指定提交哈希值 cd ../.. git add .gitmodules src/dest_dir git commit -m "添加子模块目标目录到src"
用户克隆仓库时会自动拉取pkg/src/dest_dir的内容,devtools安装时可直接使用该目录下的文件,无需额外复制。
内容的提问来源于stack exchange,提问作者optimizationguy
相关产品推荐
相关产品推荐

