Giter Site home page Giter Site logo

derpixler / git-tag-release-automator Goto Github PK

View Code? Open in Web Editor NEW
4.0 4.0 0.0 58 KB

Automated script for Git release tagging and creation of release branches for major and minor versions. Fetches latest Git tag and prompts user to update major, minor, or patch version. Creates new Git tag and release branch, e.g. "release/v1.1.0", and pushes it to the remote repository if no release branch is available.

License: GNU General Public License v3.0

Shell 100.00%
hacktoberfest

git-tag-release-automator's Introduction

Hello,

as an experienced traveller in the digital age, I support companies on their journey into the abysses of the digital worlds and stand by them through all their challenges. Together we will find solutions and overcome obstacles to make your ideas a reality.

I'm René Reimann with 17 years of experience as a full-stack software developer using PHP, Docker, JavaScript, CSS & HTML to create your software solution.

git-tag-release-automator's People

Contributors

derpixler avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

git-tag-release-automator's Issues

Improve Error Handling

Error handling is a critical aspect of scripting to ensure that the script behaves predictably and gracefully when unexpected situations or errors occur. In the provided script, there is minimal error handling, and certain Git commands are assumed to always succeed. The script lacks proper error handling. For example, it assumes that certain Git commands (e.g., git fetch, git push) will always succeed without checking for errors.

Here are some specific points regarding error handling in the script:

  • Assumption of Git Command Success: For example, commands like git fetch, git tag, and git push are executed without checking their return codes (exit statuses). If any of these commands fail, the script will continue executing, potentially causing further issues or unexpected behavior.

  • Silencing Errors: Several Git commands have their standard error (stderr) redirected to /dev/null, effectively silencing any error messages. While this can reduce console output, it also hides potential issues that should be addressed.

  • No Error Checking for git branch -d: The script attempts to delete a branch using git branch -d, but this command is not checked for success or failure. If the branch deletion fails, there's no indication or handling of the failure.

  • Missing Branch Name Checks: Functions like release_branch_exists or switch_branch don't adequately check if the branch name passed to them is valid or exists. This can lead to unexpected behavior or errors.

To improve error handling:

  • Check Return Codes: After executing a command, check its return code using $? and take appropriate actions based on success or failure (e.g., using if statements).

  • Display Error Messages: When an error occurs, display informative error messages to the user to indicate what went wrong and how to proceed.

  • Fail Safely: If a critical command fails (e.g., Git operations), consider terminating the script or taking appropriate actions to prevent further unexpected behavior.

  • Handle Invalid Input: Validate user input to ensure it meets expected criteria and provide clear instructions if the input is invalid.

  • Logging: Consider implementing logging mechanisms to record errors, warnings, and other important information for future reference and debugging.

Examples:

function create_and_push_git_tag() {
    # ... (existing code)

    # Check if tag creation and push were successful
    if [ $? -eq 0 ]; then
      echo "❯ Git tag $new_tag created and pushed successfully."
    else
      echo "❯ Failed to create and push Git tag $new_tag."
      exit 1
    fi
}

Input Validation

Input from the user is not thoroughly validated. It assumes that the user will always provide valid input, leading to potential errors or unexpected behavior if invalid input is provided. We are addressing the issue related to error handling for the git branch -d command. The original script used this command to attempt deleting a Git branch, but there was no error handling or informative messages in case of failure.

To improve this, we'll add error handling and provide clear messages indicating whether the branch deletion was successful or not at the switch_branch() method.

Example:

function switch_branch() {
    local branch=${1:-main}
    if [ "$branch" == "main" ]; then
        if git rev-parse --verify main >/dev/null 2>&1; then
            branch="main"
        elif git rev-parse --verify master >/dev/null 2>&1; then
            branch="master"
        else
            echo "❯ The branch $branch does not exist locally."
            exit 1
        fi
    else
        branch=$(echo $branch | sed 's/^origin\///')
    fi

    git checkout $branch > /dev/null 2>&1

    # Check if branch switch was successful
    if [ $? -eq 0 ]; then
        echo "❯ Switched to branch $branch successfully."
    else
        echo "❯ Failed to switch to branch $branch."
        exit 1
    fi
}

Global Variables

The script uses several global variables, which can lead to unintended side effects and can make the script harder to understand and maintain. Consider passing necessary values as function arguments instead.

we'll address the issue related to handling invalid user input. The original script prompts the user for input without proper validation or clear instructions on the expected input format.

To improve this, we'll add input validation and provide clear instructions to the user on how to input valid options.

Example:

# ... (existing code)

echo "Which part of the version do you want to increase: Major (M), minor (m) or patch (p)?"
read -n 1 -r -p "Your choice: " choice
echo

