a-cloud-all/.devops/scripts/npm.py

92 lines
2.6 KiB
Python
Raw Normal View History

2026-01-10 15:15:45 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NPM 打包和复制模块
"""
import os
import subprocess
import shutil
from pathlib import Path
from .log import Logger
def run_npm(work_dir, npm_commands, source_dir, target_dir):
"""
执行 NPM 打包和复制
参数
work_dir: 执行 npm 命令的目录
npm_commands: 执行的命令字符串
source_dir: 复制的源目录
target_dir: 复制的目标目录
返回
bool: 成功返回 True失败返回 False
"""
try:
# 转换为绝对路径
work_dir = Path(work_dir).resolve()
Logger.separator()
Logger.info("开始 NPM 打包")
Logger.separator()
Logger.info(f"执行目录: {work_dir}")
Logger.info(f"NPM 命令: {npm_commands}")
# 检查目录是否存在
if not work_dir.exists():
Logger.error(f"目录不存在: {work_dir}")
return False
# 执行 NPM 命令
2026-01-10 15:21:06 +08:00
if not Logger.run_command(npm_commands, work_dir):
2026-01-10 15:15:45 +08:00
Logger.error("NPM 打包失败")
return False
Logger.info("NPM 打包成功")
# 复制构建产物
Logger.separator()
Logger.info("开始复制构建产物")
Logger.separator()
source_full_path = work_dir / source_dir
Logger.info(f"源目录: {source_full_path}")
Logger.info(f"目标目录: {target_dir}")
# 检查源目录是否存在
if not source_full_path.exists():
Logger.error(f"源目录不存在: {source_full_path}")
return False
# 清空目标目录(保留 .gitkeep
target_path = Path(target_dir)
if target_path.exists():
Logger.info(f"清空目标目录: {target_dir}")
for item in target_path.iterdir():
if item.name != '.gitkeep':
if item.is_dir():
shutil.rmtree(item)
else:
item.unlink()
else:
target_path.mkdir(parents=True, exist_ok=True)
# 复制目录内容
Logger.info(f"复制目录内容...")
for item in source_full_path.iterdir():
dest = target_path / item.name
if item.is_dir():
shutil.copytree(item, dest, dirs_exist_ok=True)
else:
shutil.copy2(item, dest)
Logger.info("构建产物复制成功")
Logger.info("NPM 打包和复制完成")
return True
except Exception as e:
Logger.error(f"NPM 打包异常: {e}")
return False