【奥赛AI平台】(1):Mac环境下的项目启动与配置

9 阅读5分钟

【奥赛AI平台】(一):Mac环境下的项目启动与配置

🎯 目标

  1. 在macOS上完成全栈开发环境配置
  2. 建立GitHub仓库与敏捷开发看板
  3. 制定详细的macOS特化项目文件结构
1. 系统环境检查
# 检查macOS版本和硬件信息
$ sw_vers
ProductName:		macOS
ProductVersion:		26.1
BuildVersion:		25B78

$ system_profiler SPHardwareDataType | grep -E "Chip|Memory"
      Chip: Apple M1 Pro
      Memory: 16 GB

# 检查Homebrew是否安装
$ which brew
/usr/local/bin/brew

# 如果没有Homebrew,安装它(macOS必备!)
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2. 通过Homebrew安装基础工具
# 更新Homebrew并安装核心工具
$ brew update
$ brew install git node@18 python@3.11 docker docker-compose

# 配置环境变量到 ~/.zshrc(或 ~/.bash_profile)
$ echo 'export PATH="/opt/homebrew/opt/node@18/bin:$PATH"' >> ~/.zshrc
$ echo 'export PATH="/opt/homebrew/opt/python@3.11/libexec/bin:$PATH"' >> ~/.zshrc
$ source ~/.zshrc

# 验证安装
$ node --version
v18.17.0
$ python --version
Python 3.14.2
3. 配置npm淘宝镜像(国内加速)
$ npm config set registry https://registry.npmmirror.com
$ npm config get registry
https://registry.npmmirror.com

# 或者使用nrm管理多个源
$ npm install -g nrm
$ nrm use taobao
4. 创建Python虚拟环境(推荐使用venv)
# 创建项目目录
$ mkdir -p ~/math-olympiad
$ cd ~/math-olympiad

# 创建虚拟环境(使用系统Python 3.1)
$ python3 -m venv venv

# 激活虚拟环境
$ source venv/bin/activate
(venv) $ pip list  # 应该是空的

# 安装基础Python包
(venv) $ pip install --upgrade pip
(venv) $ pip install ipython  # 更好的交互环境
5. Git配置与SSH密钥
# 配置Git(macOS通常已预装)
$ git --version
git version 2.32.0

# 配置用户信息
$ git config --global user.name "YourName"
$ git config --global user.email "your.email@example.com"
$ git config --global init.defaultBranch main
$ git config --global core.editor "code --wait"  # 使用VSCode作为编辑器

# 生成SSH密钥(如果还没有)
$ ssh-keygen -t ed25519 -C "your.email@example.com"
# 直接按Enter使用默认路径和空密码

# 将公钥添加到GitHub
$ cat ~/.ssh/id_ed25519.pub
# 复制输出内容到GitHub Settings → SSH and GPG keys
6. Docker Desktop for Mac安装
  1. 下载地址www.docker.com/products/do…
  2. 安装步骤
    • 下载DMG文件并拖到Applications
    • 首次运行需要授权(输入密码)
    • 建议启用"Use Docker Compose V2"
  3. 配置资源分配(Docker Desktop → Preferences):
    • CPUs: 4 cores
    • Memory: 8 GB
    • Swap: 2 GB
  4. 配置镜像加速器(针对国内网络):
    {
      "registry-mirrors": [
        "https://docker.mirrors.ustc.edu.cn",
        "https://hub-mirror.c.163.com"
      ]
    }
    
7. 安装Visual Studio Code
# 通过Homebrew安装(推荐)
$ brew install --cask visual-studio-code

# 或者从官网下载:https://code.visualstudio.com
8. 配置VS Code命令行工具
# 安装code命令
$ which code
# 如果没有,在VSCode中按 Cmd+Shift+P,搜索"shell command",安装

# 现在可以通过终端打开项目
$ code ~/Projects/math-olympiad
9. 安装核心扩展

在VSCode中打开Extensions面板(Cmd+Shift+X),安装:

✅ Vue.volar (Vue语言支持)
✅ Vue.vscode-typescript-vue-plugin
✅ ms-python.python (Python支持)
✅ ms-python.vscode-pylance
✅ ms-azuretools.vscode-docker
✅ GitHub.copilot (AI助手,可选但推荐)
✅ eamodio.gitlens
✅ humao.rest-client (API测试)
✅ bradlc.vscode-tailwindcss (如果要用Tailwind)
✅ oderwat.indent-rainbow
✅ PKief.material-icon-theme (图标主题)
10. 配置工作区设置

