Compare commits

...

5 Commits
main ... main

Author SHA1 Message Date
root 979105c08c update source variables 2025-05-14 15:53:23 +07:00
root 8d732a72e9 update source variables 2025-05-14 14:54:29 +07:00
root 7d3f9b28d9 update logic check node, npm 2025-05-14 11:11:38 +07:00
joseph le d8b569b5e8 upgrade logic 2025-04-03 09:27:56 +07:00
paymentdev 7303a9c7c8 change command line 2023-12-11 07:32:11 +00:00
9 changed files with 368 additions and 299 deletions

View File

@ -1,9 +0,0 @@
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,117 +1,183 @@
# gitea_CICD # Gitea CICD Service
<div align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Node.js_logo.svg" alt="NodeJS" width="300"></div> <div align="center">
<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>
### 1) Clone project to your server ## 📝 Description
```sh 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.
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) Access the folder you just cloned 2. **Create service_run directory and configure**
```bash
mkdir service_run
cp service/giteaService.conf service_run/giteaService.conf
```
root@root# 3. **Configure environment variables**
```sh ```bash
cd gitea_CICD nano service_run/giteaService.conf
``` ```
### 3) Check the directory path Required environment variables:
- `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
root@root# 4. **Configure Nginx**
```sh
pwd
```
- output: <path>/gitea_CICD
### 4) Create folder service_run Add the following configuration to your Nginx config file:
```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;
}
```
root@root# Restart Nginx:
```bash
systemctl restart nginx
```
```sh 5. **Install service**
mkdir service_run ```bash
``` ./install.sh
Copy environment file ```
```sh
cp service/giteaService.conf service_run/giteaService.conf
```
### 5) Fill in environment variables (\*) ## ⚙️ Configure Gitea Webhook
root@root# 1. Access your Gitea repository
```sh 2. Go to Settings > Webhooks
nano service_run/giteaService.conf 3. Click "Add Webhook"
``` 4. Fill in the information:
- Target URL: `http://your-domain/git/gitea-webhook`
### 6) Add Nginx configuration - Trigger on: Select events to monitor
- Open the Nginx configuration file. - Branch filter: Enter branch to monitor (or '*' for all)
- Add thr following configuration content. ## 📁 Directory Structure
``` ```
location /git/ { gitea_CICD/
#index index.html; ├── service/ # Service files directory
proxy_pass http://<IP-address>:<PORT>; │ ├── giteaService.conf # Configuration template
proxy_http_version 1.1; │ ├── giteaService.sh # Main script
proxy_set_header X-Forwarded-Host $host; │ └── giteaHook.service # Systemd configuration
proxy_set_header X-Forwarded-Server $host; ├── service_run/ # Runtime directory (created during installation)
proxy_set_header X-Real-IP $remote_addr; ├── index.js # Main webhook handler
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ├── install.sh # Installation script
proxy_set_header X-Forwarded-Proto $scheme; └── README.md # Documentation
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;
}
```
- Change "IP-address" and "PORT". The "PORT" corresponds to the "PORT_SERVICE" of the "service_run/giteaService.conf" file. ## 🔧 Customize Build Process
- Restart Nginx service. You can customize the build process by adding environment variables in `giteaService.conf`:
```sh
systemctl restart nginx
```
### 7) Run file "install.sh" to install service
root@root# ```bash
```sh # Syntax:
./install.sh <name>_PROCESS_PATH=/path/to/directory
``` <name>_PROCESS_PATH_COMMAND=command1 && command2 ...
<div align="center"><img src="https://i.ibb.co/VJHhb3y/install-Service.png" alt="install server" width="600"></div> # Example:
FE_PROCESS_PATH=/home/project/frontend
FE_PROCESS_PATH_COMMAND=npm install && npm run build
### 8) Add webhook BE_PROCESS_PATH=/home/project/backend
BE_PROCESS_PATH_COMMAND=npm install && npm run start
```
- Open your project on Gitea: ## 📧 Email Notifications
- Choose "Setting"
<div align="center"><img src="https://i.ibb.co/QHsST4D/image.png" alt="webhook1" width="800"></div>
- Choose "Webhooks" and "Add Webhooks" The system sends email notifications when:
<div align="center"><img src="https://i.ibb.co/bKFpvbV/image.png" alt="webhook2" width="800"></div> - New repository events occur
- Build process succeeds/fails
- Errors occur during processing
- Fill in the information ## 🔍 Monitoring and Troubleshooting
<div align="center"><img src="https://i.ibb.co/GJ55RDr/image.png" alt="webhook3" width="800"></div>
- Target URL: URL to the API that handles requests when a event is triggered (Default: your_domain/git/gitea-webhook). - View service logs:
- Trigger on: Event to trigger the webhook. ```bash
- Branch filter: Events will be listened on the branch you choose. ( '*' :all branch) journalctl -u giteaHook -f
```
#### ** Note: ** - Check service status:
```bash
systemctl status giteaHook
```
- Project gitea_CICD should be placed at the same folder level as your project ## 📝 Important Notes
``` 1. The `gitea_CICD` project should be placed at the same level as the project to be monitored
├── your_project 2. Ensure appropriate file and directory permissions
└── gitea_CICD project 3. Verify environment variables before running the service
``` 4. Use HTTPS for webhooks to ensure security
- Depending on the technology your project uses, the "gitea_CICD/service_run/giteaHook.sh" file will be custom configured to match the technology. ## 👨‍💻 Author
<div align="center"><h4><i>**____ Joseph Le____ **</i></h4></div> **Joseph Le** - [GitHub](https://github.com/joseph)
## 📄 License
This project is licensed under the ISC License.
---
<div align="center">
<sub>Built with ❤️ by Joseph Le</sub>
</div>

View File

View File

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

210
index.js
View File

@ -3,138 +3,112 @@ 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")
.filter((i) => i.includes("PORT_SERVICE"))[0] .find(line => line.includes("PORT_SERVICE"))
?.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 checkSendMail = contentFile const emailAddress = getConfigValue("RECEIVE_EMAIL_ADDRESS");
.split("\n") const emailFrom = getConfigValue("EMAIL_FROM") || "git@notification.com";
.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"];
const body = req.body; // Return response immediately
//console.log(body) res.status(200).send({ mess: "The event has been received!", data: req.body });
res console.log("STATUS:", checkStatus);
.status(200)
.send({ mess: "The event has been received!", data: req.body }); // Check if there is a running process
console.log("CHECK FILE", checkStatus);
if (checkStatus === "busy") { if (checkStatus === "busy") {
const transporter = nodeMailer.createTransport({ if (checkSendMail === "True") {
pool: true, const transporter = createTransporter();
host: "mail.ipsupply.com.au", const options = {
port: 465, from: emailFrom,
secure: true, to: emailAddress,
auth: { subject: "Git notifications (Fail)",
user: "admin@apactech.io", html: "<h3>There is an active build process. Please check and push again in a few minutes.</h3>",
pass: "BGK!dyt6upd2eax1bhz", };
}, return transporter.sendMail(options);
}); }
return;
const options = {
from: "admin@apactech.io",
to: emailAddress,
subject: "Git notifications (Fail)",
html:
"<h3>There is an active build process in the " +
FE_Path +
" directory. Please check and push again in a few minutes.</h3>",
};
return transporter.sendMail(options);
} else {
console.log("New event: " + giteaEvent);
// fs.writeFileSync("./service_run/checkFile", "true");
checkStatus="busy"
exec("./service_run/giteaHook.sh", (error, stdout, stderr) => {
let content = stdout !== "" ? stdout : stderr;
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);
}
});
} }
// 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
if (checkSendMail === "True") {
const transporter = createTransporter();
const options = {
from: emailFrom,
to: emailAddress,
subject: title,
html: `
<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>
<h4>Branch: ${req.body.ref || "N/A"}</h4>
${req.body.commits[0]?.url ? `<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.replace(/error|fail|warning/gi, match => `<span style="background-color:yellow;color:red;font-weight:bold">${match}</span>`)}</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,5 +1,10 @@
#!/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 *****|"
@ -27,11 +32,17 @@ 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#source .*#source $escaped_pwd_install/service_run/giteaService.conf#" $pwd_install/service_run/giteaHook.sh && sudo sed -i "s#NODE_BIN=.*#NODE_BIN=$NODE_BIN#" $pwd_install/service_run/giteaService.conf &&
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,7 +1,16 @@
#!/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"
@ -49,14 +58,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}') &&
# #
@ -82,25 +91,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 # npm install -f
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,7 +2,8 @@
# 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>
@ -14,22 +15,19 @@ 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=True SEND_EMAIL=False
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
# #
@ -39,6 +37,10 @@ FE_ROOT_FOLDER_PATH=</FE/public/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,59 +1,85 @@
#!/bin/bash #!/bin/bash
source /home/phuc/gitea_CICD/service_run/giteaService.conf set -e # Dừng script nếu có lỗi
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://##')"
cd "$PROJECT_PATH" && # Debug PATH nếu cần
# 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
git config --global --add safe.directory $HOME && # if ! command -v node &> /dev/null; then
# 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
SET_ORIGIN=$(git remote set-url origin $REPOSITORY_AUTH) && # # Kiểm tra npm tương tự
# if ! command -v npm &> /dev/null; then
# Ki?m tra xem Node.js đ? cài đ?t chưa # echo "npm not found in PATH, attempting to locate..."
if ! command -v node &> /dev/null; then # NPM_PATH=$(find /usr /opt /home -type f -name "npm" -executable 2>/dev/null | head -n 1)
echo -e "\e[31mNode.js is not installed.\e[0m" # if [ -x "$NPM_PATH" ]; then
echo -e "\e[32mInstall Node.js...\e[0m" # export PATH=$(dirname "$NPM_PATH"):$PATH
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - && # echo "Added $(dirname "$NPM_PATH") to PATH"
sudo apt-get install nodejs -y && # fi
node -v # fi
else
echo -e "\e[32mNodejs is installed!\e[0m" &&
node -v
fi
# Ki?m tra xem npm đ? cài đ?t chưa # if ! command -v npm &> /dev/null; then
if ! command -v npm &> /dev/null; then # echo -e "\e[41mnpm is not installed or not in PATH\e[0m"
echo -e "\e[31mnpm is not installed. Install npm...\e[0m" # exit 1
sudo apt-get install npm -y # else
else # echo -e "\e[32mnpm is installed!\e[0m"
echo -e "\e[32mnpm is installed!\e[0m" && # npm -v
npm -v # fi
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 "" echo -e "\e[41mError: Repository $GIT_REPOSITORY does not exist.\e[0m"
echo -e "\e[41mError: Repository $GIT_REPOSITORY not exists.\e[0m"
echo ""
exit 1 exit 1
fi fi
# Ki?m tra xem t?p index.js có t?n t?i không # Chạy index.js nếu tồn tại
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 install && $NPM_BIN install &&
node "$indexjs_path" $NODE_BIN "$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