Mac OS를 기준으로 작성된 글입니다. Window 환경과는 약간의 차이가 있을 수 있습니다.
회사에서 멀티 모듈 프로젝트로 작업하다보면, 많은 불편함이 있다. GUI를 사용하면 편하겠지만, CLI를 더 선호하기 때문에, 불편함을 감수하고 cd
로 이곳저곳을 돌아다니면서 고생을 했다. 하지만 alias
를 사용하면 이런 귀찮은 일을 쉽게 해결할 수 있다.
스크립트 보관 폴더 생성
스크립트를 보관할 전용 폴더를 생성한다.
mkdir ~/git-scripts | cd ~/git-scripts
스크립트 파일 생성
원하는 동작을 수행하는 JavaScript 파일을 생성한다. 이런 스크립트는 지피티가 잘 짜주기 때문에 원하는 스크립트를 지피티에게 요청하면 바로 나올 것이다.
아래 스크립트는 현재 디렉터리와 하위 디렉터리 중 Git Repository로 관리되는 폴더를 찾아, 원격 저장소의 현재 브랜치 기준으로 초기화하는 스크립트이다.
이 스크립트는 .git 폴더가 있는 디렉토리에만 적용되며, Git으로 관리되지 않는 폴더는 무시된다.
vim git-clear.js
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const currentDirectory = process.cwd();
const getDirectories = (directory) => {
return fs.readdirSync(directory).filter((file) => {
const filePath = path.join(directory, file);
return fs.statSync(filePath).isDirectory();
});
};
const isGitRepository = (directory) => {
return fs.existsSync(path.join(directory, '.git'));
};
const execCommand = (command, cwd) => {
return new Promise((resolve) => {
exec(command, { cwd }, (error, stdout, stderr) => {
if (stdout) console.log(`[${cwd}] ${stdout}`);
if (stderr) console.error(`[${cwd}] ${stderr}`);
resolve();
});
});
};
const getCurrentBranch = async (directory) => {
return new Promise((resolve) => {
exec('git rev-parse --abbrev-ref HEAD', { cwd: directory }, (error, stdout) => {
resolve(stdout.trim());
});
});
};
const hardResetAndClean = async (directory) => {
console.log(`\n🧹 Cleaning Git repo at: ${directory}`);
const branch = await getCurrentBranch(directory);
await execCommand(`git fetch origin ${branch}`, directory);
await execCommand(`git reset --hard origin/${branch}`, directory);
await execCommand(`git clean -fd`, directory);
};
(async () => {
if (isGitRepository(currentDirectory)) {
await hardResetAndClean(currentDirectory);
}
const subDirs = getDirectories(currentDirectory);
for (const dir of subDirs) {
const fullPath = path.join(currentDirectory, dir);
if (isGitRepository(fullPath)) {
await hardResetAndClean(fullPath);
}
}
})();
스크립트 추가
작성한 스크립트를 Git 명령어처럼 사용할 수 있도록 Git 설정 파일에 alias를 등록한다.
vim ~/.gitconfig
[alias]
섹션이 없다면 새로 추가하면 된다.
[alias]
clear = "!node ~/git-scripts/git-clear.js"
실제 사용
설정이 완료되었다면, 지정한 별칭을 통해 깃 프로젝트에서 사용하면 된다.
git clear
'Devlog > Git' 카테고리의 다른 글
[Git] cherry-pick을 통해 push된 커밋 되돌리기 (0) | 2025.01.13 |
---|---|
[Git] 버퍼 용량 초과 에러 (1) | 2024.10.29 |