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();
相关推荐
提笔了无痕6 小时前
git基本了解、常用基本命令与使用
git·后端
小胖霞9 小时前
企业级全栈项目(14) winston记录所有日志
vue.js·前端框架·node.js
一苓二肆10 小时前
代码常用工具使用
git·vscode·docker·github·vim
Elieal11 小时前
12 Git 多人协作(完整版工作流)
git
好好研究11 小时前
Git - 项目克隆命令、冲突处理流程
git·gitee
Anita_Sun11 小时前
🎨 基础认知篇:打破单线程误区
node.js
空空kkk11 小时前
Git——多人协作
git
Anita_Sun12 小时前
😋 核心原理篇:线程池的 5 大核心组件
前端·node.js
孟祥_成都12 小时前
nest.js / hono.js 一起学!字节团队如何配置多环境攻略!
前端·node.js
Cx330❀13 小时前
Git 分支管理完全指南:从基础到团队协作
大数据·git·搜索引擎·全文检索