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
相关推荐
Java后端的Ai之路1 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
2601_962077712 小时前
基于Python与NLP的新闻事件信息抽取实战:从NER到时空标准化
python·nlp·transformers·spacy·新闻事件抽取
JavaPub-rodert2 小时前
LangChain 从入门到 Agent 实战:用 Python 搭建一个真正能调用工具和知识库的 AI 助手
人工智能·python·langchain
郝学胜-神的一滴2 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
m0_380743873 小时前
给 OpenAI API 调用加上模型切换:GPT-5.1 和 Codex 的配置实践
人工智能·python·gpt
2601_962297483 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
“AI国潮设计-小江”4 小时前
Python实战 | SDXL精准控制“普宁英歌舞×星空蛋糕”IP落地,附核心Prompt与商用授权思路
开发语言·人工智能·python·prompt·aigc
公爵爱学习4 小时前
无人机视觉识别前序-Linux-YOLO安装
python·yolo·计算机视觉·conda·无人机
2601_962295334 小时前
使用python实现一个浏览器自动化的脚本
python·脚本·rpa·浏览器自动化·操作
小刘在重生~5 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python