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();
相关推荐
不老刘15 小时前
Antigravity 的 New Worktree 模式:给 AI 代理一个安全的“平行工位”
人工智能·git·ai编程·antigravity
光谱SpectrAI15 小时前
Windows 也中招:Git Bash 和 Node 仍信任泄露的 eMudhra 证书
git
YIN_尹15 小时前
【git原理与使用】git初识与安装
大数据·git·elasticsearch
雨季mo浅忆17 小时前
记录Node.js安全漏洞及其内置Brotli解码器问题
node.js·安全性测试
tommyjiatong17 小时前
资安底座连环雷:从 PHP2Shell 到 Node2Shell
node.js·php
Leo_Mr20 小时前
Vue3 项目配置 Git 提交规范(企业通用方案:husky + commitlint + cz-git + lint-staged)
git
SEO_juper20 小时前
Bash 交叉验证 robots.txt 和 sitemap:两个文件自相矛盾,页面永远收录不了
开发语言·python·node.js·json·bash
jyOverQ21 小时前
Git rebase 和 merge 有什么区别?什么时候该用哪个?
git
晗夜未央21 小时前
跨仓库 Skill 换台电脑就失效?用 Git remote 校验项目
人工智能·git·python
Lsetea21 小时前
Git访问HTTPS证书不受信任:用URL级sslCAInfo限定私有CA范围
git·https·开发工具·ssl证书·ca证书