远程GItlab更改host,本地Python脚本替换host

205 阅读1分钟
  • 问题描述 原始地址:192.168.30.10:20003

替换地址:gitlab...com

由于本地项目比较多,一个一个替换地址很麻烦,所以写个脚本自动替换

  • 解决思路 遍历指定目录下的所有文件夹,然后找到 .git文件夹,获取它下面的 config ,替换其中的地址。

  • 代码如下

import os

path = "/Users/mac/Documents/MyProject/xxx" #文件夹目录
old_url = "192.168.30.10:20003"
new_url = "gitlab.***.***.com"

def find_dir(dirPath):
    for parent, dirnames, filenames in os.walk(dirPath):
        for dirname in dirnames:
            if dirname == ".git":
                find_file(parent + "/" + dirname)

def find_file(filePath):
    files = os.listdir(filePath)  # 得到文件夹下的所有文件名称
    for filename in files:  # 遍历文件夹
        if filename == "config":
            alter(filePath + "/" + filename, old_url, new_url)


def alter(file, old_str, new_str):
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:

    """
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                print("old_str, new_str : {0},{1}".format(old_str, new_str))
                line = line.replace(old_str, new_str)
            file_data += line
    with open(file, "w", encoding="utf-8") as f:
        f.write(file_data)

find_dir(path)
  • 打印如下

image.png

  • 重新登陆 你的代码中pull,重新登陆

image.png

登陆后

image.png

python-修改文件内容并保存的3种方法

python获取文件夹下所有文件及os模块方法