case $choice in
    M|m)
        new_tag_number=$(echo $tag_latest | awk -F. '{ printf("%d.%d.%d", $1 + 1, 0, 0) }')
        ;;
    m)
        new_tag_number=$(echo $tag_latest | awk -F. '{ printf("%d.%d.0", $1, $2 + 1) }')
        ;;
    p)
        new_tag_number=$(echo $tag_latest | awk -F. '{ printf("%d.%d.%d", $1, $2, $3 + 1) }')
        ;;
    *)
        echo "Invalid input. Please choose a valid option: M, m, or p."
        exit 1
        ;;
esac

# ... (existing code)

In this modified part of the script, after presenting the user with the options (Major, Minor, or Patch), we use a case statement to check the user's input ($choice). If the input matches one of the valid options, the script proceeds accordingly. If the input is invalid (doesn't match any option), the script prints an error message and exits.

This change ensures that the script validates the user's input and provides clear instructions on how to input valid options, improving the user experience and reducing the likelihood of erroneous input causing unexpected behavior.

Enhance Logging Implementation for Improved Logging and Maintenance

Logging is an essential aspect of script development, aiding in the identification of crucial events, errors, and behaviors during script execution. The current logging implementation provides a foundation for basic logging functionalities. However, there are opportunities to enhance the implementation for better logging practices, improved maintainability, and efficient log file management.

Proposed Enhancements:

  • Improved Log File Naming:
    Enhance the log file naming convention to include a timestamp in addition to the date, providing finer granularity for log files.

  • Consistent Log Format:
    Standardize the log message format, incorporating key details such as log level, timestamp, and the actual log message for a clearer and consistent log structure.

  • Log Level Classification:
    Implement a log level classification (e.g., INFO, ERROR, DEBUG) for log messages to differentiate between different severity levels, aiding in effective log analysis.

  • Logging to Separate Files per Day:
    Modify the logging mechanism to create separate log files for each day, enhancing log organization and readability.

  • Automated Log Cleanup:
    Introduce an automated log cleanup mechanism to regularly delete older log files, maintaining log directory cleanliness and preventing excessive log file accumulation.

  • Configurable Log Directory and Permissions:
    Make the log directory configurable to allow users to specify their preferred log directory. Additionally, enhance the script to set appropriate permissions and ownership for the log directory dynamically.

  • User Configuration for Days to Keep Logs:
    Implement user-configurable settings to define the number of days to keep log files, allowing users to tailor log retention based on their specific requirements.

Steps to Implement:

  • Refactor the log function to incorporate the proposed log message format and log level classification.
  • Update the log file naming convention to include a timestamp for each log file.
  • Modify the log function to dynamically create log files based on the current date.
  • Implement an automated log cleanup mechanism to delete log files older than the specified number of days.
  • Allow users to configure the log directory and permissions according to their preferences.
  • Enhance the script to provide an option for users to customize the number of days to retain log files.

Expected Outcome:

The enhanced logging implementation will result in a more robust and configurable logging system, providing users with greater control over log file management, improved log readability, and flexibility in configuring log settings. These enhancements will contribute to a more efficient and maintainable logging solution for script development and debugging.

Example implementation:

LOG_DIR="logs"

function initialize_logging() {
    # Create a log directory if it doesn't exist
    mkdir -p "$LOG_DIR"

    # Set appropriate permissions for the log directory
    chmod 700 "$LOG_DIR"

    # Set appropriate ownership for the log directory
    chown user:group "$LOG_DIR"
}

function log() {
    local log_message="$1"
    local log_file="$LOG_DIR/$(date '+%Y-%m-%d').log"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $log_message" >> "$log_file"
}

function cleanup_old_logs() {
    # Delete log files older than a certain number of days
    local days_to_keep=7  # Change this value as needed

    find "$LOG_DIR" -type f -name "*.log" -mtime +"$days_to_keep" -exec rm {} \;
}

# ... (existing code)

# Usage of log function
log "Script started."

# ... (existing code)

# Usage of log function
log "Script completed."

# Clean up old log files
cleanup_old_logs
  • Log Directory:
    We've introduced a LOG_DIR variable to specify the directory where log files will be stored. This helps keep the script organized. In the initialize_logging function, after creating the log directory, we set the appropriate permissions and ownership for the log directory.

    • We've added a line to set appropriate permissions for the log directory (chmod 700) to restrict access to the owner only.
    • We've added a line to set appropriate ownership for the log directory (chown user:group) to assign ownership to the intended user and group.
  • Initialize Logging:
    We added an initialize_logging function to create the log directory if it doesn't exist. This is called at the beginning of the script.

  • Log File per Day:
    The log function now creates a log file for each day in the format "YYYY-MM-DD.log" within the specified log directory.

  • Log Cleanup:
    We introduced a cleanup_old_logs function to remove log files older than a specified number of days (days_to_keep). This helps prevent an accumulation of log files over time.

To adjust the number of days to keep logs, modify the days_to_keep variable in the cleanup_old_logs function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.