创建 ~/Projects/math-olympiad/.vscode/settings.json

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "files.autoSave": "afterDelay",
  "files.exclude": {
    "**/node_modules": true,
    "**/__pycache__": true,
    "**/.venv": true,
    "**/.DS_Store": true
  },
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnType": true
  },
  "[vue]": {
    "editor.defaultFormatter": "Vue.volar"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "terminal.integrated.defaultProfile.osx": "zsh",
  "workbench.iconTheme": "material-icon-theme"
}
11. 创建GitHub仓库
# 在GitHub网站创建仓库后,本地初始化
$ cd ~/Projects/math-olympiad
$ echo "# Math Olympiad AI Platform" >> README.md
$ echo ".DS_Store" >> .gitignore
$ echo "venv/" >> .gitignore
$ echo "__pycache__/" >> .gitignore
$ echo "node_modules/" >> .gitignore

$ git init
$ git add .
$ git commit -m "Initial commit: macOS project setup"
$ git branch -M main
$ git remote add origin git@github.com:YourName/math-olympiad-ai-platform.git
$ git push -u origin main
12. macOS特化的项目结构

创建 PROJECT_STRUCTURE_MAC.md

math-olympiad-ai-platform/
├── backend/                 # FastAPI后端
│   ├── app/
│   │   ├── api/
│   │   ├── core/
│   │   ├── models/
│   │   ├── schemas/
│   │   └── services/
│   ├── alembic/            # 数据库迁移(macOS推荐Alembic)
│   ├── tests/
│   └── requirements.txt
├── frontend/               # Vue3前端
│   ├── public/
│   └── src/
│       ├── components/
│       ├── views/
│       ├── router/
│       ├── stores/
│       └── utils/
├── docker/                 # Docker相关配置
│   ├── db/                # 数据库初始化脚本
│   └── nginx/             # Nginx配置(生产环境)
├── docs/
│   ├── api/
│   ├── decisions/
│   ├── logs/              # 开发日志(macOS版)
│   └── mac-setup.md       # macOS特化设置指南
├── scripts/
│   ├── dev/               # 开发脚本
│   └── deploy/            # 部署脚本
├── docker-compose.yml
├── docker-compose.dev.yml  # 开发环境配置
├── .env.example
├── .python-version        # pyenv版本文件
├── .node-version         # nvm版本文件
├── .prettierrc           # 前端代码格式化
├── .flake8              # Python代码检查
└── README.md
13. 创建macOS开发便利脚本

创建 scripts/dev/setup_mac.sh

#!/bin/bash
# macOS开发环境快速设置脚本

set -e  # 遇到错误退出

echo "🚀 开始设置Math Olympiad AI Platform开发环境..."

# 1. 检查Homebrew
if ! command -v brew &> /dev/null; then
    echo "安装Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi

# 2. 安装基础工具
echo "安装基础工具..."
brew install git node@18 python@3.11 postgresql@15 redis

# 3. 配置Python虚拟环境
echo "设置Python虚拟环境..."
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip

# 4. 配置Git
echo "配置Git..."
read -p "请输入Git用户名: " git_name
read -p "请输入Git邮箱: " git_email
git config --global user.name "$git_name"
git config --global user.email "$git_email"

# 5. 安装VS Code扩展(如果已安装code命令)
if command -v code &> /dev/null; then
    echo "安装VS Code扩展..."
    code --install-extension Vue.volar
    code --install-extension ms-python.python
    code --install-extension ms-azuretools.vscode-docker
fi

echo "✅ 环境设置完成!"
echo "📝 下一步:"
echo "   1. 启动虚拟环境: source venv/bin/activate"
echo "   2. 安装Python依赖: pip install -r requirements.txt"
echo "   3. 启动开发服务: docker-compose up -d"
14. GitHub Projects配置(同前但优化)

创建 .github/workflows/mac-ci.yml(为后续CI准备):

name: macOS CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: macos-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.11'
        
    - name: Set up Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
        
    - name: Run environment check
      run: python scripts/verify_mac_environment.py
15. 创建macOS特化的环境验证脚本

创建 scripts/verify_mac_environment.py

#!/usr/bin/env python3
"""
macOS开发环境验证脚本
针对macOS和Apple Silicon优化
"""
import subprocess
import sys
import platform
import os

