fuc-new/doc/node_modules/@vuepress/plugin-git/lib/node/utils/inferGitProvider.js
hellcat 6adbc04d4b 1
2025-10-03 17:17:08 +08:00

65 lines
1.6 KiB
JavaScript

import { execSync } from 'node:child_process';
/**
* Gets the URL of a Git remote.
*
* 获取 Git 远程仓库的 URL
*
* @param cwd - The directory where the git commands should be executed.
*
* 执行 git 命令的目录
*/
export const getRemoteUrl = (cwd) => {
const execOptions = {
cwd,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore'],
// prevent hanging
timeout: 5000,
};
try {
const originUrl = execSync('git remote get-url origin', execOptions);
return originUrl.trim();
}
catch {
try {
const remotesOutput = execSync('git remote', execOptions);
const firstRemote = remotesOutput.split('\n')[0]?.trim();
if (firstRemote) {
const remoteUrl = execSync(`git remote get-url ${firstRemote}`, execOptions);
return remoteUrl.trim();
}
return null;
}
catch {
return null;
}
}
};
/**
* Infer git provider from remote URL
*
* 从远程 URL 推断 Git 提供商
*
* @param cwd - The directory where the git commands should be executed
*
* 执行 git 命令的目录
*/
export const inferGitProvider = (cwd) => {
const remoteUrl = getRemoteUrl(cwd);
if (!remoteUrl)
return null;
if (remoteUrl.includes('github.com')) {
return 'github';
}
if (remoteUrl.includes('gitlab.com')) {
return 'gitlab';
}
if (remoteUrl.includes('gitee.com')) {
return 'gitee';
}
if (remoteUrl.includes('bitbucket.org')) {
return 'bitbucket';
}
return null;
};