旧项目建立远程git仓库
已有本地项目如何初始化 Git 并推送到远程仓库,包括处理大文件和脏目录的方法
#type / howto
#status / growing
#tech / ops
旧项目建立远程git仓库
目标
为已有本地项目创建远程 Git 仓库,统一管理代码版本。适用于:
- 从官方仓库拉取的开源项目,做了自定义修改后需要独立管理
- 手动维护的项目需要纳入版本控制
- 项目目录已被污染(含大量依赖、编译产物),需要提取核心源码
前置条件
- 已安装 Git
- 已注册 GitHub / GitLab / Gitee 等平台账号
- 了解项目目录中哪些是源码、哪些是依赖/产物
步骤
方案一:全新项目(目录干净)
# 1. 进入项目目录
cd /path/to/your/project
# 2. 初始化 Git
git init
# 3. 创建 .gitignore(排除不需要跟踪的文件)
# 根据项目类型选择模板:https://github.com/github/gitignore
# 4. 添加文件并提交
git add .
git commit -m "Initial commit"
# 5. 添加远程仓库
git remote add origin https://github.com/yourname/yourrepo.git
# 6. 推送
git push -u origin main
方案二:项目目录被污染(如 6.9G 脏目录)
当项目目录包含大量依赖、编译产物时,直接 git add . 会把垃圾文件也提交进去。
步骤:
- 分析目录结构,识别哪些是源码、哪些是垃圾:
# 查看各目录大小
du -sh */ | sort -rh
# 查看大文件
find . -type f -size +10M | head -20
- 创建
.gitignore,排除依赖和产物目录:
node_modules/
dist/
build/
__pycache__/
*.pyc
.venv/
vendor/
*.log
.DS_Store
- 使用 git diff overlay 方法提取修改(从官方仓库 fork 的场景):
# 方法一:在干净目录初始化,只复制修改过的文件
mkdir clean-repo && cd clean-repo
git init
# 从脏目录中手动挑选源码文件复制过来
# 方法二:如果知道官方仓库地址
git clone https://github.com/original/repo.git clean-repo
cd clean-repo
# 将本地修改的文件覆盖进来
cp -r /path/to/dirty/repo/src/ ./src/
git add -A && git commit -m "Apply local modifications"
- 清理历史中的大文件(如果误提交了):
# 使用 git-filter-repo(推荐)
pip install git-filter-repo
git filter-repo --path-glob '*.mp4' --invert-paths
# 或使用 BFG Repo-Cleaner
java -jar bfg.jar --strip-blobs-bigger-than 10M
GitHub / GitLab / Gitee 平台差异
| 操作 | GitHub | GitLab | Gitee |
|---|---|---|---|
| 创建仓库 | github.com/new | gitlab.com/projects/new | gitee.com/projects/new |
| 默认分支 | main | main(可配置) | master / main |
| 大文件 | Git LFS(5GB 限制) | Git LFS | Git LFS(5GB 限制) |
| 私有仓库 | 免费 | 免费 | 免费(5人限制) |
已有 Git 历史时的处理
如果项目之前跟踪过官方仓库的历史:
# 方法一:清除历史,从当前状态重新开始
git checkout --orphan fresh-main
git add -A
git commit -m "Initial commit (clean history)"
git branch -D main
git branch -m main
git push -f origin main
# 方法二:保留历史但断开与原仓库的关联
git remote remove origin
git remote add origin https://github.com/yourname/yourrepo.git
git push -u origin main
验证
-
git remote -v显示正确的远程仓库地址 -
git status工作区干净,无未跟踪的大文件 - 远程仓库页面能看到正确的文件结构
-
.gitignore生效:node_modules/、dist/等目录未被跟踪 - 仓库大小合理(不含依赖和编译产物)
常见问题
Q: 推送时提示「repository not found」? A: 确认远程仓库已创建、URL 正确、有推送权限。HTTPS 方式需要输入用户名和 Personal Access Token(GitHub 已不支持密码认证)。
Q: 项目太大推不上去?
A: GitHub 单文件限制 100MB,仓库建议不超过 1GB。大文件使用 Git LFS:git lfs install && git lfs track "*.psd"。或排除大文件目录。
Q: 如何选择 main 还是 master 作为默认分支?
A: GitHub 默认使用 main,Gitee 默认使用 master。建议统一使用 main,在平台设置中修改默认分支名。
Q: 忽略文件已添加但仍在跟踪?
A: .gitignore 只对未跟踪的文件生效。已跟踪的文件需要先取消跟踪:git rm -r --cached node_modules/,然后重新提交。
[!info] related notes git-diff-overlay-method