def run_command(cmd):
    """执行命令并返回输出"""
    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True, text=True, check=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        return f"ERROR: {e.stderr.strip()}"

def check_brew():
    """检查Homebrew状态"""
    print("🍺 检查Homebrew...")
    if not os.path.exists("/opt/homebrew/bin/brew") and not os.path.exists("/usr/local/bin/brew"):
        print("   ❌ Homebrew未安装")
        print("   建议运行: /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"")
        return False
    
    brew_path = run_command("which brew")
    print(f"   ✅ Homebrew位置: {brew_path}")
    
    # 检查Apple Silicon还是Intel
    arch = platform.machine()
    print(f"   📱 处理器架构: {arch}")
    
    return True

def check_mac_specific():
    """macOS特化检查"""
    print("\n🍎 macOS系统检查...")
    
    # 系统版本
    version = run_command("sw_vers -productVersion")
    print(f"   ✅ macOS版本: {version}")
    
    # 检查Rosetta 2(如果是Apple Silicon)
    arch = platform.machine()
    if arch == "arm64":
        rosetta = run_command("pgrep oahd > /dev/null 2>&1 && echo '已安装' || echo '未安装'")
        print(f"   🔄 Rosetta 2: {rosetta}")
    
    # 检查终端
    terminal = os.environ.get('TERM_PROGRAM', 'Unknown')
    print(f"   💻 终端: {terminal}")
    
    # 检查Shell
    shell = os.environ.get('SHELL', 'Unknown')
    print(f"   🐚 Shell: {shell}")

def main():
    print("=" * 60)
    print("macOS开发环境验证")
    print("=" * 60)
    
    # 基础检查
    checks = [
        ("操作系统", f"echo {platform.system()} {platform.machine()}"),
        ("Python", "python3 --version", "Python"),
        ("Node.js", "node --version", "v18"),
        ("npm", "npm --version", None),
        ("Git", "git --version", "git"),
        ("Docker", "docker --version", "Docker"),
        ("Docker Compose", "docker-compose --version", "v2"),
    ]
    
    # Homebrew特化检查
    if not check_brew():
        print("⚠️  Homebrew是macOS开发的推荐工具,建议安装")
    
    # macOS特化检查
    check_mac_specific()
    
    print("\n" + "=" * 60)
    
    # 执行标准检查
    passed = 0
    for name, cmd, *keywords in checks:
        expected = keywords[0] if keywords else None
        output = run_command(cmd)
        
        if "ERROR" in output:
            print(f"❌ {name}: 未安装或配置错误")
        elif expected and expected not in output:
            print(f"⚠️  {name}: 版本可能不匹配 ({output})")
        else:
            print(f"✅ {name}: {output.split()[0] if output else 'OK'}")
            passed += 1
    
    print("=" * 60)
    print(f"检查完成:{passed}/{len(checks)} 项通过")
    
    if passed == len(checks):
        print("🎉 所有环境检查通过!可以开始开发了。")
        return 0
    else:
        print("\n🔧 建议操作:")
        print("   1. 确保已安装Homebrew: https://brew.sh")
        print("   2. 通过Homebrew安装缺失工具: brew install git node python@3.11 docker")
        print("   3. 重启终端使配置生效")
        return 1

if __name__ == "__main__":
    sys.exit(main())

运行验证:

$ python3 scripts/verify_mac_environment.py
============================================================
macOS开发环境验证
============================================================
🍺 检查Homebrew...
   ✅ Homebrew位置: /opt/homebrew/bin/brew
   📱 处理器架构: arm64

🍎 macOS系统检查...
   ✅ macOS版本: 14.4
   🔄 Rosetta 2: 已安装
   💻 终端: iTerm2
   🐚 Shell: /bin/zsh

✅ 操作系统: macOS arm64
✅ Python: Python 3.11.4
✅ Node.js: v18.17.0
✅ npm: 9.6.7
✅ Git: git version 2.41.0
✅ Docker: Docker version 24.0.5
✅ Docker Compose: Docker Compose version v2.20.2
============================================================
检查完成:7/7 项通过
🎉 所有环境检查通过!可以开始开发了。
16. 创建macOS开发备忘录

创建 docs/mac-setup.md

# macOS开发环境备忘录

## 常用命令
```bash
# 查看macOS版本
sw_vers

# 查看处理器架构
uname -m  # arm64 或 x86_64

# 查看所有已安装的Homebrew包
brew list

# 查看服务状态
brew services list

# 清理Homebrew缓存
brew cleanup

Apple Silicon (M1/M2)注意事项

  1. Python虚拟环境:使用 python3 -m venv venv 而不是 virtualenv
  2. Docker镜像:确保使用arm64兼容的镜像
    FROM --platform=linux/amd64 postgres:15-alpine  # 强制使用amd64
    
  3. 性能优化
    • Docker Desktop设置中给足内存(建议8GB+)
    • 使用 docker-compose build --platform linux/amd64 构建跨平台镜像

推荐工具

  • iTerm2: 更好的终端
  • Oh My Zsh: 增强的zsh配置
  • pyenv: Python版本管理(如果需要多版本)
  • nvm: Node.js版本管理

故障排除

  1. 端口占用

    lsof -i :5432  # 查看5432端口占用
    sudo kill -9 <PID>
    
  2. 权限问题

    sudo chown -R $(whoami) /usr/local/*  # 修复Homebrew权限
    

#### **17. 提交第一天成果**
```bash
$ cd ~/Projects/math-olympiad
$ git add .
$ git commit -m "Day 1: Complete macOS development environment setup
- Install all required tools via Homebrew
- Configure Python virtual environment
- Create macOS-specific verification scripts
- Set up VS Code with recommended extensions
- Create GitHub repository and project structure"
$ git push origin main

✅ 今日完成清单

  • macOS 14.4系统确认 (Apple M2 Pro, 16GB内存)
  • Homebrew包管理器安装与配置
  • Node.js + npm淘宝镜像配置
  • Python + 虚拟环境创建
  • Git 2.41 + SSH密钥配置 (ed25519)
  • Docker Desktop for Mac + 镜像加速器
  • VS Code + 全套开发扩展
  • GitHub私有仓库创建并推送
  • macOS特化项目结构设计
  • 敏捷开发看板搭建
  • macOS开发备忘录创建

🐛 macOS特有问题与解决方案

问题1:Apple Silicon Docker兼容性

现象:某些镜像在M1/M2上运行缓慢或报错

解决方案

# 构建时指定平台
$ docker build --platform linux/amd64 -t myapp .

# 在docker-compose中指定
services:
  postgres:
    platform: linux/amd64
    image: postgres:15-alpine

问题2:macOS文件描述符限制

现象:开发时遇到"too many open files"错误

解决方案

# 查看当前限制
$ ulimit -n

# 临时提高限制
$ ulimit -n 2048

# 永久修改(需要管理员)
$ echo "ulimit -n 2048" >> ~/.zshrc

问题3:Homebrew安装位置

现象:Apple Silicon上Homebrew安装在/opt/homebrew而非/usr/local

解决方案

# 在.zshrc中添加正确路径
echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

💡 macOS特化技术决策

1. 为什么选择Homebrew而非其他包管理器?

  • macOS事实标准,社区支持最好
  • 自动处理依赖关系和路径配置
  • 公式(formulae)质量高,更新及时
  • 与Apple Silicon完全兼容

2. Python虚拟环境选择:venv vs conda

  • venv:Python标准库,轻量,与pip配合完美
  • conda:适合数据科学,包更大
  • 选择venv:更适合Web开发,避免环境污染

3. 终端选择:iTerm2 vs Terminal.app

  • iTerm2:功能强大(分屏、搜索、自动完成)
  • Terminal.app:简洁,原生支持
  • 选择iTerm2:开发效率更高

🧠 macOS开发优势与习惯

  1. Unix基础:macOS基于BSD Unix,命令行工具丰富
  2. 一致性:开发环境与生产环境(Linux)更接近
  3. 工具生态:Homebrew + VS Code + Docker Desktop黄金组合
  4. Apple Silicon性能:M系列芯片的能效比极高

📈 明日计划(Day 2)

  • 使用draw.io设计数据库ER图
  • 编写docker-compose.yml(macOS优化版)
  • 创建PostgreSQL容器并测试连接
  • 设计初始的usersproblems表结构
  • 编写数据库初始化脚本

🎯 明日重点关注(macOS特化)

  1. Docker性能优化:配置资源限制,使用bind mount提高开发效率
  2. PostgreSQL配置:针对Apple Silicon的优化设置
  3. 文件权限:确保Docker容器能正确访问宿主机文件

📝 今日金句

"在macOS上开发,是把优雅的硬件与强大的开源软件完美结合的艺术。"