遞迴遍歷當前目錄下所有的git倉庫,執行git pull操作

dx2019發表於2024-06-06
import os
import subprocess
from datetime import datetime
#記錄遍歷的時間資訊
record_file = 'gitpull.record'
#最大遍歷深度
max_depth = 3
#是否每次git pull,過後都儲存pull_record檔案
#False會等到遍歷完的時候,以覆蓋的方式一次性寫入檔案。
write_record_when_pull=True
pull_record = {}

class record_obj:
def __init__(self, date, pull_success):
self.date = date
self.pull_success = pull_success

def record_pull_time(directory, max_depth):
if max_depth <= 0:
return
current_date = datetime.now().strftime("%Y-%m")
for sub_dir in os.listdir(directory):
full_path = os.path.join(directory, sub_dir)
if os.path.isdir(full_path):
# 檢查是否已經執行過 git pull
mydata = pull_record.get(sub_dir)
if mydata is not None and mydata.date == current_date:
print(f"Git pull has already been executed in {full_path}. Skipping...")
continue
if os.path.exists(os.path.join(full_path, '.git')):
print(f"Pulling from: {full_path}")
result = subprocess.run(['git', 'pull'], cwd=full_path)
# CompletedProcess(args=['git', 'pull'], returncode=1)
pull_success = result.returncode == 0
if not pull_success:
print(f"Pulling failed from: {full_path}")
pull_record[sub_dir] = record_obj(current_date, pull_success)
if write_record_when_pull:
print(f"Write_record after git pull, append dir:{full_path}")
write_record()
else:
record_pull_time(full_path, max_depth - 1)

def read_record():
if os.path.exists(record_file):
with open(record_file, 'r') as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split(',')
pull_record[parts[0]] = record_obj(parts[1], len(parts) >2 and parts[2] == "True")

def write_record():
# 更新記錄檔案
with open(record_file, 'w') as f:
for subdir, record_obj in pull_record.items():
f.write(f"{subdir},{record_obj.date},{record_obj.pull_success}\n")

if __name__ == "__main__":
read_record()
record_pull_time('.', max_depth)
if not write_record_when_pull:
write_record()
print("Git pull done!")

相關文章