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

240
README.md
View File

@ -1,183 +1,117 @@
# Gitea CICD Service
# gitea_CICD
<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>
<div align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Node.js_logo.svg" alt="NodeJS" width="300"></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.
### 🌟 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
```sh
git clone https://gitea.nswteam.net/joseph/gitea_CICD.git
```
2. **Create service_run directory and configure**
```bash
mkdir service_run
cp service/giteaService.conf service_run/giteaService.conf
```
### 2) Access the folder you just cloned
3. **Configure environment variables**
```bash
nano service_run/giteaService.conf
```
root@root#
```sh
cd gitea_CICD
```
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
### 3) Check the directory path
4. **Configure Nginx**
root@root#
```sh
pwd
```
- output: <path>/gitea_CICD
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;
}
```
### 4) Create folder service_run
Restart Nginx:
```bash
systemctl restart nginx
```
root@root#
5. **Install service**
```bash
./install.sh
```
```sh
mkdir service_run
```
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
2. Go to Settings > Webhooks
3. Click "Add Webhook"
4. Fill in the information:
- Target URL: `http://your-domain/git/gitea-webhook`
- Trigger on: Select events to monitor
- Branch filter: Enter branch to monitor (or '*' for all)
root@root#
```sh
nano service_run/giteaService.conf
```
## 📁 Directory Structure
### 6) Add Nginx configuration
- Open the Nginx configuration file.
```
gitea_CICD/
├── service/ # Service files directory
│ ├── giteaService.conf # Configuration template
│ ├── giteaService.sh # Main script
│ └── giteaHook.service # Systemd configuration
├── service_run/ # Runtime directory (created during installation)
├── index.js # Main webhook handler
├── install.sh # Installation script
└── README.md # Documentation
```
- Add thr following configuration content.
## 🔧 Customize Build Process
```
location /git/ {
#index index.html;
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;
}
```
You can customize the build process by adding environment variables in `giteaService.conf`:
- Change "IP-address" and "PORT". The "PORT" corresponds to the "PORT_SERVICE" of the "service_run/giteaService.conf" file.
```bash
# Syntax:
<name>_PROCESS_PATH=/path/to/directory
<name>_PROCESS_PATH_COMMAND=command1 && command2 ...
- Restart Nginx service.
```sh
systemctl restart nginx
```
### 7) Run file "install.sh" to install service
# Example:
FE_PROCESS_PATH=/home/project/frontend
FE_PROCESS_PATH_COMMAND=npm install && npm run build
root@root#
```sh
./install.sh
```
BE_PROCESS_PATH=/home/project/backend
BE_PROCESS_PATH_COMMAND=npm install && npm run start
```
<div align="center"><img src="https://i.ibb.co/VJHhb3y/install-Service.png" alt="install server" width="600"></div>
## 📧 Email Notifications
### 8) Add webhook
The system sends email notifications when:
- New repository events occur
- Build process succeeds/fails
- Errors occur during processing
- Open your project on Gitea:
- Choose "Setting"
<div align="center"><img src="https://i.ibb.co/QHsST4D/image.png" alt="webhook1" width="800"></div>
## 🔍 Monitoring and Troubleshooting
- Choose "Webhooks" and "Add Webhooks"
<div align="center"><img src="https://i.ibb.co/bKFpvbV/image.png" alt="webhook2" width="800"></div>
- View service logs:
```bash
journalctl -u giteaHook -f
```
- Fill in the information
<div align="center"><img src="https://i.ibb.co/GJ55RDr/image.png" alt="webhook3" width="800"></div>
- Check service status:
```bash
systemctl status giteaHook
```
- Target URL: URL to the API that handles requests when a event is triggered (Default: your_domain/git/gitea-webhook).
- Trigger on: Event to trigger the webhook.
- Branch filter: Events will be listened on the branch you choose. ( '*' :all branch)
## 📝 Important Notes
#### ** Note: **
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
3. Verify environment variables before running the service
4. Use HTTPS for webhooks to ensure security
- Project gitea_CICD should be placed at the same folder level as your project
## 👨‍💻 Author
```
├── your_project
└── gitea_CICD project
```
**Joseph Le** - [GitHub](https://github.com/joseph)
- Depending on the technology your project uses, the "gitea_CICD/service_run/giteaHook.sh" file will be custom configured to match the technology.
## 📄 License
This project is licensed under the ISC License.
---
<div align="center">
<sub>Built with ❤️ by Joseph Le</sub>
</div>
<div align="center"><h4><i>**____ Joseph Le____ **</i></h4></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 { exec } = require("child_process");
const nodeMailer = require("nodemailer");
// Read configuration file
const contentFile = fs.readFileSync("./service_run/giteaService.conf", "utf8");
let checkStatus = "ready";
// Get port from configuration file
let checkStatus = "ready"
// const checkFile = fs.readFileSync("./service_run/checkFile", "utf8");
const PORT = contentFile
.split("\n")
.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))
.filter((i) => i.includes("PORT_SERVICE"))[0]
?.split("=")[1]
.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.post("/git/gitea-webhook", async (req, res) => {
let title = "";
const checkSendMail = getConfigValue("SEND_EMAIL");
const emailAddress = getConfigValue("RECEIVE_EMAIL_ADDRESS");
const emailFrom = getConfigValue("EMAIL_FROM") || "git@notification.com";
const checkSendMail = contentFile
.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"];
// Return response immediately
res.status(200).send({ mess: "The event has been received!", data: req.body });
console.log("STATUS:", checkStatus);
// Check if there is a running process
const body = req.body;
//console.log(body)
res
.status(200)
.send({ mess: "The event has been received!", data: req.body });
console.log("CHECK FILE", checkStatus);
if (checkStatus === "busy") {
if (checkSendMail === "True") {
const transporter = createTransporter();
const options = {
from: emailFrom,
to: emailAddress,
subject: "Git notifications (Fail)",
html: "<h3>There is an active build process. Please check and push again in a few minutes.</h3>",
};
return transporter.sendMail(options);
}
return;
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: "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, () => {
console.log("Service is running on port", PORT);
console.log("Service is running on port ", PORT);
});

View File

@ -1,10 +1,5 @@
#!/bin/bash
NODE_BIN=$(which node)
NPM_BIN=$(which npm)
echo $NODE_BIN
echo $NPM_BIN
if [ -d "/etc/systemd/system" ]; then
echo "|---------------------------|"
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 &&
echo -e "* \e[32mHOOK_PATH\e[0m *" &&
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 &&
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 ""
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

View File

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

View File

@ -2,8 +2,7 @@
# The variable is automatically filled in by the system
HOOK_PATH=/home/gitea_CICD
NODE_BIN=/path/to/node
NPM_BIN=/path/to/npm
# Git account (*)
GIT_USERNAME=<your_username>
GIT_PASSWORD=<your_password>
@ -15,19 +14,22 @@ GIT_BRANCH=<your_branch>
PORT_SERVICE=5000
# Email: Used to send notifications when the repository has updates (*)
EMAIL_ADDRESS=<youremail>
# Enable/Disable send mail: True or False (*)
SEND_EMAIL=False
RECEIVE_EMAIL_ADDRESS=<youremail>
EMAIL_FROM=
EMAIL_HOST=
EMAIL_PORT=
EMAIL_SECURE=True
EMAIL_USER=
EMAIL_PASSWORD=
SEND_EMAIL=True
# URL of project directory (*)
# Example: /home/My_project/
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
#
@ -37,10 +39,6 @@ PROJECT_PATH=</project/directory/path>
#
# 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(*)
#BE_PROCESS_PATH=/home/My_project/BE_directory
#BE_PROCESS_PATH_COMMAND=npm install && echo "\n" && echo "BACK_END"

View File

@ -1,85 +1,59 @@
#!/bin/bash
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
source /home/phuc/gitea_CICD/service_run/giteaService.conf
export HOME=$PROJECT_PATH
indexjs_path="$HOOK_PATH/index.js"
project_path="$HOOK_PATH"
# Đường dẫn tới tệp index.js
indexjs_path=$HOOK_PATH/index.js
project_path=$HOOK_PATH
USERNAME=$(echo "$GIT_USERNAME" | sed 's/@/%40/g')
PASSWORD=$(echo "$GIT_PASSWORD" | sed 's/@/%40/g')
REPOSITORY_AUTH="https://$USERNAME:$PASSWORD@$(echo $GIT_REPOSITORY | sed 's#https://##')"
# 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
cd "$PROJECT_PATH" &&
# 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
git config --global --add safe.directory $HOME &&
# # Kiểm tra npm tương tự
# if ! command -v npm &> /dev/null; then
# echo "npm not found in PATH, attempting to locate..."
# NPM_PATH=$(find /usr /opt /home -type f -name "npm" -executable 2>/dev/null | head -n 1)
# if [ -x "$NPM_PATH" ]; then
# export PATH=$(dirname "$NPM_PATH"):$PATH
# echo "Added $(dirname "$NPM_PATH") to PATH"
# fi
# fi
SET_ORIGIN=$(git remote set-url origin $REPOSITORY_AUTH) &&
# if ! command -v npm &> /dev/null; then
# echo -e "\e[41mnpm is not installed or not in PATH\e[0m"
# exit 1
# else
# echo -e "\e[32mnpm is installed!\e[0m"
# npm -v
# fi
# Ki?m tra xem Node.js đ? cài đ?t chưa
if ! command -v node &> /dev/null; then
echo -e "\e[31mNode.js is not installed.\e[0m"
echo -e "\e[32mInstall Node.js...\e[0m"
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - &&
sudo apt-get install nodejs -y &&
node -v
else
echo -e "\e[32mNodejs is installed!\e[0m" &&
node -v
fi
cd "$PROJECT_PATH"
git config --global --add safe.directory "$HOME"
git remote set-url origin "$REPOSITORY_AUTH"
# Ki?m tra xem npm đ? cài đ?t chưa
if ! command -v npm &> /dev/null; then
echo -e "\e[31mnpm is not installed. Install npm...\e[0m"
sudo apt-get install npm -y
else
echo -e "\e[32mnpm is installed!\e[0m" &&
npm -v
fi
if git ls-remote -q --exit-code "$REPOSITORY_AUTH" > /dev/null; then
echo -e "\e[32mOK: Repository $GIT_REPOSITORY exists\e[0m"
sleep 1
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
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
echo "Run file $indexjs_path..."
echo $NPM_BIN
echo $NODE_BIN
export PATH="$(dirname $NODE_BIN):$PATH"
cd "$project_path" &&
$NPM_BIN install &&
$NODE_BIN "$indexjs_path"
npm install &&
node "$indexjs_path"
else
echo -e "\e[31mFile $indexjs_path not exists\e[0m"
exit 1
fi