本文目录导读:

我来分享几种实用的自动更新依赖库的脚本方案,针对不同语言和场景:
Python (pip/poetry)
使用 pip-tools 自动更新
#!/bin/bash # update-python-deps.sh # 更新 pip 本身 pip install --upgrade pip # 使用 pip-tools 管理依赖 pip install pip-tools # 更新 requirements.in 中的所有依赖 pip-compile --upgrade requirements.in # 安装更新后的依赖 pip-sync requirements.txt # 生成更新报告 echo "=== 更新日志 ===" pip list --outdated
使用 Poetry 自动更新
#!/usr/bin/env python3
# update_poetry_deps.py
import subprocess
import json
from datetime import datetime
def update_dependencies():
print(f"开始更新依赖: {datetime.now()}")
# 获取当前依赖状态
result = subprocess.run(
["poetry", "show", "--latest", "--json"],
capture_output=True, text=True
)
if result.returncode == 0:
deps = json.loads(result.stdout)
outdated = [d for d in deps if d.get("latest-version") != d.get("version")]
print(f"发现 {len(outdated)} 个可更新依赖")
# 逐个更新
for dep in outdated:
name = dep["name"]
old_ver = dep["version"]
new_ver = dep["latest-version"]
print(f"更新 {name}: {old_ver} -> {new_ver}")
subprocess.run(["poetry", "add", f"{name}@{new_ver}"])
# 更新 lock 文件
subprocess.run(["poetry", "lock", "--no-update"])
print("依赖更新完成!")
if __name__ == "__main__":
update_dependencies()
JavaScript/Node.js (npm/yarn/pnpm)
使用 npm-check-updates
#!/bin/bash # update-node-deps.sh # 安装 ncu 工具 npx npm-check-updates # 交互式更新 npx npm-check-updates -u # 或者自动更新所有依赖 npx npm-check-updates -u --target latest # 重新安装依赖 npm install # 更新日志 echo "=== 更新摘要 ===" npm outdated --long
使用 yarn-upgrade-all
// update-yarn-deps.js
const { execSync } = require('child_process');
const fs = require('fs');
async function updateYarnDeps() {
console.log('开始检查 Yarn 依赖更新...');
// 获取过时包列表
try {
const outdated = execSync('yarn outdated --json', {
encoding: 'utf8',
maxBuffer: 50 * 1024 * 1024
});
const packages = outdated
.split('\n')
.filter(line => line.startsWith('{"type":"table"'))
.map(line => JSON.parse(line))
.flatMap(obj => obj.data.body);
if (packages.length > 0) {
console.log(`发现 ${packages.length} 个可更新包`);
// 使用 yarn upgrade-interactive 自动更新
execSync('yarn upgrade-interactive --latest', {
stdio: 'inherit'
});
} else {
console.log('所有依赖已是最新');
}
} catch (error) {
console.error('更新过程中出现错误:', error.message);
}
}
updateYarnDeps();
Java (Maven)
Maven 版本自动更新脚本
#!/bin/bash
# update-maven-deps.sh
# 使用 versions-maven-plugin
mvn versions:display-dependency-updates
# 自动更新 pom.xml 中的版本
mvn versions:use-latest-releases
# 或只更新特定范围
mvn versions:use-latest-releases \
-Dincludes="com.example:*" \
-Dexcludes="com.example:unwanted-artifact"
# 验证更新后的依赖
mvn dependency:tree -Dverbose
# 提交变更
mvn versions:commit
高级更新脚本
#!/usr/bin/env python3
# update_maven_deps.py
import subprocess
import xml.etree.ElementTree as ET
import requests
def check_maven_updates():
# 解析 pom.xml
tree = ET.parse('pom.xml')
root = tree.getroot()
ns = {'m': 'http://maven.apache.org/POM/4.0.0'}
# 查找所有依赖
deps = root.findall('.//m:dependency', ns)
updates = []
for dep in deps:
group_id = dep.find('m:groupId', ns).text
artifact_id = dep.find('m:artifactId', ns).text
version = dep.find('m:version', ns).text if dep.find('m:version', ns) is not None else None
if version:
# 查询 Maven Central 获取最新版本
url = f"https://search.maven.org/solrsearch/select?q=g:{group_id}+AND+a:{artifact_id}&rows=1&wt=json"
try:
response = requests.get(url)
data = response.json()
if data['response']['docs']:
latest = data['response']['docs'][0]['latestVersion']
if latest != version:
updates.append({
'group': group_id,
'artifact': artifact_id,
'current': version,
'latest': latest
})
except Exception as e:
print(f"检查 {group_id}:{artifact_id} 失败: {e}")
return updates
# 执行更新
updates = check_maven_updates()
if updates:
print(f"发现 {len(updates)} 个更新:")
for u in updates:
print(f" {u['group']}:{u['artifact']} {u['current']} -> {u['latest']}")
else:
print("所有依赖已是最新")
Go Modules
#!/bin/bash # update-go-deps.sh # 更新所有依赖到最新版本 go get -u ./... # 或只更新直接依赖 go get -u -d ./... # 清理不必要的依赖 go mod tidy # 验证依赖 go mod verify # 显示更新摘要 echo "=== 依赖状态 ===" go list -u -m all | grep '\['
通用自动化工具
Dependabot 配置文件 (.github/dependabot.yml)
version: 2
updates:
# Python 依赖
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
labels:
- "dependencies"
- "python"
# 限制更新数量
open-pull-requests-limit: 10
# 版本策略
versioning-strategy: "increase-if-necessary"
# npm 依赖
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "monthly"
allow:
- dependency-type: "direct"
- dependency-type: "production"
ignore:
- dependency-name: "react"
versions: [">=17.0.0"]
Renovate 配置文件 (renovate.json)
{
"extends": ["config:base"],
"automerge": true,
"automergeType": "pr",
"major": {
"automerge": false
},
"packageRules": [
{
"matchPackagePatterns": ["*"],
"matchUpdateTypes": ["minor", "patch"],
"automerge": true
}
],
"schedule": ["every weekend"],
"timezone": "Asia/Shanghai"
}
综合更新脚本
多项目管理脚本
#!/bin/bash
# batch-update-deps.sh
# 配置
PROJECTS_DIR="/path/to/projects"
LOG_FILE="update-$(date +%Y%m%d).log"
update_project() {
local project=$1
local type=$2
echo "=== 更新 $project ===" | tee -a $LOG_FILE
cd "$PROJECTS_DIR/$project"
case $type in
python)
pip-compile --upgrade requirements.in 2>&1 | tee -a $LOG_FILE
pip-sync requirements.txt 2>&1 | tee -a $LOG_FILE
;;
node)
npx npm-check-updates -u 2>&1 | tee -a $LOG_FILE
npm install 2>&1 | tee -a $LOG_FILE
;;
java)
mvn versions:use-latest-releases 2>&1 | tee -a $LOG_FILE
;;
go)
go get -u ./... 2>&1 | tee -a $LOG_FILE
;;
esac
# 运行测试
if [ -f "Makefile" ]; then
make test 2>&1 | tee -a $LOG_FILE
fi
}
# 读取项目配置并更新
while IFS=':' read -r project type; do
update_project "$project" "$type"
done << EOF
my-python-app:python
my-node-app:node
my-java-app:java
my-go-app:go
EOF
echo "更新完成! 查看日志: $LOG_FILE"
使用建议
- 安全更新:始终在更新前创建备份或使用版本控制
- 分阶段更新:先更新补丁版本,再更新次版本,最后主版本
- 测试验证:更新后运行完整的测试套件
- 监控更新:使用 CI/CD 管道自动检查并报告更新
- 设置更新策略:根据项目稳定性需求配置更新频率和范围
这些脚本可以根据你的具体需求进行调整和组合使用。