#!/usr/bin/env bash # DMS管理平台 · 本地启动脚本(macOS / Linux / Windows Git Bash 均可) # # 用法: # ./scripts/run.sh 正常启动(默认开热更新,监听 0.0.0.0 供局域网访问) # PORT=8771 ./scripts/run.sh 换端口 # HOST=127.0.0.1 ./scripts/run.sh 只监听本机(默认是 0.0.0.0,同机可写 http://本机IP:端口) # DEV=0 ./scripts/run.sh 关闭热更新 # NO_OPEN=1 ./scripts/run.sh 启动后不打开浏览器 # AUTO_INSTALL=0 ./scripts/run.sh 缺环境时不尝试自动安装,只打印安装命令 # # 环境要求由脚本自动兜底: # 1. 找 Python 3.10+(找不到时按 AUTO_INSTALL=1 尝试用系统包管理器安装) # 2. 建项目内 .venv,缺依赖时自动 pip install -r requirements.txt(多源重试) # 3. 缺 .env 时从 .env.example 生成,建好 data/ 目录,首次运行自动建库 # 4. 端口已被占用时直接提示访问地址,不重复起进程 set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT" log() { printf '%s\n' "$*"; } warn() { printf '!! %s\n' "$*" >&2; } die() { printf '!! %s\n' "$*" >&2; exit 1; } # 读取 .env 里的单值配置(不 source,避免特殊字符被执行) env_get() { [ -f .env ] || return 0 sed -n "s/^[[:space:]]*$1[[:space:]]*=//p" .env | tail -1 | sed 's/[[:space:]]*$//' } is_windows() { case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) return 0 ;; *) return 1 ;; esac } run_root() { if [ "$(id -u)" = "0" ]; then "$@" elif command -v sudo >/dev/null 2>&1; then # 交互式终端允许 sudo 提示密码;非交互(systemd / CI)时不要卡住等密码 if [ -t 0 ] || sudo -n true 2>/dev/null; then sudo "$@" else return 1 fi else return 1 fi } # ---------- 配置 ---------- PORT="${PORT:-$(env_get PORT)}" PORT="${PORT:-8770}" # 默认监听所有网卡:局域网同事用 http://<本机IP>: 直接访问(无 TLS,仅限内网) HOST="${HOST:-$(env_get HOST)}" HOST="${HOST:-0.0.0.0}" DEV="${DEV:-$(env_get DEV)}" DEV="${DEV:-1}" export DEV NO_OPEN="${NO_OPEN:-0}" AUTO_INSTALL="${AUTO_INSTALL:-1}" PIP_INDEX_URL="${PIP_INDEX_URL:-$(env_get PIP_INDEX_URL)}" echo "==> DMS管理平台" # ---------- 1. 找一个可用的 Python 3.10+ ---------- PY_SYS="" find_python() { local c for c in "${PYTHON:-}" python3 python; do [ -n "$c" ] || continue command -v "$c" >/dev/null 2>&1 || continue if "$c" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 10) else 1)' >/dev/null 2>&1; then PY_SYS="$(command -v "$c")" return 0 fi done return 1 } # 自动装 Python:只在明确缺解释器时触发,且需要包管理器 / 管理员权限 install_python() { [ "$AUTO_INSTALL" = "1" ] || return 1 log "==> 未找到 Python 3.10+,尝试自动安装" case "$(uname -s)" in Darwin) if command -v brew >/dev/null 2>&1; then brew install python@3.12 && return 0 fi warn "macOS 需要先装 Homebrew(https://brew.sh)或从 python.org 安装 Python 3.10+" ;; Linux) if command -v dnf >/dev/null 2>&1; then run_root dnf install -y python3 python3-pip && return 0 elif command -v yum >/dev/null 2>&1; then run_root yum install -y python3 python3-pip && return 0 elif command -v apt-get >/dev/null 2>&1; then run_root apt-get update && run_root apt-get install -y python3 python3-venv python3-pip && return 0 elif command -v apk >/dev/null 2>&1; then run_root apk add --no-cache python3 py3-pip && return 0 fi ;; *) ;; esac return 1 } if ! find_python; then if install_python; then find_python || die "Python 安装后仍不可用,请手动安装 Python 3.10+ 后重试" else die "没有找到 Python 3.10+。请先安装: macOS : brew install python@3.12 或 https://www.python.org/downloads/ Ubuntu/Debian : sudo apt install -y python3 python3-venv python3-pip RHEL/openEuler : sudo dnf install -y python3 python3-pip 然后重新执行:./scripts/run.sh" fi fi log " 系统 Python:$PY_SYS ($("$PY_SYS" -V 2>&1))" # ---------- 2. 端口占用检查(已在运行就直接给地址,省得重复启动) ---------- port_busy() { "$PY_SYS" - "$PORT" <<'PY' >/dev/null 2>&1 import socket, sys s = socket.socket() s.settimeout(1.5) sys.exit(0 if s.connect_ex(("127.0.0.1", int(sys.argv[1]))) == 0 else 1) PY } health_url="http://127.0.0.1:${PORT}/health" if port_busy; then if command -v curl >/dev/null 2>&1 && curl -fsS --max-time 2 "$health_url" >/dev/null 2>&1; then echo "==> 端口 ${PORT} 上已有 DMS 服务在运行" echo " 看板地址: http://127.0.0.1:${PORT}" echo " (要重启请先在原窗口按 Ctrl+C,或执行:lsof -ti:${PORT} | xargs kill)" exit 0 fi die "端口 ${PORT} 已被其他程序占用。换一个端口:PORT=8771 ./scripts/run.sh 或找出占用进程:lsof -ti:${PORT} | xargs kill" fi # ---------- 3. .env 与数据目录 ---------- if [ ! -f .env ]; then cp .env.example .env log "==> 已从 .env.example 生成 .env(AI Key、管理员密码按需修改)" fi mkdir -p data/uploads data/exports data/import # ---------- 4. 项目内虚拟环境(缺依赖自动安装) ---------- VENV_DIR="$ROOT/.venv" if is_windows; then VENV_PY="$VENV_DIR/Scripts/python.exe" else VENV_PY="$VENV_DIR/bin/python" fi # 兼容在另一种 shell 下建好的 .venv if [ ! -x "$VENV_PY" ]; then for cand in "$VENV_DIR/bin/python" "$VENV_DIR/Scripts/python.exe"; do if [ -x "$cand" ]; then VENV_PY="$cand"; break; fi done fi install_venv_support() { [ "$AUTO_INSTALL" = "1" ] || return 1 case "$(uname -s)" in Linux) if command -v apt-get >/dev/null 2>&1; then run_root apt-get update && run_root apt-get install -y python3-venv elif command -v dnf >/dev/null 2>&1; then run_root dnf install -y python3-pip elif command -v yum >/dev/null 2>&1; then run_root yum install -y python3-pip elif command -v apk >/dev/null 2>&1; then run_root apk add --no-cache python3 py3-pip else return 1 fi ;; *) return 1 ;; esac } if [ ! -x "$VENV_PY" ]; then log "==> 创建虚拟环境:.venv" if ! "$PY_SYS" -m venv "$VENV_DIR" >/tmp/dms_venv.log 2>&1; then warn "创建虚拟环境失败,尝试补齐 python3-venv ..." install_venv_support || true # 删掉半成品再重试,否则 venv 会认为目录已存在但不可用 case "$VENV_DIR" in */.venv) if [ -d "$VENV_DIR" ]; then rm -rf "$VENV_DIR"; fi ;; esac if ! "$PY_SYS" -m venv "$VENV_DIR"; then warn "虚拟环境创建失败,日志见 /tmp/dms_venv.log" die "请手动安装 venv 支持后重试: Ubuntu/Debian : sudo apt install -y python3-venv RHEL/openEuler : sudo dnf install -y python3-pip 或者删掉 .venv 后重跑 ./scripts/run.sh" fi fi if is_windows; then VENV_PY="$VENV_DIR/Scripts/python.exe"; else VENV_PY="$VENV_DIR/bin/python"; fi fi log " 虚拟环境:$VENV_PY" DEPS_CHECK='import fastapi, uvicorn, sqlalchemy, pydantic, httpx, openpyxl, multipart' deps_ok() { "$VENV_PY" -c "$DEPS_CHECK" >/dev/null 2>&1; } install_deps() { local indexes=() idx args if ! "$VENV_PY" -m pip --version >/dev/null 2>&1; then log "==> 虚拟环境里没有 pip,尝试 ensurepip 补齐" "$VENV_PY" -m ensurepip --upgrade >/dev/null 2>&1 || die "虚拟环境缺少 pip,请删掉 .venv 后重跑 ./scripts/run.sh" fi if [ -n "$PIP_INDEX_URL" ]; then indexes=("$PIP_INDEX_URL") else # 先尊重本机 pip 配置,失败再换国内镜像 indexes=("" "https://pypi.tuna.tsinghua.edu.cn/simple" "https://mirrors.aliyun.com/pypi/simple") fi for idx in "${indexes[@]}"; do args=(install --disable-pip-version-check --timeout 20 --retries 2 -r requirements.txt) if [ -n "$idx" ]; then args+=(-i "$idx") log "==> 安装依赖:$idx" else log "==> 安装依赖(pip 默认源)" fi if "$VENV_PY" -m pip "${args[@]}"; then return 0 fi warn "该源安装失败,换下一个源重试" done return 1 } REQ_HASH="$(cksum requirements.txt 2>/dev/null | awk '{print $1 "-" $2}')" DEPS_STAMP="$VENV_DIR/.requirements.cksum" NEED_INSTALL=0 if ! deps_ok; then NEED_INSTALL=1 elif [ ! -f "$DEPS_STAMP" ] || [ "$(cat "$DEPS_STAMP" 2>/dev/null)" != "$REQ_HASH" ]; then # requirements.txt 变过(新增/升级依赖)时重装一次;pip 本身是幂等的 NEED_INSTALL=1 fi if [ "$NEED_INSTALL" = "1" ]; then log "==> 安装/更新运行依赖(首次约 1~2 分钟)" if ! install_deps; then die "依赖安装失败。可以手动执行: $VENV_PY -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple 或指定镜像:PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple ./scripts/run.sh" fi deps_ok || die "依赖装完仍无法 import,请检查 requirements.txt 与 Python 版本" printf '%s\n' "$REQ_HASH" > "$DEPS_STAMP" fi log " 依赖检查:OK" # ---------- 4.5 前端:装依赖 + 构建(nex.config.yaml 标准栈:npm + Vite)---------- # 后端只托管 web/dist 的构建产物;没构建时 app/main.py 退回 web/legacy(改造前的零构建版), # 所以缺 node 的机器也能先把服务跑起来,只是界面是旧版。 # WEB=0 跳过前端构建(用现有 dist / legacy) # WEB=1 需要时才构建(默认) WEB=force 每次都重建 WEB="${WEB:-$(env_get WEB)}" WEB="${WEB:-1}" NPM_REGISTRY="${NPM_REGISTRY:-$(env_get NPM_REGISTRY)}" NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmmirror.com}" need_build() { [ "${WEB}" = "0" ] && ${ log " 前端构建:跳过(WEB=0)"; return 1; } [ -f web/dist/index.html ] || return 0 [ "${WEB}" = "force" ] && return 0 # dist 比任何源文件旧就重建(配置 / src / lockfile) [ -z "$(find web/src web/index.html web/vite.config.ts web/tsconfig.json web/package-lock.json -newer web/dist/index.html 2>/dev/null | head -1)" ] && ${ log " 前端构建:已是最新,跳过"; return 1; } return 0 } if ! command -v npm >/dev/null 2>&1; then if [ -f web/dist/index.html ]; then warn "未找到 npm(需 Node 20+):直接用现有前端构建产物 web/dist" else warn "未找到 npm 且没有 web/dist:界面退回零构建旧版(web/legacy)。装好 Node 再跑本脚本即切回新版。" fi elif need_build; then if [ ! -d web/node_modules ]; then log "==> 安装前端依赖(首次约 1~2 分钟,源:${NPM_REGISTRY})" # 网络盘 / SMB 挂载上 chmod 会被拒(EPERM),这时退一步用 --no-bin-links 装(下面构建时有对应兜底) ( cd web && npm ci --no-audit --no-fund --registry "${NPM_REGISTRY}" 2>/dev/null \ || npm ci --no-audit --no-fund --no-bin-links --registry "${NPM_REGISTRY}" 2>/dev/null \ || npm install --no-audit --no-fund --registry "${NPM_REGISTRY}" \ || npm install --no-audit --no-fund --no-bin-links --registry "${NPM_REGISTRY}" ) \ || die "前端依赖安装失败。手动执行:cd web && npm ci --registry ${NPM_REGISTRY}" fi log "==> 构建前端(Vite)" if [ -x web/node_modules/.bin/vite ] || [ -f web/node_modules/.bin/vite ]; then ( cd web && npm run build ) || die "前端构建失败:cd web && npm run build 看报错" else # --no-bin-links 装的包没有 node_modules/.bin,直接调入口脚本,效果与 npm run build 相同 ( cd web && node node_modules/typescript/bin/tsc --noEmit && node node_modules/vite/bin/vite.js build ) \ || die "前端构建失败:cd web && node node_modules/vite/bin/vite.js build 看报错" fi log " 前端构建:OK(web/dist)" fi # ---------- 5. 首次运行:建表 + 预置分类 ---------- if [ ! -f data/board.db ]; then log "==> 首次运行,初始化数据库" "$VENV_PY" scripts/init_db.py fi # ---------- 6. 启动 ---------- RELOAD_ARGS=() if [ "$DEV" = "1" ]; then RELOAD_ARGS=(--reload --reload-include "*.js" --reload-include "*.css" --reload-include "*.html" --reload-include ".env") fi open_url() { local url="$1" [ "$NO_OPEN" = "1" ] && return 0 case "$(uname -s)" in Darwin) open "$url" >/dev/null 2>&1 || true ;; Linux) if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v xdg-open >/dev/null 2>&1; then xdg-open "$url" >/dev/null 2>&1 || true fi ;; MINGW*|MSYS*|CYGWIN*) cmd.exe /c start "" "$url" >/dev/null 2>&1 || true ;; esac } URL="http://127.0.0.1:${PORT}" # 探测本机局域网 IP(UDP connect 不发包,只挑默认路由的源地址) LAN_IP="$("$PY_SYS" - <<'PY' 2>/dev/null || true import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("10.255.255.255", 1)) print(s.getsockname()[0]) except Exception: pass finally: s.close() PY )" echo "==> 启动服务: $URL" if [ "$HOST" = "0.0.0.0" ] && [ -n "$LAN_IP" ]; then echo " 局域网访问: http://${LAN_IP}:${PORT} (监听 0.0.0.0;HOST=127.0.0.1 可改回仅本机)" fi echo " API 文档: $URL/api/docs" echo " 热更新: $([ "$DEV" = "1" ] && echo 开启 || echo 关闭)" echo " 停止服务: Ctrl+C" echo if [ "$NO_OPEN" != "1" ]; then ( sleep 3; open_url "$URL" ) & fi exec "$VENV_PY" -m uvicorn app.main:app --host "$HOST" --port "$PORT" \ ${RELOAD_ARGS[@]+"${RELOAD_ARGS[@]}"}