Posts tagged with “bash”

AI Prompt for Git Commit Messages

Analyze the following code changes and generate a concise, meaningful git commit message that:

1. Summarizes the main purpose or impact of the changes
2. Is no longer than 100 characters (150 characters maximum if absolutely necessary)
3. Uses present tense and imperative mood (e.g., "Add feature" not "Added feature")
4. Focuses on the "what" and "why" rather than the "how"

Provide ONLY the commit message itself, without any additional text, explanations, or formatting.

Code changes:

I have used it in my bash script ci and it works very well! ...

Set Up a 2GB Swap on a Remote VPS with a Simple Script

Running a small VPS with limited memory can be frustrating, especially when processes get killed due to low memory. A quick and easy way to help prevent this is by setting up a swap file.

This script will

  1. Checks if swap already exists on the remote machine.
  2. If not, it creates a 2GB swap file and enables it.
  3. Adds the swap file to /etc/fstab to make it permanent.

The script uses scp to copy a temporary script to the remote machine and ssh to execute it. Here’s the full script:

#!/bin/bash

# Check if machine name is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <machine-name>"
  exit 1
fi

REMOTE_MACHINE=$1
SWAPFILE=/swapfile
SIZE=2048

# Generate remote script content
REMOTE_SCRIPT=$(cat <<EOF
#!/bin/bash
if swapon --show | grep -q "$SWAPFILE"; then
  echo "Swap is already enabled on $SWAPFILE"
  exit 0
fi

sudo dd if=/dev/zero of=$SWAPFILE bs=1M count=$SIZE
sudo chmod 600 $SWAPFILE
sudo mkswap $SWAPFILE
sudo swapon $SWAPFILE

if ! grep -q "$SWAPFILE" /etc/fstab; then
  echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
fi
free -h
EOF
)

# Save remote script locally
echo "$REMOTE_SCRIPT" > /tmp/create_swap.sh

# Copy script to remote machine and execute it
scp /tmp/create_swap.sh $REMOTE_MACHINE:/tmp/
ssh $REMOTE_MACHINE "bash /tmp/create_swap.sh"

# Cleanup
ssh $REMOTE_MACHINE "rm /tmp/create_swap.sh"

How It Works

  • The script checks if the swap file already exists by running swapon --show on the remote machine.
  • If swap is already enabled, it exits.
  • Otherwise, it creates a 2GB swap file (/swapfile), sets the right permissions, and adds it to /etc/fstab so it’s automatically enabled after a reboot.

Usage

  1. Save the script as create_swap.sh and make it executable:

    chmod +x create_swap.sh
    
  2. Run the script with the remote machine name:

    ./create_swap.sh <remote-machine>
    

And that's it! The script takes care of everything for you, ensuring your VPS has a swap file ready to handle memory spikes.

Build command for deploying your flutter web app to cloudflare pages

set -x && if cd flutter; then git pull && cd .. ; else git clone https://github.com/flutter/flutter.git; (cd flutter && git fetch --tags && git checkout 3.22.3); fi && ls && flutter/bin/flutter doctor && flutter/bin/flutter clean && flutter/bin/flutter config --enable-web && cp .env.production .env && sed -i "s/VERSION_PLACEHOLDER/`git rev-parse --short HEAD`/" .env && flutter/bin/flutter build web --web-renderer html --base-href="/" --release

A bash script `ci` to help you write commit message and commit with OPEN AI/Groq API

Writing commit message could be time-consuming if you want a good summrize. ChatGPT just released their cheapest but still powerful model gpt-4o-mini, we can use it to save our time and keep the commit message accurate.

Attention

I refine the following script time by time and keep the latest version on github. Click here to see the latest version!

You need to put your API KEY in environment variable OPENAI_API_KEY before running this script. You need to run git add first before running this ci script. If you don't want to bother adding first, change git diff --cached -w -b to git diff -w -b and add -a option in the commit command (the last line of the script)

#!/bin/bash

# Get git changes
changes=$(git diff --cached -w -b)

# Exit if no changes
if [ -z "$changes" ]; then
  echo "No changes to commit."
  exit 0
fi

# Set prompt template
prompt_template=$(cat <<-END
You are skilled at writing git commit messages and follow the conventional commits specification:

    refactor: for refactoring
    fix: for bug fixes
    minor: for minor changes
    ...

You will be given the changes from a 'git diff -w -b HEAD' command.
Please summarize all meaningful changes into one commit message, no more than 100 characters.
Respond only with the commit message. Do not mention unchanged aspects. Do not put doube quote in the message. Do not escape underscore characters.
DO REVISE THE MESSAGE THREE TIMES before sending it out. And again: no more than 100 characters!!!
Here are the changes:

END
)

prompt_template+="$changes"

# Build JSON request body using jq
request_body=$(jq -n --arg model "gpt-4o-mini-2024-07-18" --arg prompt "$prompt_template" \
  '{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 32768, seed: 45, temperature: 0}')

