Posts tagged with “bash”

Introducing changesummary: A Git Change Summary Script

The changesummary script is a powerful tool for developers to quickly understand the key changes made between two Git commits. It leverages AI to analyze the diff and provide a concise summary of the modifications.

Functionality

The script takes one or two arguments: the start commit hash and an optional end commit hash. If the end commit hash is not provided, it defaults to HEAD.

Usage

To use changesummary, simply run it in your Git Bash terminal:

./changesummary <start_commit_hash> [<end_commit_hash>]

Example

./changesummary abc123 def456

Result:

The key changes between the specified commit hashes are:

* Renamed `TrmWithRiaSettlementPricingTask` to `TrmWithRiaDetailsPricingTask` and refactored its logic into a base class `TrmConfigPricingTaskBase`.
* Removed `RiaRawRateDataDecorator` and updated `TrmWithRiaDetailsPricingTask` to use `RiaRate` instead of `RiaRawRate`.
* Updated the `RequiredData` enum to remove `RiaRawRate` and updated the `TrmWithRiaDetailsPricingTask` to require `RiaRate`.
* Updated error codes and messages to reflect the changes.

These changes simplify the pricing task logic and improve maintainability.

Benefits

  • Provides a quick and meaningful summary of changes, saving time during code reviews.
  • Helps in understanding the impact of changes made between commits.
  • Easy to integrate into existing Git workflows.
  • Flexible comparison range with optional end commit hash.

By using changesummary, developers can streamline their code review process and focus on the most important changes.

here's the source code:

#!/bin/bash

# Check if commit hash is provided
if [ -z "$1" ]; then
    echo "Error: Commit hash is required as an argument."
    exit 1
fi

convert_to_uppercase() {
    # Enable case-insensitive matching
    shopt -s nocasematch
    
    if [[ $1 =~ ^(HEAD|FETCH_HEAD|ORIG_HEAD|MERGE_HEAD)(\~[0-9]+|\^[0-9]*)* ]]; then
        # Convert to uppercase
        echo "${1^^}"
    else
        # Return original string
        echo "$1"
    fi
    
    # Reset case-sensitivity to default
    shopt -u nocasematch
}

start_hash=$(convert_to_uppercase "$1")
end_hash=$(convert_to_uppercase "${2:-HEAD}")

# Define static prompt text
static_prompt=$(cat <<-END
Analyze the following code diff. Generate a concise summary (under 100 words) of the **key changes** made between the specified commit hashes. Present the changes in a bullet-point list format, focusing on the main modifications and their impact.
Code changes:
END
)

# Define model and system message variables
model="meta-llama/llama-4-maverick:free"
system_message="You are a programmer"

# Execute git diff and pipe its output to the AI model
git diff -w -b $start_hash..$end_hash | jq -R -s --arg model "$model" --arg system_content "$system_message" --arg static_prompt "$static_prompt" \
    '{
        model: $model,
        messages: [
            {role: "system", content: $system_content},
            {role: "user", content: ($static_prompt + .) }
        ],
        max_tokens: 16384,
        temperature: 0
    }' | curl -s --request POST \
        --url https://openrouter.ai/api/v1/chat/completions \
        --header "Authorization: Bearer $OR_FOR_CI_API_KEY" \
        --header "Content-Type: application/json" \
        --data-binary @- | jq -r '.choices[0].message.content'

Simplify MySQL Connections with a Smarter Bash Function

Working with multiple MySQL environments is a common scenario for developers. Whether you're connecting to development, staging, or production databases, you often need different connection parameters for each environment. While MySQL's configuration files help manage these connections, switching between them can be cumbersome. Let me introduce a simple but powerful bash function that will streamline this process.

The Problem

If you work with MySQL regularly, you likely have multiple connection profiles defined in your ~/.my.cnf file using the [group] syntax. To use a specific configuration group, you need to use the --defaults-group-suffix option:

mysql --defaults-group-suffix=dev
mysql --defaults-group-suffix=prod

This works, but it's verbose and typo-prone.

The Solution: A Smarter Bash Function

Here's a bash function that makes working with MySQL much more convenient:

m() {
    if [ $# -eq 0 ]; then
        # If no arguments provided, run mysql directly
        mysql
    elif [[ "$1" == -* ]]; then
        # If first argument starts with -, pass all arguments directly to mysql
        mysql "$@"
    else
        # Otherwise, treat first argument as suffix
        local suffix=$1
        shift
        mysql --defaults-group-suffix=$suffix "$@"
    fi
}

How It Works

This function provides three different behaviors depending on how you call it:

  1. No arguments: Simply runs the MySQL client with default settings.

    m
    
  2. First argument starts with a dash: Passes all arguments directly to MySQL, just like you're using the mysql command.

    m -e "SHOW DATABASES"
    
  3. First argument doesn't start with a dash: Uses the first argument as the defaults-group-suffix and passes the remaining arguments to MySQL.

    m dev -e "SELECT * FROM users"
    

Practical Examples

Example 1: Connect to Different Environments

m dev    # Connect to development database
m prod   # Connect to production database
m stage  # Connect to staging database

Example 2: Run Commands Directly

m dev -e "SELECT COUNT(*) FROM orders"
m prod -N -e "SELECT id FROM customers LIMIT 5"  # -N removes column names

Example 3: Use MySQL Options Directly

m -N -e "SELECT VERSION()"  # Quick query without environment prefix
m -t -e "SHOW TABLES"  # Table format output

Setup Instructions

  1. Add the function to your .bashrc or .zshrc file.
  2. Set up your MySQL configuration groups in ~/.my.cnf:
[client]
# Default settings

[clientdev]
user=devuser
password=devpass
host=dev-db.example.com

[clientprod]
user=produser
password=prodpass
host=prod-db.example.com

[mysql]
database=YourDataBase
  1. Source your shell configuration file or restart your terminal.

Benefits

  • Brevity: No need to type connection parameters (-h, -u, -p) repeatedly, as they're stored in your config file.
  • Flexibility: Pass any MySQL options like -N (skip column names) or -e (execute) alongside environment selection.
  • Consistency: Maintain the standard MySQL command syntax for direct option usage.

This simple function has saved me countless keystrokes and made database work significantly smoother. It's especially handy for running quick queries with options like -e (execute) and -N (no headers) without having to type connection details every time. Give it a try in your workflow—small improvements like this add up to a much more efficient development experience!

Do you have any favorite shell functions that make your development life easier? Share them in the comments!

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