Compare commits

..

No commits in common. "main" and "main" have entirely different histories.
main ... main

9 changed files with 299 additions and 368 deletions

9
Dockerfile Normal file
View File

@ -0,0 +1,9 @@
FROM node:16.3.0-alpine
RUN apk update
RUN apk add --no-cache --upgrade bash
#RUN addgroup -S admin && adduser -S admin -G admin
WORKDIR /data
#RUN chown -R admin:admin /data
#RUN chmod 755 /data
#USER admin
CMD npm install; npm run start

242
README.md
View File

@ -1,183 +1,117 @@
# Gitea CICD Service # gitea_CICD
<div align="center"> <div align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Node.js_logo.svg" alt="NodeJS" width="300"></div>
<img src="https://static-00.iconduck.com/assets.00/ci-cd-line-icon-512x511-3m4br5fx.png" alt="CI/CD" width="200">
<h3>Automated CI/CD System for Gitea</h3>
</div>
## 📝 Description ### 1) Clone project to your server
Gitea CICD Service is an automated CI/CD (Continuous Integration/Continuous Deployment) solution for projects hosted on Gitea. The system automatically monitors repository events (such as push, pull request) and executes corresponding commands to build, test, and deploy applications. ```sh
git clone https://gitea.nswteam.net/joseph/gitea_CICD.git
### 🌟 Key Features
- Automatic triggering on Gitea events (push, pull request)
- Support for multiple environments and technologies (Node.js, Frontend, Backend)
- Email notifications for events
- Flexible configuration through config file
- Nginx integration for webhook handling
- Runs as a systemd service for reliability
## 🚀 Installation
### System Requirements
- Node.js (version 16.3.0 or higher)
- NPM
- Nginx
- Git
- Systemd (for Linux)
### Installation Steps
1. **Clone repository**
```bash
git clone https://gitea.nswteam.net/joseph/gitea_CICD.git
cd gitea_CICD
``` ```
2. **Create service_run directory and configure** ### 2) Access the folder you just cloned
```bash
mkdir service_run
cp service/giteaService.conf service_run/giteaService.conf
```
3. **Configure environment variables** root@root#
```bash ```sh
nano service_run/giteaService.conf cd gitea_CICD
``` ```
Required environment variables: ### 3) Check the directory path
- `GIT_USERNAME`: Gitea username
- `GIT_PASSWORD`: Gitea password
- `GIT_REPOSITORY`: Repository URL
- `GIT_BRANCH`: Branch to monitor
- `PORT_SERVICE`: Service port
- `EMAIL_ADDRESS`: Notification email
- `SEND_EMAIL`: Enable/disable email notifications (True/False)
- `RECEIVE_EMAIL_ADDRESS`: Email address to receive notifications
- `EMAIL_FROM`: Sender email address
- `EMAIL_HOST`: Email server host
- `EMAIL_PORT`: Email server port
- `EMAIL_SECURE`: Secure connection (True/False)
- `EMAIL_USER`: Email username
- `EMAIL_PASSWORD`: Email password
- `PROJECT_PATH`: Project directory path
4. **Configure Nginx** root@root#
```sh
pwd
```
- output: <path>/gitea_CICD
Add the following configuration to your Nginx config file: ### 4) Create folder service_run
```nginx
location /git/ {
proxy_pass http://<IP-address>:<PORT>;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass_request_headers on;
proxy_max_temp_file_size 0;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
}
```
Restart Nginx: root@root#
```bash
systemctl restart nginx
```
5. **Install service** ```sh
```bash mkdir service_run
./install.sh ```
``` Copy environment file
```sh
cp service/giteaService.conf service_run/giteaService.conf
```
## ⚙️ Configure Gitea Webhook ### 5) Fill in environment variables (\*)
1. Access your Gitea repository root@root#
2. Go to Settings > Webhooks ```sh
3. Click "Add Webhook" nano service_run/giteaService.conf
4. Fill in the information: ```
- Target URL: `http://your-domain/git/gitea-webhook`
- Trigger on: Select events to monitor ### 6) Add Nginx configuration
- Branch filter: Enter branch to monitor (or '*' for all) - Open the Nginx configuration file.
## 📁 Directory Structure - Add thr following configuration content.
``` ```
gitea_CICD/ location /git/ {
├── service/ # Service files directory #index index.html;
│ ├── giteaService.conf # Configuration template proxy_pass http://<IP-address>:<PORT>;
│ ├── giteaService.sh # Main script proxy_http_version 1.1;
│ └── giteaHook.service # Systemd configuration proxy_set_header X-Forwarded-Host $host;
├── service_run/ # Runtime directory (created during installation) proxy_set_header X-Forwarded-Server $host;
├── index.js # Main webhook handler proxy_set_header X-Real-IP $remote_addr;
├── install.sh # Installation script proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
└── README.md # Documentation proxy_set_header X-Forwarded-Proto $scheme;
``` proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass_request_headers on;
proxy_max_temp_file_size 0;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
}
```
## 🔧 Customize Build Process - Change "IP-address" and "PORT". The "PORT" corresponds to the "PORT_SERVICE" of the "service_run/giteaService.conf" file.
You can customize the build process by adding environment variables in `giteaService.conf`: - Restart Nginx service.
```sh
systemctl restart nginx
```
### 7) Run file "install.sh" to install service
```bash root@root#
# Syntax: ```sh
<name>_PROCESS_PATH=/path/to/directory ./install.sh
<name>_PROCESS_PATH_COMMAND=command1 && command2 ... ```
# Example: <div align="center"><img src="https://i.ibb.co/VJHhb3y/install-Service.png" alt="install server" width="600"></div>
FE_PROCESS_PATH=/home/project/frontend
FE_PROCESS_PATH_COMMAND=npm install && npm run build
BE_PROCESS_PATH=/home/project/backend ### 8) Add webhook
BE_PROCESS_PATH_COMMAND=npm install && npm run start
```
## 📧 Email Notifications - Open your project on Gitea:
- Choose "Setting"
<div align="center"><img src="https://i.ibb.co/QHsST4D/image.png" alt="webhook1" width="800"></div>
The system sends email notifications when: - Choose "Webhooks" and "Add Webhooks"
- New repository events occur <div align="center"><img src="https://i.ibb.co/bKFpvbV/image.png" alt="webhook2" width="800"></div>
- Build process succeeds/fails
- Errors occur during processing
## 🔍 Monitoring and Troubleshooting - Fill in the information
<div align="center"><img src="https://i.ibb.co/GJ55RDr/image.png" alt="webhook3" width="800"></div>
- View service logs: - Target URL: URL to the API that handles requests when a event is triggered (Default: your_domain/git/gitea-webhook).
```bash - Trigger on: Event to trigger the webhook.
journalctl -u giteaHook -f - Branch filter: Events will be listened on the branch you choose. ( '*' :all branch)
```
- Check service status: #### ** Note: **
```bash
systemctl status giteaHook
```
## 📝 Important Notes - Project gitea_CICD should be placed at the same folder level as your project
1. The `gitea_CICD` project should be placed at the same level as the project to be monitored ```
2. Ensure appropriate file and directory permissions ├── your_project
3. Verify environment variables before running the service └── gitea_CICD project
4. Use HTTPS for webhooks to ensure security ```
## 👨‍💻 Author - Depending on the technology your project uses, the "gitea_CICD/service_run/giteaHook.sh" file will be custom configured to match the technology.
**Joseph Le** - [GitHub](https://github.com/joseph) <div align="center"><h4><i>**____ Joseph Le____ **</i></h4></div>
## 📄 License
This project is licensed under the ISC License.
---
<div align="center">
<sub>Built with ❤️ by Joseph Le</sub>
</div>

0
abc.txt Normal file
View File

10
docker-compose.yaml Normal file
View File

@ -0,0 +1,10 @@
version: '3'
services:
giteahook:
build: .
container_name: giteahook
volumes:
- ".:/data"
tty: true
ports:
- '8000:8001'

210
index.js
View File

@ -3,112 +3,138 @@ const express = require("express");
const app = express(); const app = express();
const { exec } = require("child_process"); const { exec } = require("child_process");
const nodeMailer = require("nodemailer"); const nodeMailer = require("nodemailer");
// Read configuration file
const contentFile = fs.readFileSync("./service_run/giteaService.conf", "utf8"); const contentFile = fs.readFileSync("./service_run/giteaService.conf", "utf8");
let checkStatus = "ready"; let checkStatus = "ready"
// const checkFile = fs.readFileSync("./service_run/checkFile", "utf8");
// Get port from configuration file
const PORT = contentFile const PORT = contentFile
.split("\n") .split("\n")
.find(line => line.includes("PORT_SERVICE")) .filter((i) => i.includes("PORT_SERVICE"))[0]
?.split("=")[1]
.trim() || 5000;
// Get email configuration from config file
const getConfigValue = (key) => contentFile
.split("\n")
.find(line => line.includes(key))
?.split("=")[1] ?.split("=")[1]
.trim(); .trim();
// Configure email transporter
const createTransporter = () => nodeMailer.createTransport({
pool: true,
host: getConfigValue("EMAIL_HOST") || "smtp.gmail.com",
port: parseInt(getConfigValue("EMAIL_PORT") || "587"),
secure: getConfigValue("EMAIL_SECURE") === "True",
auth: {
user: getConfigValue("EMAIL_USER") || "git@notification.com",
pass: getConfigValue("EMAIL_PASSWORD") || "123456789",
},
});
app.use(express.json()); app.use(express.json());
app.post("/git/gitea-webhook", async (req, res) => { app.post("/git/gitea-webhook", async (req, res) => {
let title = ""; let title = "";
const checkSendMail = getConfigValue("SEND_EMAIL");
const emailAddress = getConfigValue("RECEIVE_EMAIL_ADDRESS"); const checkSendMail = contentFile
const emailFrom = getConfigValue("EMAIL_FROM") || "git@notification.com"; .split("\n")
.filter((i) => i.includes("SEND_EMAIL"))[0]
?.split("=")[1]
.trim();
const emailAddress = contentFile
.split("\n")
.filter((i) => i.includes("EMAIL_ADDRESS"))[0]
?.split("=")[1]
.trim();
const FE_Path = contentFile
.split("\n")
.filter((i) => i.includes("FE_PROJECT_PATH"))[0]
?.split("=")[1]
.trim();
const giteaEvent = req.headers["x-gitea-event"]; const giteaEvent = req.headers["x-gitea-event"];
// Return response immediately const body = req.body;
res.status(200).send({ mess: "The event has been received!", data: req.body }); //console.log(body)
console.log("STATUS:", checkStatus); res
.status(200)
// Check if there is a running process .send({ mess: "The event has been received!", data: req.body });
console.log("CHECK FILE", checkStatus);
if (checkStatus === "busy") { if (checkStatus === "busy") {
if (checkSendMail === "True") { const transporter = nodeMailer.createTransport({
const transporter = createTransporter(); pool: true,
const options = { host: "mail.ipsupply.com.au",
from: emailFrom, port: 465,
to: emailAddress, secure: true,
subject: "Git notifications (Fail)", auth: {
html: "<h3>There is an active build process. Please check and push again in a few minutes.</h3>", user: "admin@apactech.io",
}; pass: "BGK!dyt6upd2eax1bhz",
return transporter.sendMail(options); },
} });
return;
}
// Process new event
console.log("New event: " + giteaEvent);
checkStatus = "busy";
exec("./service_run/giteaHook.sh", (error, stdout, stderr) => {
let content = stdout || stderr;
if (error) {
console.log("Pull failed. Please check");
console.log(`Error executing command: ${error}`);
title = `New Git event: ${giteaEvent}`;
} else {
console.log(stdout);
const hasError = [stderr, stdout].some(output =>
output && (output.includes("Error") || output.includes("failed"))
);
title = `New Git event: ${giteaEvent}${hasError ? "" : " (success)"}`;
// Reset status after 10 seconds
setTimeout(() => {
checkStatus = "ready";
}, 10000);
}
// Send notification email if configured const options = {
if (checkSendMail === "True") { from: "admin@apactech.io",
const transporter = createTransporter(); to: emailAddress,
const options = { subject: "Git notifications (Fail)",
from: emailFrom, html:
to: emailAddress, "<h3>There is an active build process in the " +
subject: title, FE_Path +
html: ` " directory. Please check and push again in a few minutes.</h3>",
<h1>*** ${giteaEvent} event ***</h1> };
<h4>Committer: ${req.body.commits[0]?.committer.name || "N/A"}</h4>
<h4>Message: ${req.body.commits[0]?.message || "N/A"}</h4> return transporter.sendMail(options);
<h4>Branch: ${req.body.ref || "N/A"}</h4> } else {
${req.body.commits[0]?.url ? `<a href='${req.body.commits[0].url}'>Link: ${req.body.commits[0].url}</a>` : ""} console.log("New event: " + giteaEvent);
<h4>Process output:</h4> // fs.writeFileSync("./service_run/checkFile", "true");
<textarea style='wordWrap:break-word; display: block; width:100%; height:70vh;border:solid 2px orange'>${content.replace(/error|fail|warning/gi, match => `<span style="background-color:yellow;color:red;font-weight:bold">${match}</span>`)}</textarea> checkStatus="busy"
`, exec("./service_run/giteaHook.sh", (error, stdout, stderr) => {
}; let content = stdout !== "" ? stdout : stderr;
return transporter.sendMail(options); if (error) {
} console.log("Pull failed. Please check");
}); console.log(`Error executing command: ${error}`);
title += "New Git envent: " + giteaEvent;
} else {
console.log(stdout);
if (
stderr.includes("Error") ||
stderr.includes("failed") ||
stdout.includes("Error") ||
stdout.includes("failed")
) {
title += "New Git envent: " + giteaEvent;
} else {
title += "New Git envent: " + giteaEvent + "(success)";
}
setTimeout(() => {
checkStatus="ready"
// fs.writeFileSync("./service_run/checkFile", "false");
}, 10000);
}
if (checkSendMail === "True") {
const transporter = nodeMailer.createTransport({
pool: true,
host: "mail.ipsupply.com.au",
port: 465,
secure: true,
auth: {
user: "admin@apactech.io",
pass: "BGK!dyt6upd2eax1bhz",
},
});
const options = {
from: "admin@apactech.io",
to: emailAddress,
subject: title,
html:
"<h1>*** " +
giteaEvent +
" event ***</h1><h4>Committer: " +
req.body.commits[0]?.committer.name +
"</h4><h4>Message: " +
req.body.commits[0]?.message +
"</h4><h4>Branch: " +
req.body.ref +
"</h4><a href='" +
req.body.commits[0]?.url +
"'>Link: " +
req.body.commits[0]?.url +
"</a><h4>Process output:</h4><textarea style='wordWrap:break-word; display: block; width:100%; height:70vh;border:solid 2px orange'>" +
content +
"</textarea>",
};
return transporter.sendMail(options);
}
});
}
}); });
app.listen(PORT, () => { app.listen(PORT, () => {
console.log("Service is running on port", PORT); console.log("Service is running on port ", PORT);
}); });

View File

@ -1,10 +1,5 @@
#!/bin/bash #!/bin/bash
NODE_BIN=$(which node)
NPM_BIN=$(which npm)
echo $NODE_BIN
echo $NPM_BIN
if [ -d "/etc/systemd/system" ]; then if [ -d "/etc/systemd/system" ]; then
echo "|---------------------------|" echo "|---------------------------|"
echo -e "|***** \e[33mINSTALL SERVICE\e[0m *****|" echo -e "|***** \e[33mINSTALL SERVICE\e[0m *****|"
@ -32,17 +27,11 @@ if [ -d "/etc/systemd/system" ]; then
sudo sed -i "s#HOOK_PATH=.*#HOOK_PATH=$escaped_pwd_install#" $pwd_install/service_run/giteaService.conf && sudo sed -i "s#HOOK_PATH=.*#HOOK_PATH=$escaped_pwd_install#" $pwd_install/service_run/giteaService.conf &&
echo -e "* \e[32mHOOK_PATH\e[0m *" && echo -e "* \e[32mHOOK_PATH\e[0m *" &&
sudo sed -i "s#NODE_BIN=.*#NODE_BIN=$NODE_BIN#" $pwd_install/service_run/giteaService.conf && sudo sed -i "s#source .*#source $escaped_pwd_install/service_run/giteaService.conf#" $pwd_install/service_run/giteaHook.sh &&
echo -e "* \e[32mNODE_BIN\e[0m *" &&
sudo sed -i "s#NPM_BIN=.*#NPM_BIN=$NPM_BIN#" $pwd_install/service_run/giteaService.conf &&
echo -e "* \e[32mNPM_BIN\e[0m *" &&
sudo sed -i "s#source=.*#source=$escaped_pwd_install/service_run/giteaService.conf#" $pwd_install/service_run/giteaHook.sh &&
echo -e "* \e[32mEXEC_FILE\e[0m *" && echo -e "* \e[32mEXEC_FILE\e[0m *" &&
echo "" echo ""
sudo sed -i "s#source=.*#source=$escaped_pwd_install/service_run/giteaService.conf#" $pwd_install/service_run/giteaService.sh && sudo sed -i "s#source .*#source $escaped_pwd_install/service_run/giteaService.conf#" $pwd_install/service_run/giteaService.sh &&
systemctl stop giteaHook.service systemctl stop giteaHook.service

View File

@ -1,16 +1,7 @@
#!/bin/bash #!/bin/bash
#File chua bien moi truong #File chua bien moi truong
source=/home/joseph/tr2/gitea_CICD/service_run/giteaService.conf source /home/joseph/tr2/gitea_CICD/service_run/giteaService.conf
while read -r line; do
[[ -z "$line" || "$line" =~ ^# ]] && continue
if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
varname="${line%%=*}"
varvalue="${line#*=}"
export "$varname=$varvalue"
fi
done < $source
check="false" check="false"
@ -58,14 +49,14 @@ else
echo "" && echo "" &&
echo "$result" && echo "$result" &&
output=$(echo "$result" | grep "|" | awk -F "|" '{gsub(/ /, "", $1); print $1}') && output=$(echo "$result" | grep "|" | awk -F "|" '{gsub(/ /, "", $1); print $1}') &&
# while IFS= read -r line; do while IFS= read -r line; do
# if [[ $line != "" && $(find "$project" | grep "$line" | grep -q "$FE_PROJECT_PATH"; echo $?) -eq 0 ]]; then if [[ $line != "" && $(find "$project" | grep "$line" | grep -q "$FE_PROJECT_PATH"; echo $?) -eq 0 ]]; then
# echo "$line ton tai" && echo "$line ton tai" &&
# check="true" check="true"
# else else
# echo "$line ko ton tai" echo "$line ko ton tai"
# fi fi
# done <<< "$output" done <<< "$output"
# process_ids=$(ps aux | grep "$FE_PROJECT_PATH" | grep "build" | grep -v grep | awk '{print $2}') && # process_ids=$(ps aux | grep "$FE_PROJECT_PATH" | grep "build" | grep -v grep | awk '{print $2}') &&
# #
@ -91,25 +82,25 @@ else
# #
# fi # fi
# if [[ $check == "true" ]]; then if [[ $check == "true" ]]; then
# echo "|--------------------------------------------------------|" echo "|--------------------------------------------------------|"
# echo "|***** THERE ARE CHANGES INSIDE FOLDER $FE_PROJECT_PATH *****|" echo "|***** THERE ARE CHANGES INSIDE FOLDER $FE_PROJECT_PATH *****|"
# echo "|--------------------------------------------------------|" echo "|--------------------------------------------------------|"
# echo "|---------------|" echo "|---------------|"
# echo "|*** INSTALL ***|" echo "|*** INSTALL ***|"
# echo "|---------------|" echo "|---------------|"
# cd $FE_PROJECT_PATH && cd $FE_PROJECT_PATH &&
# npm install -f npm install
# echo "|-------------|" echo "|-------------|"
# echo "|*** BUILD ***|" echo "|*** BUILD ***|"
# echo "|-------------|" echo "|-------------|"
# npm run build && npm run build &&
# cp -rf $FE_PROJECT_PATH/build/* $FE_ROOT_FOLDER_PATH cp -rf $FE_PROJECT_PATH/build/* $FE_ROOT_FOLDER_PATH
# fi fi
echo "|----------------------|" echo "|----------------------|"
echo "|*** UPDATE LIBRARY ***|" echo "|*** UPDATE LIBRARY ***|"

View File

@ -2,8 +2,7 @@
# The variable is automatically filled in by the system # The variable is automatically filled in by the system
HOOK_PATH=/home/gitea_CICD HOOK_PATH=/home/gitea_CICD
NODE_BIN=/path/to/node
NPM_BIN=/path/to/npm
# Git account (*) # Git account (*)
GIT_USERNAME=<your_username> GIT_USERNAME=<your_username>
GIT_PASSWORD=<your_password> GIT_PASSWORD=<your_password>
@ -15,19 +14,22 @@ GIT_BRANCH=<your_branch>
PORT_SERVICE=5000 PORT_SERVICE=5000
# Email: Used to send notifications when the repository has updates (*) # Email: Used to send notifications when the repository has updates (*)
EMAIL_ADDRESS=<youremail>
# Enable/Disable send mail: True or False (*) # Enable/Disable send mail: True or False (*)
SEND_EMAIL=False SEND_EMAIL=True
RECEIVE_EMAIL_ADDRESS=<youremail>
EMAIL_FROM=
EMAIL_HOST=
EMAIL_PORT=
EMAIL_SECURE=True
EMAIL_USER=
EMAIL_PASSWORD=
# URL of project directory (*) # URL of project directory (*)
# Example: /home/My_project/ # Example: /home/My_project/
PROJECT_PATH=</project/directory/path> PROJECT_PATH=</project/directory/path>
# URL of front-end directory(*)
# Example: /home/My_project/FE_directory
FE_PROJECT_PATH=</FE/directory/path>
# URL of front-end public directory (*)
# Example: /var/www/html
FE_ROOT_FOLDER_PATH=</FE/public/directory/path>
# #
# It is possible to add many other directory besides the front-end directory # It is possible to add many other directory besides the front-end directory
# #
@ -37,10 +39,6 @@ PROJECT_PATH=</project/directory/path>
# #
# Example: # Example:
# URL of FE directory(*)
#FE_PROCESS_PATH=/home/My_project/FE_directory
#FE_PROCESS_PATH_COMMAND=npm install -f && npm run build && cp -rf /home/My_project/FE_directory/build/* /var/www/html
# URL of back-end directory(*) # URL of back-end directory(*)
#BE_PROCESS_PATH=/home/My_project/BE_directory #BE_PROCESS_PATH=/home/My_project/BE_directory
#BE_PROCESS_PATH_COMMAND=npm install && echo "\n" && echo "BACK_END" #BE_PROCESS_PATH_COMMAND=npm install && echo "\n" && echo "BACK_END"

View File

@ -1,85 +1,59 @@
#!/bin/bash #!/bin/bash
set -e # Dừng script nếu có lỗi source /home/phuc/gitea_CICD/service_run/giteaService.conf
source=/home/joseph/tr2/gitea_CICD/service_run/giteaService.conf
while read -r line; do
[[ -z "$line" || "$line" =~ ^# ]] && continue
if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
varname="${line%%=*}"
varvalue="${line#*=}"
export "$varname=$varvalue"
fi
done < $source
export HOME=$PROJECT_PATH export HOME=$PROJECT_PATH
# Đường dẫn tới tệp index.js
indexjs_path="$HOOK_PATH/index.js" indexjs_path=$HOOK_PATH/index.js
project_path="$HOOK_PATH" project_path=$HOOK_PATH
USERNAME=$(echo "$GIT_USERNAME" | sed 's/@/%40/g') USERNAME=$(echo "$GIT_USERNAME" | sed 's/@/%40/g')
PASSWORD=$(echo "$GIT_PASSWORD" | sed 's/@/%40/g') PASSWORD=$(echo "$GIT_PASSWORD" | sed 's/@/%40/g')
REPOSITORY_AUTH="https://$USERNAME:$PASSWORD@$(echo $GIT_REPOSITORY | sed 's#https://##')" REPOSITORY_AUTH="https://$USERNAME:$PASSWORD@$(echo $GIT_REPOSITORY | sed 's#https://##')"
# Debug PATH nếu cần cd "$PROJECT_PATH" &&
# echo "Current PATH: $PATH"
# # Thiết lập lại PATH nếu thiếu (thường gặp khi chạy từ systemd)
# if ! command -v node &> /dev/null; then
# echo "Node.js not found in PATH, attempting to locate..."
# NODE_PATH=$(find /usr /opt /home -type f -name "node" -executable 2>/dev/null | head -n 1)
# if [ -x "$NODE_PATH" ]; then
# export PATH=$(dirname "$NODE_PATH"):$PATH
# echo "Added $(dirname "$NODE_PATH") to PATH"
# fi
# fi
# if ! command -v node &> /dev/null; then git config --global --add safe.directory $HOME &&
# echo -e "\e[41mNode.js is not installed or not in PATH\e[0m"
# exit 1
# else
# echo -e "\e[32mNode.js is installed!\e[0m"
# node -v
# fi
# # Kiểm tra npm tương tự SET_ORIGIN=$(git remote set-url origin $REPOSITORY_AUTH) &&
# if ! command -v npm &> /dev/null; then
# echo "npm not found in PATH, attempting to locate..." # Ki?m tra xem Node.js đ? cài đ?t chưa
# NPM_PATH=$(find /usr /opt /home -type f -name "npm" -executable 2>/dev/null | head -n 1) if ! command -v node &> /dev/null; then
# if [ -x "$NPM_PATH" ]; then echo -e "\e[31mNode.js is not installed.\e[0m"
# export PATH=$(dirname "$NPM_PATH"):$PATH echo -e "\e[32mInstall Node.js...\e[0m"
# echo "Added $(dirname "$NPM_PATH") to PATH" curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - &&
# fi sudo apt-get install nodejs -y &&
# fi node -v
else
echo -e "\e[32mNodejs is installed!\e[0m" &&
node -v
fi
# if ! command -v npm &> /dev/null; then # Ki?m tra xem npm đ? cài đ?t chưa
# echo -e "\e[41mnpm is not installed or not in PATH\e[0m" if ! command -v npm &> /dev/null; then
# exit 1 echo -e "\e[31mnpm is not installed. Install npm...\e[0m"
# else sudo apt-get install npm -y
# echo -e "\e[32mnpm is installed!\e[0m" else
# npm -v echo -e "\e[32mnpm is installed!\e[0m" &&
# fi npm -v
fi
cd "$PROJECT_PATH"
git config --global --add safe.directory "$HOME"
git remote set-url origin "$REPOSITORY_AUTH"
if git ls-remote -q --exit-code "$REPOSITORY_AUTH" > /dev/null; then if git ls-remote -q --exit-code "$REPOSITORY_AUTH" > /dev/null; then
echo -e "\e[32mOK: Repository $GIT_REPOSITORY exists\e[0m" echo -e "\e[32mOK: Repository $GIT_REPOSITORY exists\e[0m"
sleep 1
else else
echo -e "\e[41mError: Repository $GIT_REPOSITORY does not exist.\e[0m" echo ""
echo -e "\e[41mError: Repository $GIT_REPOSITORY not exists.\e[0m"
echo ""
exit 1 exit 1
fi fi
# Chạy index.js nếu tồn tại # Ki?m tra xem t?p index.js có t?n t?i không
if [ -f "$indexjs_path" ]; then if [ -f "$indexjs_path" ]; then
echo "Run file $indexjs_path..." echo "Run file $indexjs_path..."
echo $NPM_BIN
echo $NODE_BIN
export PATH="$(dirname $NODE_BIN):$PATH"
cd "$project_path" && cd "$project_path" &&
$NPM_BIN install && npm install &&
$NODE_BIN "$indexjs_path" node "$indexjs_path"
else else
echo -e "\e[31mFile $indexjs_path not exists\e[0m" echo -e "\e[31mFile $indexjs_path not exists\e[0m"
exit 1
fi fi