# Use curl to request the OpenAI API to generate a commit message
response=$(curl -s --request POST \
  --url https://api.openai.com/v1/chat/completions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header "Content-Type: application/json" \
  --data "$request_body")

# Extract commit message from the response
commit_message=$(echo "$response" | jq -r '.choices[0].message.content')

# Exit if the commit message is empty
if [ -z "$commit_message" ] || [ "$commit_message" == "null" ]; then
  echo 'failed to generate a commit message:'
  echo $response
  exit 1
fi

# Commit changes
git commit -m "$commit_message"
```bash
**2024-07-24 update**
## Free alternative provided by Groq

If you don't want to pay for the ChatGPT API, you can opt for the free alternative provided by [Groq](https://groq.com). To get started, simply sign up for a Groq account using Google Login. Once you've created your account, you can generate an API key by following this link: <https://console.groq.com/keys>. Finally, make a minor modification to your script, as outlined below.

Build JSON request body using jq

#request_body=$(jq -n arg model "gpt-4o-mini-2024-07-18" arg prompt "$prompt_template" \

'{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 50, seed: 45, temperature: 0}')

#response=$(curl -s --request POST \

--url https://api.openai.com/v1/chat/completions \

--header "Authorization: Bearer $OPENAI_API_KEY" \

--header "Content-Type: application/json" \

--data "$request_body")

request_body=$(jq -n arg model "mixtral-8x7b-32768" arg prompt "$prompt_template"
'{model: $model, messages: [{role:"system",content:"You are a programmer"},{role: "user", content: $prompt}], max_tokens: 32768, stream: false, temperature: 0, top_p: 1, stop: null}')

Use curl to request the OpenAI API to generate a commit message

response=$(curl -s request POST
url https://api.groq.com/openai/v1/chat/completions
header "Authorization: Bearer $GROQ_API_KEY"
header "Content-Type: application/json"
--data "$request_body")

A tip to ease the process creating new feature branch

We use feature/ticket-number-team-abbr as feature branch name, such as feature/mt-1234-axo at work.

If you mainly work with a huge repository. Everytime, you switch to the integration/main branch and run git pull before you create a feature branch, it would take a while as it needs to update your work directory and normally there are a lot of files changed.

I use a different way which is a little bit speedy. Whatever which branch you are now in, run

git fetch && git checkout -b feature/mt-xxxx-axo origin/integration 

It helps but I still need to type the above, which is still a lot of letters! So, I create a bash script to help me more,

see the following command nbi 38546

nbi 38546
remote: Enumerating objects: 22, done.
remote: Counting objects: 100% (22/22), done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 22 (delta 17), reused 22 (delta 17), pack-reused 0
Unpacking objects: 100% (22/22), 4.43 KiB | 5.00 KiB/s, done.
From github.com:Euronet-XE/DFX
   941796a8a..11f76bff7  feature/mt-38183-fugu -> origin/feature/mt-38183-fugu
 * [new branch]          feature/mt-39492-ice  -> origin/feature/mt-39492-ice
 * [new branch]          feature/mt-39744-ice-card -> origin/feature/mt-39744-ice-card
branch 'feature/mt-38546-axo' set up to track 'origin/integration'.
David.Wei @ /d/git/xemt-core/dfx - [feature/mt-38546-axo] $

what’s in this nbi script? here it is

cat ~/bin/nbi
#!/bin/bash

# Check if the current directory is a git repository
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
    echo "Error: Current directory is not a git repository."
    exit 1
fi

# Run git fetch to get the latest changes from the remote repository
git fetch

# Determine the action based on the script name
case "$(basename "$0")" in
    nbi)
        # Check if an argument is provided
        if [[ $# -eq 1 ]]; then
            # Run git checkout to create and switch to a new branch based on the integration branch
            git checkout -b "feature/mt-$1-axo" "origin/integration"
            exit $?
        else
            echo "Usage: $0 <anumber>"
            exit 1
        fi
        ;;
    nbm)
        # Check if an argument is provided
        if [[ $# -eq 1 ]]; then
            # Run git checkout to create and switch to a new branch based on the main branch
            git checkout -b "feature/mt-$1-axo" "origin/main"
            exit $?
        else
            echo "Usage: $0 <anumber>"
            exit 1
        fi
        ;;
    *)
        echo "Error: Unsupported script name."
        exit 1
        ;;
esac

why do I call it nbi ? haha, it is a ABBR from new branch from integration

Wait, why did I mention nbm in the script? Yes, you can copy this nbi script with name nbm , then using the nbm command it will work the same way with the repositories that use main as the integration branch.

Did you see? How lazy I am!

2024-07-22 Update: I also wrote another script sw to ease the switching branches operation:

#!/bin/bash

# Check if the user provided a number
if [ -z "$1" ]; then
  echo "Usage: sw <number>"
  exit 1
fi

# Construct the branch name
branch_name="feature/mt-$1-axo"

# Switch to the branch
git switch "$branch_name"

# Check if the switch was successful
if [ $? -eq 0 ]; then
  echo "Switched to branch '$branch_name'"
else
  echo "Failed to switch to branch '$branch_name'"
fi