개발/Node JS
Node JS - exec으로 Git Push 하기
피로물든딸기
2024. 1. 14. 19:25
반응형
원격 저장소에 변경된 내용을 주기적으로 Push를 하거나,
리액트 등에서 특정 이벤트가 발생했을 때 Push를 한다고 가정해 보자.
먼저 필요한 명령어를 shell script로 만들어 둔다. (test.sh)
#!/bin/bash
# shell script가 있는 디렉토리 이동
cd "D:/github/auto-test"
# Git 저장소 초기화
git init
# 원격 저장소의 main 브랜치 fetch
git fetch origin main
# 로컬 저장소의 main 브랜치로 원격 저장소의 main 브랜치 병합
git merge origin/main
# 변경된 모든 파일을 스테이징
git add .
# 커밋 생성
git commit -m "Auto Commit"
# 원격 저장소에 연결
git remote add origin https://github.com/bloodstrawberry/auto-test.git
# main 브랜치 생성
git branch -M main
# 변경 사항을 원격 저장소에 푸시
git push -u origin main
원격 저장소의 주소는 깃허브 리포지토리에서 Code 버튼을 누르면 확인할 수 있다.
노드에서는 exec 모듈을 이용해서 shell script를 실행할 수 있다. (git_test.js, 예시는 윈도우 경로)
const { exec } = require("child_process");
const execute_shell = (shellPath) => {
exec(`sh ${shellPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error script: ${error}`);
} else {
console.log("Execute Shell");
console.log(stdout);
}
});
};
execute_shell("D:\\github\\auto-test\\test.sh");
git_test.js를 실행하면 아래 결과를 얻을 수 있고, 실제로 리포지토리가 원격 저장소에 잘 반영된다.
$ node git_test.js
Execute Shell
Reinitialized existing Git repository in D:/github/auto-test/.git/
Already up to date.
[main 2e00eaf] Auto Commit
2 files changed, 4 insertions(+), 4 deletions(-)
delete mode 100644 image.jpg
Branch 'main' set up to track remote branch 'main' from 'origin'.
반응형