node.js实现批量修改git项目的数据源

在项目开发过程中,大型项目会分块,每一块都会拥有一个git地址,当想切换git地址的域名时,如果手动一个一个去修改对我们来说费时费力的事情,如果能有一个脚本,一次性批量修改,可以给大家节省很多时间成本。

一般来讲,git源切换只是修改了域名,项目名称基本不会变化

**步骤1:**引入对应模块

javascript 复制代码
// 引入对应模块
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

**步骤2:**声明新旧域名、搜索目录 常量并赋值

javascript 复制代码
// 旧域名和新域名
const OLD_DOMAIN = 'http://xxx.xxx.xxx.xxx/';
const NEW_DOMAIN = 'http://xxx.xxx.xxx.xxx/';

// 要搜索的目录
const SEARCH_DIR = '.'; // 当前目录,可以修改为其他目录

**步骤3:**定义一个函数,用于遍历当前目录下的所有项目,当然,你可以根据文件夹名称进行过滤

javascript 复制代码
// 查找 Git 仓库并切换远程 URL
function changeGitRemotesInFolders(dir) {
    fs.readdirSync(dir).forEach(file => {
        const fullPath = path.join(dir, file);
        if(!fullPath.includes('.vscode') && !fullPath.includes('node_modules')){
          const stats = fs.statSync(fullPath);
          if (stats.isDirectory()) {
            if (fs.existsSync(path.join(fullPath, '.git'))) {
              // 这是一个 Git 仓库
              changeGitRemote(fullPath);
            }
          }
        }
    });
}

**步骤4:**逐个修改项目git地址(注意:进入一个文件夹执行修改命令后,需要退出当前文件夹,回到上一级目录,不然可能会出现找不到下一个项目的报错提示)

process.chdir(folderPath); // 修改当前工作目录

process.chdir('..'); // 返回上一级目录

javascript 复制代码
// 切换 Git 远程仓库 URL(只替换域名)
function changeGitRemote(folderPath) {
  try {
    process.chdir(folderPath);
    // 获取当前远程仓库的 URL
    const remoteUrl = execSync('git config --get remote.origin.url').toString().trim();
    // 检查是否需要替换域名
    if (remoteUrl.includes(OLD_DOMAIN)) {
        const newRemoteUrl = remoteUrl.replace(OLD_DOMAIN, NEW_DOMAIN);
        // 设置新的远程仓库 URL
        execSync(`git remote set-url origin ${newRemoteUrl}`);
        console.log(`Successfully changed remote URL for ${folderPath} from ${remoteUrl} to ${newRemoteUrl}`);
    } else {
        console.log(`No need to change remote URL for ${folderPath} (current URL: ${remoteUrl})`);
    }
    // process.chdir(process.cwd()); // 理论上这里不需要,因为 process.chdir 是对当前进程的修改,但为清晰起见还是加上
    process.chdir('..');
  } catch (error) {
    console.error(`Error processing ${folderPath}:`, error);
  }
}

完整代码

javascript 复制代码
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 旧域名和新域名
const OLD_DOMAIN = 'http://xxx.xxx.xxx.xxx/';
const NEW_DOMAIN = 'http://xxx.xxx.xxx.xxx/';

// 要搜索的目录
const SEARCH_DIR = '.'; // 当前目录,可以修改为其他目录

// 查找 Git 仓库并切换远程 URL
function changeGitRemotesInFolders(dir) {
  fs.readdirSync(dir).forEach(file => {
    const fullPath = path.join(dir, file);
    if(!fullPath.includes('.vscode') && !fullPath.includes('node_modules')){
      const stats = fs.statSync(fullPath);
      if (stats.isDirectory()) {
        if (fs.existsSync(path.join(fullPath, '.git'))) {
          // 这是一个 Git 仓库
          changeGitRemote(fullPath);
        }
      }
    }
  });
}

// 切换 Git 远程仓库 URL(只替换域名)
function changeGitRemote(folderPath) {
  try {
    process.chdir(folderPath);
    // 获取当前远程仓库的 URL
    const remoteUrl = execSync('git config --get remote.origin.url').toString().trim();
    // 检查是否需要替换域名
    if (remoteUrl.includes(OLD_DOMAIN)) {
        const newRemoteUrl = remoteUrl.replace(OLD_DOMAIN, NEW_DOMAIN);
        // 设置新的远程仓库 URL
        execSync(`git remote set-url origin ${newRemoteUrl}`);
        console.log(`Successfully changed remote URL for ${folderPath} from ${remoteUrl} to ${newRemoteUrl}`);
    } else {
        console.log(`No need to change remote URL for ${folderPath} (current URL: ${remoteUrl})`);
    }
    // process.chdir(process.cwd()); // 理论上这里不需要,因为 process.chdir 是对当前进程的修改,但为清晰起见还是加上
    process.chdir('..');
  } catch (error) {
    console.error(`Error processing ${folderPath}:`, error);
  }
}

// 主函数
function main() {
  changeGitRemotesInFolders(SEARCH_DIR);
}

main();
相关推荐
howard20052 小时前
6.4 Git安装与配置
git·安装配置
shmily麻瓜小菜鸡5 小时前
TDD(测试驱动开发)详解
开发语言·javascript·typescript·node.js·ecmascript
tryCbest6 小时前
git实现前后端分离项目提交同一个仓库
git·gitee
Mr.朱鹏6 小时前
Git 仓库同时推送到 Gitee 与 GitHub 配置指南
git·gitee·开源·github
半生过往7 小时前
Node.js 多版本管理完全指南
node.js
梦帮科技19 小时前
AI 音乐产品的发布工程:验证门、数据发布、回滚与生产运维纪律
数据结构·数据库·架构·node.js·音视频·动态规划·推荐算法
Flynt1 天前
HN 382分热文里的终端小技巧,我实测了一遍,git pickaxe 最值
git·命令行
BreezeJiang1 天前
别把 WebSocket 当成一门新协议学:搞懂"借 HTTP 握手",双端 Demo 和跨域就都通了
websocket·node.js
65岁退休Coder1 天前
把 Agent 框架拆开:PI 开发生产级 Harness
后端·node.js·agent
横木沉1 天前
IntelliJ IDEA 无法识别 Git:Git is not installed 问题解决
java·git·github·intellij-idea