Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

git 动态设置用户信息 #21

Open
zhangwt-cn opened this issue Oct 12, 2023 · 0 comments
Open

git 动态设置用户信息 #21

zhangwt-cn opened this issue Oct 12, 2023 · 0 comments
Labels
Mac os Mac 相关内容

Comments

@zhangwt-cn
Copy link
Owner

zhangwt-cn commented Oct 12, 2023

前因

在开发公司项目和个人项目都在同一个主机时出现一个很尴尬的问题,git设置了user.nameuser.email,在提交代码时难免出现个人项目使用公司的邮箱提交或者是公司项目用了个人的邮箱去提交,因为git项目本地的设置只作用于这个项目,不会影响到其他项目,因此想了一个解决办法那就是在项目clone到本地的时候根据域名设置项目本地的user.nameuser.email

实现脚本custom-clone.sh

#!/bin/bash

GREEN='\033[0;32m'
NC='\033[0m'
YELLOW='\033[0;33m'

# 检查是否提供了仓库URL
if [ "$#" -ne 1 ]; then
  echo "Usage: custom-clone.sh <repository_url>"
  exit 1
fi

# 获取仓库URL
repository_url="$1"

# 克隆仓库
git clone "$repository_url"

# 进入克隆的仓库目录
repository_name=$(basename "$repository_url" .git)
cd "$repository_name"

git config --local user.name "xxx"

# 获取远程仓库的URL
remote_url=$(git config --get remote.origin.url)

# 提取邮箱域名部分
if [[ $remote_url =~ @(.+)$ ]]; then
  domain="${BASH_REMATCH[1]}"
  # 根据域名设置本地项目的邮箱地址
  case "$domain" in
    *github.com*)
      git config --local user.email "exm1@xx.com"
      echo -e "This domain is ${GREEN}github.com${NC}"
      echo -e "Set up user.name: ${GREEN}$(git config user.name)${NC}"
      echo -e "Set up user.email: ${GREEN}$(git config user.email)${NC}" 
      ;;
    *xx.com*)
      git config --local user.email "exm2@xx.cn"
      echo -e "This domain is ${GREEN}xx.com${NC}"
      echo -e "Set up user.name: ${GREEN}$(git config user.name)${NC}"
      echo -e "Set up user.email: ${GREEN}$(git config user.email)${NC}"
      ;;
    *)
      # 设置一个默认邮箱地址,如果没有匹配的域名
      git config --local user.email "exm3@xx.com"
      echo -e "This domain unrecognized ${YELLOW}$domain${NC}"
      echo -e "Set up default user.name: ${GREEN}$(git config user.name)${NC}"
      echo -e "Set up default user.email: ${GREEN}$(git config user.email)${NC}"
      ;;
  esac
fi

执行 chmod +x custom-clone.sh 增加执行权限

配置git 别名

  1. 编辑全局配置文件
git config --global --edit
  1. 设置别名
[alias]
    custom-clone = "!/path/to/custom-clone.sh"
  1. 保存设置

执行命令

git custom-clone url

一切配置好之后只需替换url为实际项目地址就能实现拉取项目时根据配置的域名动态写入用户信息

@zhangwt-cn zhangwt-cn added the Mac os Mac 相关内容 label Oct 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Mac os Mac 相关内容
Projects
None yet
Development

No branches or pull requests

1 participant