git仓删除当前仓且保留嵌套子仓--类似保留特定文件目录

当前git若有损坏需删除重新下载,但其还含有子仓,不能直接删除整体目录。清理方法如下:

分如下两种场景

1、若是子仓当前没有进行任何操作,即子仓可以临时移动

这种比较简单,分如下几步:

step1:找到全部子仓路径(第2中情况中find_all_sub_git即为查找全部git仓路径的方法);

step2: 创建备份目录;

step3:依次将子仓保留目录层move到备份目录;

step4: 删除当前路径;

step5:将备份目录move当前目录。

2、若是子仓当前正在进行操作,如挑单等,即子仓不可移动

这种需正向找到全部需要删除的目录和文件,依次删除。代码实现如下

python 复制代码
import os
import shutil
from pathlib import Path

def remove_git_dir_and_retain_sub_git(dir_path):
    shutil.rmtree(os.path.join(dir_path, ".git"))  # 需先删除,不然影响递归
    remove_list = []
    get_all_remove_list(dir_path, remove_list)
    for sub_remove in remove_list:
        if os.path.isdir(sub_remove):
            shutil.rmtree(sub_remove)
        else:
            os.remove(sub_remove)
            
def get_all_remove_list(dir_path, remove_list):
    //子仓跳过
    if os.path.exists(os.path.join(dir_path, ".git")): 
        return
    //不包含.git仓的目录可以直接删除
    if not find_all_sub_git(dir_path):
        remove_list.append(dir_path)
        return
    //其它包含.git仓的目录需进行递归
    sub_path_list = os.listdir(dir_path)
    for sub_path in sub_path_list:
        sub_full_path = os.path.join(dir_path, sub_path)
        if os.path.isdir(sub_full_path):
            get_all_remove_list(sub_full_path, remove_list)
        else:
            remove_list.append(sub_full_path)

def find_all_sub_git(dir_path):
    keywords = '**/.git'
    p = Path(base_dir)
    files = p.glob(keywords)
    file_list = list(files)
    file_list = [os.fspath(file_path) for file_path in file_list]
    file_list = [file_path for file_path in file_list if os.path.basename(file_path)]
    return file_list
相关推荐
这个人懒得名字都没写4 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_4 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
是毛毛吧5 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
三途河畔人5 小时前
Pytho基础语法_运算符
开发语言·python·入门
独行soc6 小时前
2025年渗透测试面试题总结-275(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
拽着尾巴的鱼儿7 小时前
工具篇:git 分支版本回退
git
番石榴AI8 小时前
java版的ocr推荐引擎——JiaJiaOCR 2.0重磅升级!纯Java CPU推理,新增手写OCR与表格识别
java·python·ocr
时光轻浅,半夏挽歌8 小时前
python不同格式文件的读写方式(json等)
python·json
测试人社区-千羽9 小时前
边缘计算场景下的智能测试挑战
人工智能·python·安全·开源·智能合约·边缘计算·分布式账本
抽象带篮子9 小时前
Pytorch Lightning 框架运行顺序
人工智能·pytorch·python